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
|
/* This file is part of the KDE project
* Copyright (C) 2009 Ganesh Paramasivam <ganesh@crystalfab.com>
* Copyright (C) 2009 Pierre Stirnweiss <pstirnweiss@googlemail.com>
* Copyright (C) 2010 Thomas Zander <zander@kde.org>
* Copyright (C) 2012 C. Boemann <cbo@boemann.dk>
* Copyright (C) 2014-2015 Denis Kuplyakov <dener.kup@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.*/
#include "DeleteCommand.h"
#include <klocalizedstring.h>
#include <KoList.h>
#include <KoTextEditor.h>
#include <KoTextEditor_p.h>
#include <KoTextDocument.h>
#include <KoInlineTextObjectManager.h>
#include <KoTextRangeManager.h>
#include <KoAnchorInlineObject.h>
#include <KoAnchorTextRange.h>
#include <KoAnnotation.h>
#include <KoSection.h>
#include <KoSectionUtils.h>
#include <KoSectionModel.h>
#include <KoSectionEnd.h>
#include <KoShapeController.h>
#include <algorithm>
bool DeleteCommand::SectionDeleteInfo::operator<(const DeleteCommand::SectionDeleteInfo &other) const
{
// At first we remove sections that lays deeper in tree
// On one level we delete sections by descending order of their childIdx
// That is needed on undo, cuz we want it to be simply done by inserting
// sections back in reverse order of their deletion.
// Without childIdx compare it is possible that we will want to insert
// section on position 2 while the number of children is less than 2.
if (section->level() != other.section->level()) {
return section->level() > other.section->level();
}
return childIdx > other.childIdx;
}
DeleteCommand::DeleteCommand(DeleteMode mode,
QTextDocument *document,
KoShapeController *shapeController,
KUndo2Command *parent)
: KoTextCommandBase (parent)
, m_document(document)
, m_shapeController(shapeController)
, m_first(true)
, m_mode(mode)
, m_mergePossible(true)
{
setText(kundo2_i18n("Delete"));
}
void DeleteCommand::undo()
{
KoTextCommandBase::undo();
UndoRedoFinalizer finalizer(this); // Look at KoTextCommandBase documentation
// KoList
updateListChanges();
// KoTextRange
KoTextRangeManager *rangeManager = KoTextDocument(m_document).textRangeManager();
foreach (KoTextRange *range, m_rangesToRemove) {
rangeManager->insert(range);
}
// KoInlineObject
foreach (KoInlineObject *object, m_invalidInlineObjects) {
object->manager()->addInlineObject(object);
}
// KoSectionModel
insertSectionsToModel();
}
void DeleteCommand::redo()
{
if (!m_first) {
KoTextCommandBase::redo();
UndoRedoFinalizer finalizer(this); // Look at KoTextCommandBase documentation
// KoTextRange
KoTextRangeManager *rangeManager = KoTextDocument(m_document).textRangeManager();
foreach (KoTextRange *range, m_rangesToRemove) {
rangeManager->remove(range);
}
// KoSectionModel
deleteSectionsFromModel();
// TODO: there is nothing for InlineObjects and Lists. Is it OK?
} else {
m_first = false;
if (m_document) {
KoTextEditor *textEditor = KoTextDocument(m_document).textEditor();
if (textEditor) {
textEditor->beginEditBlock();
doDelete();
textEditor->endEditBlock();
}
}
}
}
// Section handling algorithm:
// At first, we go though the all section starts and ends
// that are in selection, and delete all pairs, because
// they will be deleted.
// Then we have multiple cases: selection start split some block
// or don't split any block.
// In the first case all formatting info will be stored in the
// split block(it has startBlockNum number).
// In the second case it will be stored in the block pointed by the
// selection end(it has endBlockNum number).
// Also there is a trivial case, when whole selection is inside
// one block, in this case hasEntirelyInsideBlock will be false
// and we will do nothing.
class DeleteVisitor : public KoTextVisitor
{
public:
DeleteVisitor(KoTextEditor *editor, DeleteCommand *command)
: KoTextVisitor(editor)
, m_first(true)
, m_command(command)
, m_startBlockNum(-1)
, m_endBlockNum(-1)
, m_hasEntirelyInsideBlock(false)
{
}
void visitBlock(QTextBlock &block, const QTextCursor &caret) override
{
for (QTextBlock::iterator it = block.begin(); it != block.end(); ++it) {
QTextCursor fragmentSelection(caret);
fragmentSelection.setPosition(qMax(caret.selectionStart(), it.fragment().position()));
fragmentSelection.setPosition(
qMin(caret.selectionEnd(), it.fragment().position() + it.fragment().length()),
QTextCursor::KeepAnchor
);
if (fragmentSelection.anchor() >= fragmentSelection.position()) {
continue;
}
visitFragmentSelection(fragmentSelection);
}
// Section handling below
bool doesBeginInside = false;
bool doesEndInside = false;
if (block.position() >= caret.selectionStart()) { // Begin of the block is inside selection.
doesBeginInside = true;
QList<KoSection *> openList = KoSectionUtils::sectionStartings(block.blockFormat());
foreach (KoSection *sec, openList) {
m_curSectionDelimiters.push_back(SectionHandle(sec->name(), sec));
}
}
if (block.position() + block.length() <= caret.selectionEnd()) { // End of the block is inside selection.
doesEndInside = true;
QList<KoSectionEnd *> closeList = KoSectionUtils::sectionEndings(block.blockFormat());
foreach (KoSectionEnd *se, closeList) {
if (!m_curSectionDelimiters.empty() && m_curSectionDelimiters.last().name == se->name()) {
KoSection *section = se->correspondingSection();
int childIdx = KoTextDocument(m_command->m_document).sectionModel()
->findRowOfChild(section);
m_command->m_sectionsToRemove.push_back(
DeleteCommand::SectionDeleteInfo(
section,
childIdx
)
);
m_curSectionDelimiters.pop_back(); // This section will die
} else {
m_curSectionDelimiters.push_back(SectionHandle(se->name(), se));
}
}
}
if (!doesBeginInside && doesEndInside) {
m_startBlockNum = block.blockNumber();
} else if (doesBeginInside && !doesEndInside) {
m_endBlockNum = block.blockNumber();
} else if (doesBeginInside && doesEndInside) {
m_hasEntirelyInsideBlock = true;
}
}
void visitFragmentSelection(QTextCursor &fragmentSelection) override
{
if (m_first) {
m_firstFormat = fragmentSelection.charFormat();
m_first = false;
}
if (m_command->m_mergePossible && fragmentSelection.charFormat() != m_firstFormat) {
m_command->m_mergePossible = false;
}
// Handling InlineObjects below
KoTextDocument textDocument(fragmentSelection.document());
KoInlineTextObjectManager *manager = textDocument.inlineTextObjectManager();
QString selected = fragmentSelection.selectedText();
fragmentSelection.setPosition(fragmentSelection.selectionStart() + 1);
int position = fragmentSelection.position();
const QChar *data = selected.constData();
for (int i = 0; i < selected.length(); i++) {
if (data->unicode() == QChar::ObjectReplacementCharacter) {
fragmentSelection.setPosition(position + i);
KoInlineObject *object = manager->inlineTextObject(fragmentSelection);
m_command->m_invalidInlineObjects.insert(object);
}
data++;
}
}
enum SectionHandleAction
{
SectionClose, ///< Denotes close of the section.
SectionOpen ///< Denotes start or beginning of the section.
};
/// Helper struct for handling sections.
struct SectionHandle {
QString name; ///< Name of the section.
SectionHandleAction type; ///< Action of a SectionHandle.
KoSection *dataSec; ///< Pointer to KoSection.
KoSectionEnd *dataSecEnd; ///< Pointer to KoSectionEnd.
SectionHandle(const QString &_name, KoSection *_data)
: name(_name)
, type(SectionOpen)
, dataSec(_data)
, dataSecEnd(0)
{
}
SectionHandle(const QString &_name, KoSectionEnd *_data)
: name(_name)
, type(SectionClose)
, dataSec(0)
, dataSecEnd(_data)
{
}
};
bool m_first;
DeleteCommand *m_command;
QTextCharFormat m_firstFormat;
int m_startBlockNum;
int m_endBlockNum;
bool m_hasEntirelyInsideBlock;
QList<SectionHandle> m_curSectionDelimiters;
};
void DeleteCommand::finalizeSectionHandling(QTextCursor *cur, DeleteVisitor &v)
{
// Lets handle pointers from block formats first
// It means that selection isn't within one block.
if (v.m_hasEntirelyInsideBlock || v.m_startBlockNum != -1 || v.m_endBlockNum != -1) {
QList<KoSection *> openList;
QList<KoSectionEnd *> closeList;
foreach (const DeleteVisitor::SectionHandle &handle, v.m_curSectionDelimiters) {
if (handle.type == v.SectionOpen) { // Start of the section.
openList << handle.dataSec;
} else { // End of the section.
closeList << handle.dataSecEnd;
}
}
// We're expanding ends in affected blocks to the end of the start block,
// delete all sections, that are entirely in affected blocks,
// and move ends, we have, to the begin of the next after the end block.
if (v.m_startBlockNum != -1) {
QTextBlockFormat fmt = cur->document()->findBlockByNumber(v.m_startBlockNum).blockFormat();
QTextBlockFormat fmt2 = cur->document()->findBlockByNumber(v.m_endBlockNum + 1).blockFormat();
fmt.clearProperty(KoParagraphStyle::SectionEndings);
// m_endBlockNum != -1 in this case.
QList<KoSectionEnd *> closeListEndBlock = KoSectionUtils::sectionEndings(
cur->document()->findBlockByNumber(v.m_endBlockNum).blockFormat());
while (!openList.empty() && !closeListEndBlock.empty()
&& openList.last()->name() == closeListEndBlock.first()->name()) {
int childIdx = KoTextDocument(m_document)
.sectionModel()->findRowOfChild(openList.back());
m_sectionsToRemove.push_back(
DeleteCommand::SectionDeleteInfo(
openList.back(),
childIdx
)
);
openList.pop_back();
closeListEndBlock.pop_front();
}
openList << KoSectionUtils::sectionStartings(fmt2);
closeList << closeListEndBlock;
// We leave open section of start block untouched.
KoSectionUtils::setSectionStartings(fmt2, openList);
KoSectionUtils::setSectionEndings(fmt, closeList);
QTextCursor changer = *cur;
changer.setPosition(cur->document()->findBlockByNumber(v.m_startBlockNum).position());
changer.setBlockFormat(fmt);
if (v.m_endBlockNum + 1 < cur->document()->blockCount()) {
changer.setPosition(cur->document()->findBlockByNumber(v.m_endBlockNum + 1).position());
changer.setBlockFormat(fmt2);
}
} else { // v.m_startBlockNum == -1
// v.m_endBlockNum != -1 in this case.
// We're pushing all new section info to the end block.
QTextBlockFormat fmt = cur->document()->findBlockByNumber(v.m_endBlockNum).blockFormat();
QList<KoSection *> allStartings = KoSectionUtils::sectionStartings(fmt);
fmt.clearProperty(KoParagraphStyle::SectionStartings);
QList<KoSectionEnd *> pairedEndings;
QList<KoSectionEnd *> unpairedEndings;
foreach (KoSectionEnd *se, KoSectionUtils::sectionEndings(fmt)) {
KoSection *sec = se->correspondingSection();
if (allStartings.contains(sec)) {
pairedEndings << se;
} else {
unpairedEndings << se;
}
}
if (cur->selectionStart()) {
QTextCursor changer = *cur;
changer.setPosition(cur->selectionStart() - 1);
QTextBlockFormat prevFmt = changer.blockFormat();
QList<KoSectionEnd *> prevEndings = KoSectionUtils::sectionEndings(prevFmt);
prevEndings = prevEndings + closeList;
KoSectionUtils::setSectionEndings(prevFmt, prevEndings);
changer.setBlockFormat(prevFmt);
}
KoSectionUtils::setSectionStartings(fmt, openList);
KoSectionUtils::setSectionEndings(fmt, pairedEndings + unpairedEndings);
QTextCursor changer = *cur;
changer.setPosition(cur->document()->findBlockByNumber(v.m_endBlockNum).position());
changer.setBlockFormat(fmt);
}
}
// Now lets deal with KoSectionModel
std::sort(m_sectionsToRemove.begin(), m_sectionsToRemove.end());
deleteSectionsFromModel();
}
void DeleteCommand::deleteSectionsFromModel()
{
KoSectionModel *model = KoTextDocument(m_document).sectionModel();
foreach (const SectionDeleteInfo &info, m_sectionsToRemove) {
model->deleteFromModel(info.section);
}
}
void DeleteCommand::insertSectionsToModel()
{
KoSectionModel *model = KoTextDocument(m_document).sectionModel();
QList<SectionDeleteInfo>::ConstIterator it = m_sectionsToRemove.constEnd();
while (it != m_sectionsToRemove.constBegin()) {
--it;
model->insertToModel(it->section, it->childIdx);
}
}
void DeleteCommand::doDelete()
{
KoTextEditor *textEditor = KoTextDocument(m_document).textEditor();
Q_ASSERT(textEditor);
QTextCursor *caret = textEditor->cursor();
QTextCharFormat charFormat = caret->charFormat();
bool caretAtBeginOfBlock = (caret->position() == caret->block().position());
if (!textEditor->hasSelection()) {
if (m_mode == PreviousChar) {
caret->movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor);
} else {
caret->movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
}
}
DeleteVisitor visitor(textEditor, this);
textEditor->recursivelyVisitSelection(m_document.data()->rootFrame()->begin(), visitor);
// Sections Model
finalizeSectionHandling(caret, visitor); // Finalize section handling routine.
// InlineObjects
foreach (KoInlineObject *object, m_invalidInlineObjects) {
deleteInlineObject(object);
}
// Ranges
KoTextRangeManager *rangeManager = KoTextDocument(m_document).textRangeManager();
m_rangesToRemove = rangeManager->textRangesChangingWithin(
textEditor->document(),
textEditor->selectionStart(),
textEditor->selectionEnd(),
textEditor->selectionStart(),
textEditor->selectionEnd()
);
foreach (KoTextRange *range, m_rangesToRemove) {
KoAnchorTextRange *anchorRange = dynamic_cast<KoAnchorTextRange *>(range);
KoAnnotation *annotation = dynamic_cast<KoAnnotation *>(range);
if (anchorRange) {
// we should only delete the anchor if the selection is covering it... not if the selection is
// just adjacent to the anchor. This is more in line with what other wordprocessors do
if (anchorRange->position() != textEditor->selectionStart()
&& anchorRange->position() != textEditor->selectionEnd()) {
KoShape *shape = anchorRange->anchor()->shape();
if (m_shapeController) {
KUndo2Command *shapeDeleteCommand = m_shapeController->removeShape(shape, this);
shapeDeleteCommand->redo();
}
// via m_shapeController->removeShape a DeleteAnchorsCommand should be created that
// also calls rangeManager->remove(range), so we shouldn't do that here aswell
}
} else if (annotation) {
KoShape *shape = annotation->annotationShape();
if (m_shapeController) {
KUndo2Command *shapeDeleteCommand = m_shapeController->removeShape(shape, this);
shapeDeleteCommand->redo();
}
// via m_shapeController->removeShape a DeleteAnnotationsCommand should be created that
// also calls rangeManager->remove(range), so we shouldn't do that here aswell
} else {
rangeManager->remove(range);
}
}
// Check: is merge possible?
if (textEditor->hasComplexSelection()) {
m_mergePossible = false;
}
//FIXME: lets forbid merging of "section affecting" deletions by now
if (!m_sectionsToRemove.empty()) {
m_mergePossible = false;
}
if (m_mergePossible) {
// Store various info needed for checkMerge
m_format = textEditor->charFormat();
m_position = textEditor->selectionStart();
m_length = textEditor->selectionEnd() - textEditor->selectionStart();
}
// Actual deletion of text
caret->deleteChar();
if (m_mode != PreviousChar || !caretAtBeginOfBlock) {
caret->setCharFormat(charFormat);
}
}
void DeleteCommand::deleteInlineObject(KoInlineObject *object)
{
if (object) {
KoAnchorInlineObject *anchorObject = dynamic_cast<KoAnchorInlineObject *>(object);
if (anchorObject) {
KoShape *shape = anchorObject->anchor()->shape();
KUndo2Command *shapeDeleteCommand = m_shapeController->removeShape(shape, this);
shapeDeleteCommand->redo();
} else {
object->manager()->removeInlineObject(object);
}
}
}
int DeleteCommand::id() const
{
// Should be an enum declared somewhere. KoTextCommandBase.h ???
return 56789;
}
bool DeleteCommand::mergeWith(const KUndo2Command *command)
{
class UndoTextCommand : public KUndo2Command
{
public:
UndoTextCommand(QTextDocument *document, KUndo2Command *parent = 0)
: KUndo2Command(kundo2_i18n("Text"), parent),
m_document(document)
{}
void undo() override {
QTextDocument *doc = m_document.data();
if (doc)
doc->undo(KoTextDocument(doc).textEditor()->cursor());
}
void redo() override {
QTextDocument *doc = m_document.data();
if (doc)
doc->redo(KoTextDocument(doc).textEditor()->cursor());
}
QPointer<QTextDocument> m_document;
};
KoTextEditor *textEditor = KoTextDocument(m_document).textEditor();
if (textEditor == 0)
return false;
if (command->id() != id())
return false;
if (!checkMerge(command))
return false;
DeleteCommand *other = const_cast<DeleteCommand *>(static_cast<const DeleteCommand *>(command));
m_invalidInlineObjects += other->m_invalidInlineObjects;
other->m_invalidInlineObjects.clear();
for (int i=0; i < command->childCount(); i++)
new UndoTextCommand(const_cast<QTextDocument*>(textEditor->document()), this);
return true;
}
bool DeleteCommand::checkMerge(const KUndo2Command *command)
{
DeleteCommand *other = const_cast<DeleteCommand *>(static_cast<const DeleteCommand *>(command));
if (!(m_mergePossible && other->m_mergePossible))
return false;
if (m_position == other->m_position && m_format == other->m_format) {
m_length += other->m_length;
return true;
}
if ((other->m_position + other->m_length == m_position)
&& (m_format == other->m_format)) {
m_position = other->m_position;
m_length += other->m_length;
return true;
}
return false;
}
void DeleteCommand::updateListChanges()
{
KoTextEditor *textEditor = KoTextDocument(m_document).textEditor();
if (textEditor == 0)
return;
QTextDocument *document = const_cast<QTextDocument*>(textEditor->document());
QTextCursor tempCursor(document);
QTextBlock startBlock = document->findBlock(m_position);
QTextBlock endBlock = document->findBlock(m_position + m_length);
if (endBlock != document->end())
endBlock = endBlock.next();
QTextList *currentList;
for (QTextBlock currentBlock = startBlock; currentBlock != endBlock; currentBlock = currentBlock.next()) {
tempCursor.setPosition(currentBlock.position());
currentList = tempCursor.currentList();
if (currentList) {
KoListStyle::ListIdType listId;
if (sizeof(KoListStyle::ListIdType) == sizeof(uint))
listId = currentList->format().property(KoListStyle::ListId).toUInt();
else
listId = currentList->format().property(KoListStyle::ListId).toULongLong();
if (!KoTextDocument(document).list(currentBlock)) {
KoList *list = KoTextDocument(document).list(listId);
if (list) {
list->updateStoredList(currentBlock);
}
}
}
}
}
DeleteCommand::~DeleteCommand()
{
}
|