PhraseModel.cxx 17.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
//=========================================================================
//  Copyright (c) Kitware, Inc.
//  All rights reserved.
//  See LICENSE.txt for details.
//
//  This software is distributed WITHOUT ANY WARRANTY; without even
//  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
//  PURPOSE.  See the above copyright notice for more information.
//=========================================================================
#include "smtk/view/PhraseModel.h"

#include "smtk/view/DescriptivePhrase.h"
13
#include "smtk/view/PhraseListContent.h"
14
#include "smtk/view/SubphraseGenerator.h"
15 16 17
#include "smtk/view/View.h"

#include "smtk/operation/Manager.h"
18
#include "smtk/operation/Operation.h"
19 20 21 22 23 24 25 26

#include "smtk/attribute/Attribute.h"
#include "smtk/attribute/ComponentItem.h"

#include "smtk/resource/Component.h"

#include "smtk/io/Logger.h"

27 28
#undef SMTK_PHRASE_DEBUG

29 30 31 32
namespace smtk
{
namespace view
{
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
namespace detail
{

// Sort paths from deepest to shallowest, then rear-most to front-most.
// Doing these things keeps us from invalidating paths when items are removed.
struct PathComp
{
  bool operator()(const std::vector<int>& a, const std::vector<int>& b) const
  {
    if (a.size() < b.size())
    {
      return false;
    }
    else if (a.size() > b.size())
    {
      return true;
    }
    std::size_t ii = 0;
    for (auto ai : a)
    {
      if (ai < b[ii])
      {
        return false;
      }
      else if (ai > b[ii])
      {
        return true;
      }
      ++ii;
    }
    return false; // a == b... neither is less than other.
  }
};
}

class PhraseDeltas : public std::set<std::vector<int>, detail::PathComp>
{
};
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

std::map<std::string, PhraseModel::ModelConstructor> PhraseModel::s_modelTypes;

bool PhraseModel::registerModelType(const std::string& typeName, ModelConstructor ctor)
{
  if (typeName.empty() || !ctor || s_modelTypes.find(typeName) != s_modelTypes.end())
  {
    return false;
  }
  s_modelTypes[typeName] = ctor;
  return true;
}

bool PhraseModel::unregisterModelType(const std::string& typeName)
{
  return s_modelTypes.erase(typeName) > 0;
}

PhraseModelPtr PhraseModel::create(const smtk::view::ViewPtr& viewSpec)
{
  if (!viewSpec || viewSpec->type().empty())
  {
    return nullptr;
  }
  auto entry = s_modelTypes.find(viewSpec->type());
  if (entry == s_modelTypes.end())
  {
    return nullptr;
  }
  return entry->second(viewSpec);
}

PhraseModel::PhraseModel()
{
105
  m_decorator = [](smtk::view::DescriptivePhrasePtr) {};
106 107 108 109 110 111 112
}

PhraseModel::~PhraseModel()
{
  this->resetSources();
}

113 114
bool PhraseModel::addSource(smtk::resource::ManagerPtr rsrcMgr, smtk::operation::ManagerPtr operMgr,
  smtk::view::SelectionPtr seln)
115 116 117
{
  for (auto source : m_sources)
  {
118
    if (source.m_rsrcMgr == rsrcMgr && source.m_operMgr == operMgr && source.m_seln == seln)
119 120 121 122 123
    {
      return false; // Do not add what we already have
    }
  }
  int rsrcHandle = rsrcMgr
124 125 126 127 128 129
    ? rsrcMgr->observers().insert(
        [this](Resource::Ptr rsrc, resource::EventType event) {
          this->handleResourceEvent(rsrc, event);
          return 0;
        },
        /*observeImmediately*/ true)
130 131
    : -1;
  int operHandle = operMgr
T.J. Corona's avatar
T.J. Corona committed
132
    ? operMgr->observers().insert(
133 134
        [this](Operation::Ptr op, operation::EventType event, Operation::Result res) {
          this->handleOperationEvent(op, event, res);
T.J. Corona's avatar
T.J. Corona committed
135 136
          return 0;
        })
137
    : -1;
138 139 140 141 142 143
  int selnHandle = seln
    ? seln->observe([this](const std::string& src,
                      smtk::view::SelectionPtr seln) { this->handleSelectionEvent(src, seln); },
        /*observeImmediately*/ true)
    : -1;
  m_sources.push_back(Source(rsrcMgr, operMgr, seln, rsrcHandle, operHandle, selnHandle));
144 145 146
  return true;
}

147 148
bool PhraseModel::removeSource(smtk::resource::ManagerPtr rsrcMgr,
  smtk::operation::ManagerPtr operMgr, smtk::view::SelectionPtr seln)
149 150 151
{
  for (auto it = m_sources.begin(); it != m_sources.end(); ++it)
  {
152
    if (it->m_rsrcMgr == rsrcMgr && it->m_operMgr == operMgr && it->m_seln == seln)
153 154 155
    {
      if (it->m_rsrcHandle >= 0)
      {
156
        it->m_rsrcMgr->observers().erase(it->m_rsrcHandle);
157 158 159
      }
      if (it->m_operHandle >= 0)
      {
T.J. Corona's avatar
T.J. Corona committed
160
        it->m_operMgr->observers().erase(it->m_operHandle);
161
      }
162 163 164 165
      if (it->m_selnHandle >= 0)
      {
        it->m_seln->unobserve(it->m_selnHandle);
      }
166 167 168 169 170 171 172 173 174 175 176 177 178
      m_sources.erase(it);
      return true;
    }
  }
  return false;
}

bool PhraseModel::resetSources()
{
  bool removedAny = false;
  while (!m_sources.empty())
  {
    auto src = m_sources.begin();
179
    if (this->removeSource(src->m_rsrcMgr, src->m_operMgr, src->m_seln))
180 181 182 183 184 185 186 187 188 189 190
    {
      removedAny = true;
    }
    else
    { // Failed to remove... you should not be here but perhaps we can prevent an infinite loop.
      m_sources.erase(m_sources.begin());
    }
  }
  return removedAny;
}

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
static void notifyRecursive(
  PhraseModel::Observer obs, DescriptivePhrasePtr parent, std::vector<int>& parentIdx)
{
  if (!parent || !parent->areSubphrasesBuilt())
  {
    return;
  }
  std::vector<int> range(2);
  DescriptivePhrases& children(parent->subphrases());
  range[0] = 0;
  range[1] = static_cast<int>(children.size());
  obs(parent, PhraseModelEvent::ABOUT_TO_INSERT, parentIdx, parentIdx, range);
  obs(parent, PhraseModelEvent::INSERT_FINISHED, parentIdx, parentIdx, range);
  parentIdx.push_back(0);
  for (auto child : children)
  {
    notifyRecursive(obs, child, parentIdx);
    ++parentIdx.back();
  }
  parentIdx.pop_back();
}

213 214 215 216 217 218 219 220 221 222 223
int PhraseModel::observe(Observer obs, bool immediatelyNotify)
{
  if (!obs)
  {
    return -1;
  }
  int handle = m_observers.empty() ? 0 : m_observers.rbegin()->first + 1;
  m_observers[handle] = obs;
  std::vector<int> parents;
  if (immediatelyNotify)
  {
224
    notifyRecursive(obs, this->root(), parents);
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
  }
  return handle;
}

bool PhraseModel::unobserve(int handle)
{
  return m_observers.erase(handle) > 0;
}

DescriptivePhrasePtr PhraseModel::root() const
{
  return DescriptivePhrasePtr();
}

void PhraseModel::handleSelectionEvent(const std::string& src, Selection::Ptr seln)
{
  (void)src;
  (void)seln;
}

245
void PhraseModel::handleResourceEvent(Resource::Ptr rsrc, smtk::resource::EventType event)
246
{
247
  std::cout << "      phrase " << (event == smtk::resource::EventType::ADDED ? "add" : "del")
248 249 250
            << " rsrc " << rsrc << " " << rsrc->location() << "\n";
}

251 252
int PhraseModel::handleOperationEvent(
  Operation::Ptr op, operation::EventType event, Operation::Result res)
253
{
254 255
  smtkDebugMacro(smtk::io::Logger::instance(), "      Phrase handler: op "
      << (event == operation::EventType::DID_OPERATE ? "ran" : "cre/pre") << " " << op);
256 257 258 259 260 261 262 263 264

  if (!op)
  {
    return 1;
  } // Every event should have an operator
  if (!res)
  {
    return 0;
  } // Ignore operator creation and about-to-operate events.
T.J. Corona's avatar
T.J. Corona committed
265
  if (event != operation::EventType::DID_OPERATE)
266 267 268 269 270
  {
    return 0;
  }

  // Find out which resource components were created, modified, or expunged.
271 272 273
  this->handleExpunged(op, res, res->findComponent("expunged"));
  this->handleModified(op, res, res->findComponent("modified"));
  this->handleCreated(op, res, res->findComponent("created"));
274 275 276
  return 0;
}

277 278 279 280 281 282 283 284 285 286
void PhraseModel::removeChildren(const std::vector<int>& parentIdx, int childRange[2])
{
  auto phr = this->root()->at(parentIdx);
  std::vector<int> removeRange{ childRange[0], childRange[1] };

  this->trigger(phr, PhraseModelEvent::ABOUT_TO_REMOVE, parentIdx, parentIdx, removeRange);
  phr->subphrases().erase(phr->subphrases().begin() + removeRange[0]);
  this->trigger(phr, PhraseModelEvent::REMOVE_FINISHED, parentIdx, parentIdx, removeRange);
}

287
void PhraseModel::handleExpunged(Operation::Ptr op, Operation::Result res, ComponentItemPtr data)
288 289 290
{
  (void)op;
  (void)res;
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

  if (!data)
  {
    return;
  }

  // By default, search all existing phrases for matching components and remove them.
  std::set<smtk::common::UUID> uuids;
  for (auto it = data->begin(); it != data->end(); ++it)
  {
    uuids.insert((*it)->id());
  }

  PhraseDeltas pd;

  // TODO: It would be more efficient to aggregate all deletions that share a
  // common path vector and update that path's children at once.
  this->root()->visitChildren([&uuids, &pd](DescriptivePhrasePtr phr, std::vector<int>& path) {
    auto comp = phr->relatedComponent();
    if (comp && uuids.find(comp->id()) != uuids.end())
    {
      pd.insert(path);
    }
    return 0;
  });

  for (auto idx : pd)
  {
    if (idx.empty())
    {
      continue;
    }

    int removeRange[2];
    removeRange[0] = idx.back();
    removeRange[1] = removeRange[0];
    idx.pop_back();
    this->removeChildren(idx, removeRange);
  }
330 331
}

332
void PhraseModel::handleModified(Operation::Ptr op, Operation::Result res, ComponentItemPtr data)
333 334 335 336 337 338 339 340 341
{
  (void)op;
  (void)res;

  if (!data)
  {
    return;
  }

342
  std::set<smtk::resource::PersistentObjectPtr> modified(data->begin(), data->end());
343 344 345 346 347 348 349 350 351 352 353 354 355 356
  auto rootPhrase = this->root();
  if (rootPhrase)
  {
    rootPhrase->visitChildren(
      [this, &modified](DescriptivePhrasePtr phr, const std::vector<int>& idx) -> int {
        if (modified.find(phr->relatedComponent()) != modified.end())
        {
          this->trigger(phr, PhraseModelEvent::PHRASE_MODIFIED, idx, idx, std::vector<int>());
        }
        return 0;
      });
  }
}

357
void PhraseModel::handleCreated(Operation::Ptr op, Operation::Result res, ComponentItemPtr data)
358
{
359 360
  (void)op;  // Ignore this in the general case but allow subclasses to special-case it.
  (void)res; // TODO: Different behavior when result is failure vs success?
361 362 363 364 365 366

  if (!data)
  {
    return;
  }

367 368 369 370 371 372 373 374
  auto rootPhrase = this->root();
  auto delegate = rootPhrase ? rootPhrase->findDelegate() : nullptr;
  if (!delegate)
  {
    return;
  }

  smtk::resource::PersistentObjectArray objects;
375 376
  for (auto cre = data->begin(); cre != data->end(); ++cre)
  {
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
    // std::cout << "    add " << (*cre)->id() << " somewhere\n";
    objects.push_back(*cre);
  }

  SubphraseGenerator::PhrasesByPath phrasesToInsert;
  delegate->subphrasesForCreatedObjects(objects, rootPhrase, phrasesToInsert);

  std::vector<int> insertRange{ 0, 0 };
  for (auto pathIt = phrasesToInsert.begin(); pathIt != phrasesToInsert.end();)
  {
    SubphraseGenerator::Path path = pathIt->first;
    auto parent = pathIt->second->parent();
    SubphraseGenerator::Path idx(
      path.begin(), path.begin() + path.size() - 1); // Index of parent, not phrase to be inserted.
    insertRange[0] = path.back();
    insertRange[1] = insertRange[0];

    DescriptivePhrases batch;
    batch.push_back(pathIt->second);
    for (++pathIt; pathIt != phrasesToInsert.end() && pathIt->first == path; ++pathIt)
    {
      batch.push_back(pathIt->second);
      ++insertRange[1];
    }
    this->trigger(parent, PhraseModelEvent::ABOUT_TO_INSERT, idx, idx, insertRange);
    auto& children = parent->subphrases();
    children.insert(children.begin() + path.back(), batch.begin(), batch.end());
    this->trigger(parent, PhraseModelEvent::INSERT_FINISHED, idx, idx, insertRange);
405 406 407 408
  }
}

void PhraseModel::updateChildren(
409
  smtk::view::DescriptivePhrasePtr src, DescriptivePhrases& next, const std::vector<int>& idx)
410
{
411
  if (!src)
412 413 414 415 416 417 418 419
  {
    smtkErrorMacro(smtk::io::Logger::instance(), "Null phrase list.");
    return;
  }

  std::map<DescriptivePhrasePtr, int> lkup;
  int ii = 0;
  std::set<int> unused;
420
  DescriptivePhrases& orig(src->subphrases());
421 422 423 424 425 426 427
  for (auto it = orig.begin(); it != orig.end(); ++it, ++ii)
  {
    unused.insert(ii);
    lkup[*it] = ii;
  }

  // Find mapping and subtract out the still-in-use phrases from unused.
428
  for (DescriptivePhrases::iterator it = next.begin(); it != next.end(); ++it)
429 430 431 432 433 434
  {
    auto oit = lkup.find(*it);
    if (oit != lkup.end())
    {
      unused.erase(oit->second);
    }
435 436 437 438
    else
    {
      // Run through the entire array to see if there are different instances
      // of the phrase that nonetheless behave identically.
439 440 441
      // Note that we might have phrases that are different instances
      // but identical in that they refer to the same component/resource/etc.,
      // hence the second test in the conditional below:
442 443
      for (auto it2 = orig.begin(); it2 != orig.end(); ++it2)
      {
444 445
        if ((it->get() == it2->get()) ||
          (it->get()->relatedObject() == it2->get()->relatedObject()))
446 447 448 449 450 451
        {
          *it = *it2;
          unused.erase(lkup[*it2]);
        }
      }
    }
452 453 454 455 456 457 458 459 460 461 462 463 464 465
  }

  // Now delete unused from model, starting at the back so we don't invalidate indices.
  std::vector<int> removalRange(2);
  for (auto uu = unused.rbegin(); uu != unused.rend(); ++uu)
  {
    auto u2 = uu;
    auto ug = u2;
    for (++u2; u2 != unused.rend() && (*u2 == (*ug - 1)); ++u2)
    {
      ug = u2;
    }
    removalRange[0] = *ug;
    removalRange[1] = *uu;
466
    this->trigger(src, PhraseModelEvent::ABOUT_TO_REMOVE, idx, idx, removalRange);
467
    orig.erase(orig.begin() + removalRange[0], orig.begin() + removalRange[1] + 1);
468
    this->trigger(src, PhraseModelEvent::REMOVE_FINISHED, idx, idx, removalRange);
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
    uu = ug;
  }

  // Update lkup to account for removed rows.
  int delta = 0;
  auto nxen = lkup.begin();
  for (auto entry = lkup.begin(); entry != lkup.end(); ++entry)
  {
    while (entry != lkup.end() && unused.find(entry->second) != unused.end())
    { // row is unused
      ++delta;
      nxen = entry;
      ++nxen;
      lkup.erase(entry);
      entry = nxen;
    }
    if (entry != lkup.end())
    { // row used... update as needed
      entry->second -= delta;
    }
489 490 491 492
    else
    {
      break;
    }
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
  }

  std::map<int, DescriptivePhrasePtr> insert;

  // Move rows that previously existed but are now ordered differently.
  // int destRow = static_cast<int>(lkup.size()) - 1;
  int iref = static_cast<int>(next.size()) - 1;
  for (auto it = next.rbegin(); it != next.rend(); ++it, --iref)
  {
    auto oit = lkup.find(*it);
    if (oit == lkup.end())
    { // Skip rows we need to create
      insert[iref] = *it;
      continue;
    }
    // Is this a batch of rows to move in sequence?
    // FIXME: TODO: Move rows!
  }

  // Finally, insert new phrases.
  std::vector<int> insertRange(2);
  DescriptivePhrases batch;
  std::map<int, DescriptivePhrasePtr>::iterator ib;
  for (ib = insert.begin(); ib != insert.end();)
  {
    batch.clear();
    batch.push_back(ib->second);
    auto ie = ib;
    auto prev = ie;
    for (++ie; ie != insert.end() && (ie->first == prev->first + 1); ++ie, ++prev)
    {
      batch.push_back(ie->second);
    }
    insertRange[0] = ib->first;
527
    insertRange[1] = prev->first;
528
    this->trigger(src, PhraseModelEvent::ABOUT_TO_INSERT, idx, idx, insertRange);
529
    orig.insert(orig.begin() + insertRange[0], batch.begin(), batch.end());
530
    this->trigger(src, PhraseModelEvent::INSERT_FINISHED, idx, idx, insertRange);
531 532 533 534 535 536 537 538
    ib = ie;
    if (ib != insert.end())
    {
      ++ib;
    }
  }
}

539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
void PhraseModel::decoratePhrase(smtk::view::DescriptivePhrasePtr phr) const
{
  m_decorator(phr);
}

bool PhraseModel::setDecorator(const PhraseDecorator& phraseDecorator)
{
  if (!phraseDecorator)
  {
    return false;
  }

  // TODO: Add warning if we already have phrases? Un-decorate and re-decorate?

  m_decorator = phraseDecorator;
  return true;
}

557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
void PhraseModel::triggerDataChanged()
{
  // It is possible the 2 lines below could work, but the feature is not well-documented in Qt:
  //   auto idx = this->root()->index();
  //   this->trigger(this->root(), PhraseModelEvent::PHRASE_MODIFIED, idx, idx, std::vector<int>());
  // Just to be safe, do it the long way:
  this->root()->visitChildren([this](DescriptivePhrasePtr phr, std::vector<int>& idx) -> int {
    this->trigger(phr, PhraseModelEvent::PHRASE_MODIFIED, idx, idx, std::vector<int>());
    return 0; // continue iterating.
  });
}

void PhraseModel::triggerDataChangedFor(smtk::resource::ComponentPtr comp)
{
  this->root()->visitChildren(
    [this, &comp](DescriptivePhrasePtr phr, std::vector<int>& idx) -> int {
      if (phr->relatedComponent() == comp)
      {
        this->trigger(phr, PhraseModelEvent::PHRASE_MODIFIED, idx, idx, std::vector<int>());
      }
      return 0; // continue iterating.
    });
}

581 582 583 584 585 586 587 588 589 590 591
int depth(DescriptivePhrasePtr phr)
{
  int dd = -1;
  while (phr)
  {
    ++dd;
    phr = phr->parent();
  }
  return dd;
}

592 593 594
void PhraseModel::trigger(DescriptivePhrasePtr phr, PhraseModelEvent event,
  const std::vector<int>& src, const std::vector<int>& dst, const std::vector<int>& arg)
{
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
#ifdef SMTK_PHRASE_DEBUG
  std::cout << "Phrase model update " << phr << " pdepth " << depth(phr) << " event "
            << static_cast<int>(event) << " src";
  for (auto ent : src)
  {
    std::cout << " " << ent;
  }
  std::cout << " dst";
  for (auto ent : dst)
  {
    std::cout << " " << ent;
  }
  std::cout << " arg";
  for (auto ent : arg)
  {
    std::cout << " " << ent;
  }
  std::cout << "\n";
  std::cout.flush();
#endif

616 617 618 619
  for (auto observer : m_observers)
  {
    observer.second(phr, event, src, dst, arg);
  }
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
  // Check to see if phrases we just inserted have pre-existing children. If so, trigger them.
  if (event == PhraseModelEvent::INSERT_FINISHED && phr && phr->areSubphrasesBuilt())
  {
    std::vector<int> range(2);
    DescriptivePhrases& children(phr->subphrases());
    range[0] = 0;
    for (int ci = arg[0]; ci <= arg[1]; ++ci)
    {
      if (!children[ci] || !children[ci]->areSubphrasesBuilt())
      {
        continue;
      }
      range[1] = static_cast<int>(children[ci]->subphrases().size());
      // Qt expects range to be closed, not half-open like the STL.
      // But it is possible to have subphrases built but be empty (size() == 0), so:
      if (range[1] == 0)
      {
        continue;
      }
      --range[1];
      std::vector<int> cpath = children[ci]->index();
      this->trigger(children[ci], PhraseModelEvent::ABOUT_TO_INSERT, cpath, cpath, range);
      this->trigger(children[ci], PhraseModelEvent::INSERT_FINISHED, cpath, cpath, range);
    }
  }
645 646 647
}
}
}