1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 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 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 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 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 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 578 579 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
|
/* This file is part of the KDE project
Copyright 2010 Marijn Kruisselbrink <mkruisselbrink@kde.org>
Copyright 2006-2007 Stefan Nikolaus <stefan.nikolaus@kdemail.net>
Copyright 2004 Tomas Mecir <mecirt@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
// Local
#include "DependencyManager.h"
#include "DependencyManager_p.h"
#include "Cell.h"
#include "CellStorage.h"
#include "Formula.h"
#include "FormulaStorage.h"
#include "Map.h"
#include "NamedAreaManager.h"
#include "Region.h"
#include "RTree.h"
#include "Sheet.h"
#include "Value.h"
#include "DocBase.h"
#include "ElapsedTime_p.h"
#include <QHash>
#include <QList>
#include <KoUpdater.h>
using namespace Calligra::Sheets;
// This is currently not called - but it's really convenient to call it from
// gdb or from debug output to check that everything is set up ok.
void DependencyManager::Private::dump() const
{
QMap<Cell, Region>::ConstIterator mend(providers.end());
for (QMap<Cell, Region>::ConstIterator mit(providers.begin()); mit != mend; ++mit) {
Cell cell = mit.key();
QStringList debugStr;
Region::ConstIterator rend((*mit).constEnd());
for (Region::ConstIterator rit((*mit).constBegin()); rit != rend; ++rit) {
debugStr << (*rit)->name();
}
kDebug(36002) << cell.name() << " consumes values of:" << debugStr.join(",");
}
foreach(Sheet* sheet, consumers.keys()) {
const QList< QPair<QRectF, Cell> > pairs = consumers[sheet]->intersectingPairs(QRect(1, 1, KS_colMax, KS_rowMax)).values();
QHash<QString, QString> table;
for (int i = 0; i < pairs.count(); ++i) {
Region tmpRange(pairs[i].first.toRect(), sheet);
table.insertMulti(tmpRange.name(), pairs[i].second.name());
}
foreach(const QString &uniqueKey, table.uniqueKeys()) {
QStringList debugStr(table.values(uniqueKey));
kDebug(36002) << uniqueKey << " provides values for:" << debugStr.join(",");
}
}
foreach(const Cell &cell, depths.keys()) {
QString cellName = cell.name();
while (cellName.count() < 4) cellName.prepend(' ');
kDebug(36002) << "depth(" << cellName << " ) =" << depths[cell];
}
}
DependencyManager::DependencyManager(const Map* map)
: d(new Private)
{
d->map = map;
}
DependencyManager::~DependencyManager()
{
qDeleteAll(d->consumers);
delete d;
}
void DependencyManager::reset()
{
d->reset();
}
void DependencyManager::regionChanged(const Region& region)
{
if (region.isEmpty())
return;
kDebug(36002) << "DependencyManager::regionChanged" << region.name();
Region::ConstIterator end(region.constEnd());
for (Region::ConstIterator it(region.constBegin()); it != end; ++it) {
const QRect range = (*it)->rect();
const Sheet* sheet = (*it)->sheet();
for (int col = range.left(); col <= range.right(); ++col) {
for (int row = range.top(); row <= range.bottom(); ++row) {
Cell cell(sheet, col, row);
const Formula formula = cell.formula();
// remove it and all its consumers from the reference depth list
d->removeDepths(cell);
// cell without a formula? remove it
if (formula.expression().isEmpty()) {
d->removeDependencies(cell);
continue;
}
d->generateDependencies(cell, formula);
}
}
}
{
ElapsedTime et("Computing reference depths", ElapsedTime::PrintOnlyTime);
d->generateDepths(region);
}
// d->dump();
}
void DependencyManager::namedAreaModified(const QString &name)
{
d->namedAreaModified(name);
}
void DependencyManager::addSheet(Sheet *sheet)
{
// Manages also the revival of a deleted sheet.
Q_UNUSED(sheet);
#if 0 // TODO Stefan: Enable, if dependencies should not be tracked all the time.
ElapsedTime et("Generating dependencies", ElapsedTime::PrintOnlyTime);
// Clear orphaned dependencies (i.e. cells formerly containing formulas)
// FIXME Stefan: Iterate only over the consumers in sheet. Needs adjustment
// of the way the providers are stored. Now: only by cell.
// Future: QHash<Sheet*, QHash<Cell, Region> >
const QList<Cell> consumers = d->providers.keys();
foreach(const Cell& cell, consumers) {
if (cell.sheet() == sheet) {
// Those cells may had got providing regions. Clear them first.
// TODO
// Clear this cell as provider.
d->providers.remove(cell);
}
}
Cell cell;
for (int c = 0; c < sheet->formulaStorage()->count(); ++c) {
cell = Cell(sheet, sheet->formulaStorage()->col(c), sheet->formulaStorage()->row(c));
d->generateDependencies(cell, sheet->formulaStorage()->data(c));
if (!d->depths.contains(cell)) {
int depth = d->computeDepth(cell);
d->depths.insert(cell , depth);
}
}
#endif
}
void DependencyManager::removeSheet(Sheet *sheet)
{
Q_UNUSED(sheet);
// TODO Stefan: Implement, if dependencies should not be tracked all the time.
}
void DependencyManager::updateAllDependencies(const Map* map, KoUpdater *updater)
{
ElapsedTime et("Generating dependencies", ElapsedTime::PrintOnlyTime);
// clear everything
d->providers.clear();
qDeleteAll(d->consumers);
d->consumers.clear();
d->namedAreaConsumers.clear();
d->depths.clear();
int cellsCount = 9;
if (updater) {
updater->setProgress(0);
foreach(const Sheet* sheet, map->sheetList())
cellsCount += sheet->formulaStorage()->count();
}
Cell cell;
int cellCurrent = 0;
foreach(const Sheet* sheet, map->sheetList()) {
for (int c = 0; c < sheet->formulaStorage()->count(); ++c, ++cellCurrent) {
cell = Cell(sheet, sheet->formulaStorage()->col(c), sheet->formulaStorage()->row(c));
d->generateDependencies(cell, sheet->formulaStorage()->data(c));
if (!sheet->formulaStorage()->data(c).isValid())
cell.setValue(Value::errorPARSE());
if (updater)
updater->setProgress(int(qreal(cellCurrent) / qreal(cellsCount) * 50.));
}
}
cellCurrent = 0;
foreach(const Sheet* sheet, map->sheetList()) {
for (int c = 0; c < sheet->formulaStorage()->count(); ++c, ++cellCurrent) {
cell = Cell(sheet, sheet->formulaStorage()->col(c), sheet->formulaStorage()->row(c));
if (!d->depths.contains(cell)) {
int depth = d->computeDepth(cell);
d->depths.insert(cell , depth);
}
if (updater)
updater->setProgress(50 + int(qreal(cellCurrent) / qreal(cellsCount) * 50.));
}
}
if (updater)
updater->setProgress(100);
}
QMap<Cell, int> DependencyManager::depths() const
{
return d->depths;
}
Calligra::Sheets::Region DependencyManager::consumingRegion(const Cell& cell) const
{
return d->consumingRegion(cell);
}
Calligra::Sheets::Region DependencyManager::reduceToProvidingRegion(const Region& region) const
{
Region providingRegion;
QList< QPair<QRectF, Cell> > pairs;
Region::ConstIterator end(region.constEnd());
for (Region::ConstIterator it(region.constBegin()); it != end; ++it) {
Sheet* const sheet = (*it)->sheet();
QHash<Sheet*, RTree<Cell>*>::ConstIterator cit = d->consumers.constFind(sheet);
if (cit == d->consumers.constEnd())
continue;
pairs = cit.value()->intersectingPairs((*it)->rect()).values();
for (int i = 0; i < pairs.count(); ++i)
providingRegion.add(pairs[i].first.toRect() & (*it)->rect(), sheet);
}
return providingRegion;
}
void DependencyManager::regionMoved(const Region& movedRegion, const Cell& destination)
{
Region::Point locationOffset(destination.cellPosition() - movedRegion.boundingRect().topLeft());
Region::ConstIterator end(movedRegion.constEnd());
for (Region::ConstIterator it(movedRegion.constBegin()); it != end; ++it) {
Sheet* const sheet = (*it)->sheet();
locationOffset.setSheet((sheet == destination.sheet()) ? 0 : destination.sheet());
QHash<Sheet*, RTree<Cell>*>::ConstIterator cit = d->consumers.constFind(sheet);
if (cit == d->consumers.constEnd())
continue;
QList<Cell> dependentLocations = cit.value()->intersects((*it)->rect());
foreach(const Cell &c, dependentLocations) {
updateFormula(c, (*it), locationOffset);
}
}
}
void DependencyManager::updateFormula(const Cell& cell, const Region::Element* oldLocation, const Region::Point& offset)
{
// Not a formula -> no dependencies
if (!cell.isFormula())
return;
const Formula formula = cell.formula();
// Broken formula -> meaningless dependencies
if (!formula.isValid())
return;
Tokens tokens = formula.tokens();
//return empty list if the tokens aren't valid
if (!tokens.valid())
return;
QString expression('=');
Sheet* sheet = cell.sheet();
foreach(const Token &token, tokens) {
//parse each cell/range and put it to our expression
if (token.type() == Token::Cell || token.type() == Token::Range) {
// FIXME Stefan: Special handling for named areas
const Region region(token.text(), sheet->map(), sheet);
//kDebug(36002) << region.name();
// the offset contains a sheet, only if it was an intersheet move.
if ((oldLocation->sheet() == region.firstSheet()) &&
(oldLocation->rect().contains(region.firstRange()))) {
const Region yetAnotherRegion(region.firstRange().translated(offset.pos()),
offset.sheet() ? offset.sheet() : sheet);
expression.append(yetAnotherRegion.name(sheet));
} else {
expression.append(token.text());
}
} else {
expression.append(token.text());
}
}
Cell(cell).parseUserInput(expression);
}
void DependencyManager::Private::reset()
{
providers.clear();
consumers.clear();
}
Calligra::Sheets::Region DependencyManager::Private::consumingRegion(const Cell& cell) const
{
QHash<Sheet*, RTree<Cell>*>::ConstIterator cit = consumers.constFind(cell.sheet());
if (cit == consumers.constEnd()) {
//kDebug(36002) << "No consumer tree found for the cell's sheet.";
return Region();
}
const QList<Cell> consumers = cit.value()->contains(cell.cellPosition());
Region region;
foreach(const Cell& c, consumers)
region.add(c.cellPosition(), c.sheet());
return region;
}
void DependencyManager::Private::namedAreaModified(const QString& name)
{
// since area names are something like aliases, modifying an area name
// basically means that all cells referencing this area should be treated
// as modified - that will retrieve updated area ranges and also update
// everything as necessary ...
QHash<QString, QList<Cell> >::ConstIterator it = namedAreaConsumers.constFind(name);
if (it == namedAreaConsumers.constEnd())
return;
Region region;
const QList<Cell> namedAreaConsumersList = it.value();
foreach(const Cell &c, namedAreaConsumersList) {
generateDependencies(c, c.formula());
region.add(c.cellPosition(), c.sheet());
}
generateDepths(region);
}
void DependencyManager::Private::removeDependencies(const Cell& cell)
{
// look if the cell has any providers
QMap<Cell, Region>::ConstIterator pit = providers.constFind(cell);
if (pit == providers.constEnd())
return; //it doesn't - nothing more to do
// first this cell is no longer a provider for all consumers
Region region = pit.value();
Region::ConstIterator end(region.constEnd());
for (Region::ConstIterator it(region.constBegin()); it != end; ++it) {
QHash<Sheet*, RTree<Cell>*>::ConstIterator cit = consumers.constFind((*it)->sheet());
if (cit != consumers.constEnd()) {
cit.value()->remove((*it)->rect(), cell);
}
}
// remove information about named area dependencies
QHash<QString, QList<Cell> >::Iterator nit(namedAreaConsumers.begin()), nend(namedAreaConsumers.end());
while (nit != nend) {
nit.value().removeAll(cell);
if (nit.value().isEmpty())
nit = namedAreaConsumers.erase(nit);
else
++nit;
}
// clear the circular dependency flags
removeCircularDependencyFlags(providers.value(cell), Backward);
removeCircularDependencyFlags(consumingRegion(cell), Forward);
// finally, remove the providers for this cell
providers.remove(cell);
}
void DependencyManager::Private::removeDepths(const Cell& cell)
{
QMap<Cell, int>::Iterator dit = depths.find(cell);
if (dit == depths.end())
return;
QHash<Sheet*, RTree<Cell>*>::ConstIterator cit = consumers.constFind(cell.sheet());
if (cit == consumers.constEnd())
return;
depths.erase(dit);
const QList<Cell> consumers = cit.value()->contains(cell.cellPosition());
foreach(const Cell &c, consumers)
removeDepths(c);
}
void DependencyManager::Private::generateDependencies(const Cell& cell, const Formula& formula)
{
//get rid of old dependencies first
removeDependencies(cell);
//new dependencies only need to be generated if the cell contains a formula
// if (cell.isNull())
// return;
// if (!cell.isFormula())
// return;
//now we need to generate the providing region
computeDependencies(cell, formula);
}
void DependencyManager::Private::generateDepths(const Region& region)
{
QSet<Cell> computedDepths;
Region::ConstIterator end(region.constEnd());
for (Region::ConstIterator it(region.constBegin()); it != end; ++it) {
const QRect range = (*it)->rect();
const Sheet* sheet = (*it)->sheet();
const CellStorage *cells = sheet->cellStorage();
int bottom = range.bottom();
if (bottom > cells->rows()) bottom = cells->rows();
int right = range.right();
if (right > cells->columns()) right = cells->columns();
for (int row = range.top(); row <= bottom; ++row) {
for (int col = range.left(); col <= right; ++col) {
Cell cell(sheet, col, row);
generateDepths(cell, computedDepths);
}
}
}
}
void DependencyManager::Private::generateDepths(Cell cell, QSet<Cell>& computedDepths)
{
static QSet<Cell> processedCells;
//prevent infinite recursion (circular dependencies)
if (processedCells.contains(cell) || cell.value() == Value::errorCIRCLE()) {
kDebug(36002) << "Circular dependency at" << cell.fullName();
cell.setValue(Value::errorCIRCLE());
depths.insert(cell, 0);
return;
}
if (computedDepths.contains(cell)) {
return;
}
// set the compute reference depth flag
processedCells.insert(cell);
int depth = computeDepth(cell);
depths.insert(cell, depth);
computedDepths.insert(cell);
// Recursion. We need the whole dependency tree of the changed region.
// An infinite loop is prevented by the check above.
QHash<Sheet*, RTree<Cell>*>::ConstIterator cit = consumers.constFind(cell.sheet());
if (cit == consumers.constEnd()) {
processedCells.remove(cell);
return;
}
const QList<Cell> consumers = cit.value()->contains(cell.cellPosition());
foreach (const Cell &c, consumers) {
generateDepths(c, computedDepths);
}
// clear the compute reference depth flag
processedCells.remove(cell);
}
int DependencyManager::Private::computeDepth(Cell cell) const
{
// a set of cell, which depth is currently calculated
static QSet<Cell> processedCells;
//prevent infinite recursion (circular dependencies)
if (processedCells.contains(cell) || cell.value() == Value::errorCIRCLE()) {
kDebug(36002) << "Circular dependency at" << cell.fullName();
cell.setValue(Value::errorCIRCLE());
return 0;
}
// set the compute reference depth flag
processedCells.insert(cell);
int depth = 0;
const Region region = providers.value(cell);
Region::ConstIterator end(region.constEnd());
for (Region::ConstIterator it(region.constBegin()); it != end; ++it) {
const QRect range = (*it)->rect();
Sheet* sheet = (*it)->sheet();
const int right = range.right();
const int bottom = range.bottom();
for (int col = range.left(); col <= right; ++col) {
for (int row = range.top(); row <= bottom; ++row) {
Cell referencedCell = Cell(sheet, col, row);
if (!providers.contains(referencedCell)) {
// no further references
// depth is one at least
depth = qMax(depth, 1);
continue;
}
QMap<Cell, int>::ConstIterator it = depths.constFind(referencedCell);
if (it != depths.constEnd()) {
// the referenced cell depth was already computed
depth = qMax(it.value() + 1, depth);
continue;
}
// compute the depth of the referenced cell, add one and
// take it as new depth, if it's greater than the current one
depth = qMax(computeDepth(referencedCell) + 1, depth);
}
}
}
//clear the computing reference depth flag
processedCells.remove(cell);
return depth;
}
void DependencyManager::Private::computeDependencies(const Cell& cell, const Formula& formula)
{
// Broken formula -> meaningless dependencies
if (!formula.isValid())
return;
const Tokens tokens = formula.tokens();
//return empty list if the tokens aren't valid
if (!tokens.valid())
return;
Sheet* sheet = cell.sheet();
int inAreasCall = 0;
Region providingRegion;
for (int i = 0; i < tokens.count(); i++) {
const Token &token = tokens[i];
if (inAreasCall) {
if (token.isOperator() && token.asOperator() == Token::LeftPar)
inAreasCall++;
else if (token.isOperator() && token.asOperator() == Token::RightPar)
inAreasCall--;
} else {
if (i > 0 && token.isOperator() && token.asOperator() == Token::LeftPar && tokens[i-1].isIdentifier() && QString::compare(tokens[i-1].text(), "AREAS", Qt::CaseInsensitive) == 0)
inAreasCall = 1;
//parse each cell/range and put it to our Region
if (token.type() == Token::Cell || token.type() == Token::Range) {
// check for named area
const bool isNamedArea = sheet->map()->namedAreaManager()->contains(token.text());
if (isNamedArea) {
// add cell as consumer of the named area
namedAreaConsumers[token.text()].append(cell);
}
// check if valid cell/range
Region region(token.text(), sheet->map(), sheet);
if (region.isValid()) {
if (isNamedArea) {
if ((i > 0 && tokens[i-1].isOperator()) || (i < tokens.count()-1 && tokens[i+1].isOperator())) {
// TODO: this check is not quite correct, to really properly determine if the entire range is referenced
// or just a single cell we would need to actually have the compile formula, not just the tokenized one
// basically this is the same logic as Formula::Private::valueOrElement
Region realRegion = region.intersectedWithRow(cell.row());
if (!realRegion.isEmpty()) {
region = realRegion;
}
}
}
// add it to the providers
providingRegion.add(region);
Sheet* sheet = region.firstSheet();
// create consumer tree, if not existing yet
QHash<Sheet*, RTree<Cell>*>::iterator it = consumers.find(sheet);
if (it == consumers.end()) {
it = consumers.insert(sheet, new RTree<Cell>());
}
// add cell as consumer of the range
it.value()->insert(region.firstRange(), cell);
}
}
}
}
// store the providing region
// NOTE Stefan: Also store cells without dependencies to avoid an
// iteration over all cells in a map/sheet on recalculation.
// empty region will be created automatically, if necessary
providers[cell].add(providingRegion);
}
void DependencyManager::Private::removeCircularDependencyFlags(const Region& region, Direction direction)
{
// a set of cells, which circular dependency flag is currently removed
static QSet<Cell> processedCells;
Region::ConstIterator end(region.constEnd());
for (Region::ConstIterator it(region.constBegin()); it != end; ++it) {
const QRect range = (*it)->rect();
const Sheet* sheet = (*it)->sheet();
for (int col = range.left(); col <= range.right(); ++col) {
for (int row = range.top(); row <= range.bottom(); ++row) {
Cell cell(sheet, col, row);
if (processedCells.contains(cell))
continue;
processedCells.insert(cell);
if (cell.value() == Value::errorCIRCLE())
cell.setValue(Value::empty());
if (direction == Backward)
removeCircularDependencyFlags(providers.value(cell), Backward);
else // Forward
removeCircularDependencyFlags(consumingRegion(cell), Forward);
processedCells.remove(cell);
}
}
}
}
#include "DependencyManager.moc"
|