History.js 21.8 KB
Newer Older
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1 2
"use strict";

3 4 5 6 7 8 9
/**
 * User: Ilja.Kirillov
 * Date: 11.04.12
 * Time: 14:35
 */


Sergey.Luzyanin's avatar
 
Sergey.Luzyanin committed
10

11 12 13
function CHistory(Document)
{
    this.Index      = -1;
14
    this.SavedIndex = null;        // Номер точки отката, на которой произошло последнее сохранение
15
    this.ForceSave  = false;       // Нужно сохранение, случается, когда у нас точка SavedIndex смещается из-за объединения точек, и мы делаем Undo
16
    this.RecIndex   = -1;          // Номер точки, на которой произошел последний пересчет
17
    this.Points     = []; // Точки истории, в каждой хранится массив с изменениями после текущей точки
18 19 20 21 22
    this.Document   = Document;

    this.RecalculateData =
    {
        Inline : { Pos : -1, PageNum : 0 },
23 24
        Flow   : [],
        HdrFtr : [],
Sergey.Luzyanin's avatar
 
Sergey.Luzyanin committed
25 26
        Drawings:
        {
27 28 29
            All:      false,
            Map:      {},
            ThemeInfo: null
Sergey.Luzyanin's avatar
 
Sergey.Luzyanin committed
30
        }
31 32 33
    };

    this.TurnOffHistory = false;
34
    this.MinorChanges   = false; // Данный параметр нужен, чтобы определить влияют ли добавленные изменения на пересчет
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51

    this.BinaryWriter = new CMemory();
}

CHistory.prototype =
{
    Is_Clear : function()
    {
        if ( this.Points.length <= 0 )
            return true;

        return false;
    },

    Clear : function()
    {
        this.Index         = -1;
52
        this.SavedIndex    = null;
53
        this.ForceSave     = false;
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
        this.Points.length = 0;
        this.Internal_RecalcData_Clear();
    },

    Can_Undo : function()
    {
        if ( this.Index >= 0 )
            return true;

        return false;
    },

    Can_Redo : function()
    {
        if ( this.Points.length > 0 && this.Index < this.Points.length - 1 )
            return true;

        return false;
    },

    Undo : function()
    {
        this.Check_UninonLastPoints();

        // Проверяем можно ли сделать Undo
        if ( true != this.Can_Undo() )
            return null;

        // Запоминаем самое последнее состояние документа для Redo
        if ( this.Index === this.Points.length - 1 )
            this.LastState = this.Document.Get_SelectionState();
85 86
        
        this.Document.Selection_Remove();
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109

        var Point = this.Points[this.Index--];

        this.Internal_RecalcData_Clear();

        // Откатываем все действия в обратном порядке (относительно их выполенения)
        for ( var Index = Point.Items.length - 1; Index >= 0; Index-- )
        {
            var Item = Point.Items[Index];
            Item.Class.Undo( Item.Data );
            Item.Class.Refresh_RecalcData( Item.Data );
        }

        this.Document.Set_SelectionState( Point.State );

        return this.RecalculateData;
    },

    Redo : function()
    {
        // Проверяем можно ли сделать Redo
        if ( true != this.Can_Redo() )
            return null;
110 111 112
        
        this.Document.Selection_Remove();
        
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
        var Point = this.Points[++this.Index];

        this.Internal_RecalcData_Clear();

        // Выполняем все действия в прямом порядке
        for ( var Index = 0; Index < Point.Items.length; Index++ )
        {
            var Item = Point.Items[Index];
            Item.Class.Redo( Item.Data );
            Item.Class.Refresh_RecalcData( Item.Data );
        }

        // Восстанавливаем состояние на следующую точку
        var State = null;
        if ( this.Index === this.Points.length - 1 )
            State = this.LastState;
        else
            State = this.Points[this.Index + 1].State;

        this.Document.Set_SelectionState( State );

        return this.RecalculateData;
    },

    Create_NewPoint : function()
    {
139
        if ( this.Index < this.SavedIndex && null !== this.SavedIndex )
140
        {
141
            this.SavedIndex = this.Index;
142 143
            this.ForceSave  = true;
        }
144

145 146
        this.Clear_Additional();

147
        this.Check_UninonLastPoints();
148
        
149
        var State = this.Document.Get_SelectionState();
150
        var Items = [];
151 152 153 154 155
        var Time  = new Date().getTime();

        // Создаем новую точку
        this.Points[++this.Index] =
        {
156 157 158 159
            State      : State, // Текущее состояние документа (курсор, селект)
            Items      : Items, // Массив изменений, начиная с текущего момента
            Time       : Time,  // Текущее время
            Additional : {}     // Дополнительная информация
160 161 162 163 164
        };

        // Удаляем ненужные точки
        this.Points.length = this.Index + 1;
    },
165 166 167 168 169 170
    
    Remove_LastPoint : function()
    {
        this.Index--;
        this.Points.length = this.Index + 1;
    },
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188

    Clear_Redo : function()
    {
        // Удаляем ненужные точки
        this.Points.length = this.Index + 1;
    },

    // Регистрируем новое изменение:
    // Class - объект, в котором оно произошло
    // Data  - сами изменения
    Add : function(Class, Data)
    {
        if ( true === this.TurnOffHistory )
            return;

        if ( this.Index < 0 )
            return;

189 190 191 192 193
        // Заглушка на случай, если у нас во время создания одной точки в истории, после нескольких изменений идет
        // пересчет, потом снова добавляются изменения и снова запускается пересчет и т.д.
        if ( this.RecIndex >= this.Index )
            this.RecIndex = this.Index - 1;

194 195 196 197 198 199 200 201 202 203 204 205 206 207
        var Binary_Pos = this.BinaryWriter.GetCurPosition();

        Class.Save_Changes( Data, this.BinaryWriter );

        var Binary_Len = this.BinaryWriter.GetCurPosition() - Binary_Pos;

        var Item =
        {
            Class : Class,
            Data  : Data,
            Binary:
            {
                Pos : Binary_Pos,
                Len : Binary_Len
208 209 210
            },
            
            NeedRecalc : !this.MinorChanges
211 212 213
        };

        this.Points[this.Index].Items.push( Item );
214
        var bZIndexManager = !(typeof ZIndexManager === "undefined");
215 216
        var bPresentation = !(typeof CPresentation === "undefined");
        var bSlide = !(typeof Slide === "undefined");
217 218 219 220
        if ( ( Class instanceof CDocument        && ( historyitem_Document_AddItem        === Data.Type || historyitem_Document_RemoveItem        === Data.Type ) ) ||
            ( Class instanceof CDocumentContent && ( historyitem_DocumentContent_AddItem === Data.Type || historyitem_DocumentContent_RemoveItem === Data.Type ) ) ||
            ( Class instanceof CTable           && ( historyitem_Table_AddRow            === Data.Type || historyitem_Table_RemoveRow            === Data.Type ) ) ||
            ( Class instanceof CTableRow        && ( historyitem_TableRow_AddCell        === Data.Type || historyitem_TableRow_RemoveCell        === Data.Type ) ) ||
221 222
            ( Class instanceof Paragraph        && ( historyitem_Paragraph_AddItem       === Data.Type || historyitem_Paragraph_RemoveItem       === Data.Type ) ) ||
            ( Class instanceof ParaHyperlink    && ( historyitem_Hyperlink_AddItem       === Data.Type || historyitem_Hyperlink_RemoveItem       === Data.Type ) ) ||
223
            ( Class instanceof ParaRun          && ( historyitem_ParaRun_AddItem         === Data.Type || historyitem_ParaRun_RemoveItem         === Data.Type ) ) ||
224 225 226 227
            ( bZIndexManager && Class instanceof ZIndexManager    && (historyitem_ZIndexManagerRemoveItem  === Data.Type || historyitem_ZIndexManagerAddItem       === Data.Type )) ||
            ( bPresentation && Class instanceof CPresentation && (historyitem_Presentation_AddSlide === Data.Type || historyitem_Presentation_RemoveSlide === Data.Type)) ||
            ( bSlide && Class instanceof Slide && (historyitem_SlideAddToSpTree === Data.Type || historyitem_SlideRemoveFromSpTree === Data.Type))
            )
228 229 230 231 232
        {
            var bAdd = ( ( Class instanceof CDocument        && historyitem_Document_AddItem        === Data.Type ) ||
                ( Class instanceof CDocumentContent && historyitem_DocumentContent_AddItem === Data.Type ) ||
                ( Class instanceof CTable           && historyitem_Table_AddRow            === Data.Type ) ||
                ( Class instanceof CTableRow        && historyitem_TableRow_AddCell        === Data.Type ) ||
233 234
                ( Class instanceof Paragraph        && historyitem_Paragraph_AddItem       === Data.Type ) ||
                ( Class instanceof ParaHyperlink    && historyitem_Hyperlink_AddItem       === Data.Type ) ||
235
                ( Class instanceof ParaRun          && historyitem_ParaRun_AddItem         === Data.Type ) ||
236 237 238
                (bZIndexManager && Class instanceof ZIndexManager    && historyitem_ZIndexManagerAddItem === Data.Type ) ||
                ( bPresentation && Class instanceof CPresentation && (historyitem_Presentation_AddSlide === Data.Type )) ||
                ( bSlide && Class instanceof Slide && (historyitem_SlideAddToSpTree === Data.Type))
239 240 241 242
                ) ? true : false;

            var Count = 1;

243
            if ( ( Class instanceof Paragraph ) ||  ( Class instanceof ParaHyperlink) || ( Class instanceof ParaRun ) ||
244 245 246 247 248 249 250 251
                ( Class instanceof CDocument        && historyitem_Document_RemoveItem        === Data.Type ) ||
                ( Class instanceof CDocumentContent && historyitem_DocumentContent_RemoveItem === Data.Type ) )
                Count = Data.Items.length;

            var ContentChanges = new CContentChangesElement( ( bAdd == true ? contentchanges_Add : contentchanges_Remove ), Data.Pos, Count, Item );
            Class.Add_ContentChanges( ContentChanges );
            CollaborativeEditing.Add_NewDC( Class );
        }
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
        if(CollaborativeEditing.AddPosExtChanges && Class instanceof CXfrm)
        {
            if(historyitem_Xfrm_SetOffX  === Data.Type ||
                historyitem_Xfrm_SetOffY === Data.Type ||
                historyitem_Xfrm_SetExtX === Data.Type ||
                historyitem_Xfrm_SetExtY === Data.Type ||
                historyitem_Xfrm_SetChOffX === Data.Type ||
                historyitem_Xfrm_SetChOffY === Data.Type ||
                historyitem_Xfrm_SetChExtX === Data.Type ||
                historyitem_Xfrm_SetChExtY  === Data.Type)
            {
                CollaborativeEditing.AddPosExtChanges(Item,
                    historyitem_Xfrm_SetOffX  === Data.Type ||
                    historyitem_Xfrm_SetExtX === Data.Type ||
                        historyitem_Xfrm_SetChOffX === Data.Type ||
                        historyitem_Xfrm_SetChExtX === Data.Type );
            }
        }
270 271 272 273 274 275 276
    },

    Internal_RecalcData_Clear : function()
    {
        this.RecalculateData =
        {
            Inline : { Pos : -1, PageNum : 0 },
277 278
            Flow   : [],
            HdrFtr : [],
Sergey.Luzyanin's avatar
 
Sergey.Luzyanin committed
279 280 281
            Drawings:
            {
                All: false,
282 283
                Map: {},
                ThemeInfo: null
Sergey.Luzyanin's avatar
 
Sergey.Luzyanin committed
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
        };
    },

    RecalcData_Add : function(Data)
    {
        if ( "undefined" === typeof(Data) || null === Data )
            return;

        switch ( Data.Type )
        {
            case historyrecalctype_Flow:
            {
                var bNew = true;
                for ( var Index = 0; Index < this.RecalculateData.Flow.length; Index++ )
                {
                    if ( this.RecalculateData.Flow[Index] === Data.Data )
                    {
                        bNew = false;
                        break;
                    }
                }

                if ( true === bNew )
                    this.RecalculateData.Flow.push( Data.Data );

                break;
            }

            case historyrecalctype_HdrFtr:
            {
                if ( null === Data.Data )
                    break;

                var bNew = true;
                for ( var Index = 0; Index < this.RecalculateData.HdrFtr.length; Index++ )
                {
                    if ( this.RecalculateData.HdrFtr[Index] === Data.Data )
                    {
                        bNew = false;
                        break;
                    }
                }

                if ( true === bNew )
                    this.RecalculateData.HdrFtr.push( Data.Data );

                break
            }

            case historyrecalctype_Inline:
            {
336
                if ( (Data.Data.Pos < this.RecalculateData.Inline.Pos) || (Data.Data.Pos === this.RecalculateData.Inline.Pos && Data.Data.PageNum < this.RecalculateData.Inline.PageNum) || this.RecalculateData.Inline.Pos < 0 )
337 338 339 340 341 342 343
                {
                    this.RecalculateData.Inline.Pos     = Data.Data.Pos;
                    this.RecalculateData.Inline.PageNum = Data.Data.PageNum;
                }

                break;
            }
Sergey.Luzyanin's avatar
 
Sergey.Luzyanin committed
344 345 346 347 348 349 350 351 352 353
            case historyrecalctype_Drawing:
            {
                if(!this.RecalculateData.Drawings.All)
                {
                    if(Data.All)
                    {
                        this.RecalculateData.Drawings.All = true;
                    }
                    else
                    {
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
                        if(Data.Theme)
                        {
                            this.RecalculateData.Drawings.ThemeInfo =
                            {
                                Theme: true,
                                ArrInd: Data.ArrInd
                            }
                        }
                        else if(Data.ColorScheme)
                        {
                            this.RecalculateData.Drawings.ThemeInfo =
                            {
                                ColorScheme: true,
                                ArrInd: Data.ArrInd
                            }
                        }
                        else
                        {
                            this.RecalculateData.Drawings.Map[Data.Object.Get_Id()] = Data.Object;
                        }
Sergey.Luzyanin's avatar
 
Sergey.Luzyanin committed
374 375
                    }
                }
376
                break;
Sergey.Luzyanin's avatar
 
Sergey.Luzyanin committed
377
            }
378 379 380 381 382
        }
    },

    Check_UninonLastPoints : function()
    {
383 384 385 386 387
        // Не объединяем точки в истории, когда отключается пересчет.
        // TODO: Неправильно изменяется RecalcIndex
        if (true === this.Document.TurnOffRecalc)
            return;

388
        // Не объединяем точки истории, если на предыдущей точке произошло сохранение
389
        if ( this.Points.length < 2 )
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
            return;

        var Point1 = this.Points[this.Points.length - 2];
        var Point2 = this.Points[this.Points.length - 1];

        // Не объединяем слова больше 63 элементов
        if ( Point1.Items.length > 63 )
            return;

        var PrevItem = null;
        var Class = null;
        for ( var Index = 0; Index < Point1.Items.length; Index++ )
        {
            var Item = Point1.Items[Index];

            if ( null === Class )
                Class = Item.Class;
            else if ( Class != Item.Class || "undefined" === typeof(Class.Check_HistoryUninon) || false === Class.Check_HistoryUninon(PrevItem.Data, Item.Data) )
                return;

            PrevItem = Item;
        }

        for ( var Index = 0; Index < Point2.Items.length; Index++ )
        {
            var Item = Point2.Items[Index];

            if ( Class != Item.Class || "undefined" === typeof(Class.Check_HistoryUninon) || false === Class.Check_HistoryUninon(PrevItem.Data, Item.Data) )
                return;

            PrevItem = Item;
        }

        var NewPoint =
        {
            State : Point1.State,
            Items : Point1.Items.concat(Point2.Items),
427 428
            Time  : Point1.Time,
            Additional : {}
429 430
        };

431
		if ( this.SavedIndex >= this.Points.length - 2 && null !== this.SavedIndex )
432 433 434 435
        {
			this.SavedIndex = this.Points.length - 3;
            this.ForceSave  = true;
        }
436

437 438
        this.Points.splice( this.Points.length - 2, 2, NewPoint );
        if ( this.Index >= this.Points.length )
439 440 441
        {
            var DiffIndex = -this.Index + (this.Points.length - 1);
            this.Index    += DiffIndex;
442
            this.RecIndex  = Math.max( -1, this.RecIndex + DiffIndex);
443
        }
444
	},
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463

    TurnOff : function()
    {
        this.TurnOffHistory = true;
    },

    TurnOn : function()
    {
        this.TurnOffHistory = false;
    },

    Is_On : function()
    {
        return ( false === this.TurnOffHistory ? true : false ) ;
    },

    Reset_SavedIndex : function()
    {
        this.SavedIndex = this.Index;
464
        this.ForceSave   = false;
465 466 467 468
    },

    Have_Changes : function()
    {
469
        if ( -1 === this.Index && null === this.SavedIndex && false === this.ForceSave )
470 471
            return false;
        
472
        if ( this.Index != this.SavedIndex || true === this.ForceSave )
473 474 475 476 477 478 479 480 481 482 483
            return true;

        return false;
    },

    Get_RecalcData : function()
    {
        if ( this.Index >= 0 )
        {
            this.Internal_RecalcData_Clear();

484
            for ( var Pos = this.RecIndex + 1; Pos <= this.Index; Pos++ )
485
            {
486 487 488 489 490 491 492
                // Считываем изменения, начиная с последней точки, и смотрим что надо пересчитать.
                var Point = this.Points[Pos];

                // Выполняем все действия в прямом порядке
                for ( var Index = 0; Index < Point.Items.length; Index++ )
                {
                    var Item = Point.Items[Index];
493 494 495
                    
                    if ( true === Item.NeedRecalc )
                        Item.Class.Refresh_RecalcData( Item.Data );
496
                }
497 498 499 500
            }
        }

        return this.RecalculateData;
501 502
    },

503 504 505 506 507
    Reset_RecalcIndex : function()
    {
        this.RecIndex = this.Index;
    },

508 509
    Is_SimpleChanges : function()
    {
510 511 512 513 514 515 516 517 518 519 520 521
        var Count, Items;
        if (this.Index - this.RecIndex !== 1 && this.RecIndex >= -1)
        {
            Items = [];
            Count = 0;
            for (var PointIndex = this.RecIndex + 1; PointIndex <= this.Index; PointIndex++)
            {
                Items = Items.concat(this.Points[PointIndex].Items);
                Count += this.Points[PointIndex].Items.length;
            }
        }
        else if (this.Index >= 0)
522 523 524 525
        {
            // Считываем изменения, начиная с последней точки, и смотрим что надо пересчитать.
            var Point = this.Points[this.Index];

526 527 528 529 530 531
            Count = Point.Items.length;
            Items = Point.Items;
        }
        else
            return [];
        
532

533 534 535
        if (Items.length > 0)
        {
            var Class = Items[0].Class;
536
            // Смотрим, чтобы класс, в котором произошли все изменения был один и тот же
537
            for (var Index = 1; Index < Count; Index++)
538
            {
539
                var Item = Items[Index];
540

541
                if (Class !== Item.Class)
542
                    return [];
543 544
            }

545 546
            if (Class instanceof ParaRun && Class.Is_SimpleChanges(Items))
                return Items;
547 548
        }

549
        return [];
550 551
    },

552 553 554 555 556 557 558 559 560 561
    Set_Additional_ExtendDocumentToPos : function()
    {
        if ( this.Index >= 0 )
        {
            this.Points[this.Index].Additional.ExtendDocumentToPos = true;
        }
    },

    Is_ExtendDocumentToPos : function()
    {
562
        if ( undefined === this.Points[this.Index] || undefined === this.Points[this.Index].Additional || undefined === this.Points[this.Index].Additional.ExtendDocumentToPos )
563 564 565 566 567 568 569 570 571
            return false;

        return true;
    },

    Clear_Additional : function()
    {
        if ( this.Index >= 0 )
        {
572
            this.Points[this.Index].Additional = {};
573
        }
574 575 576

        if ( true === editor.isMarkerFormat)
            editor.sync_MarkerFormatCallback(false);
577 578 579 580 581 582
    },

    Get_EditingTime : function(dTime)
    {
        var Count = this.Points.length;

583
        var TimeLine = [];
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
        for ( var Index = 0; Index < Count; Index++ )
        {
            var PointTime = this.Points[Index].Time;
            TimeLine.push( { t0 : PointTime - dTime, t1 : PointTime } );
        }

        Count = TimeLine.length;
        for ( var Index = 1; Index < Count; Index++ )
        {
            var CurrEl = TimeLine[Index];
            var PrevEl = TimeLine[Index - 1];
            if ( CurrEl.t0 <= PrevEl.t1 )
            {
                PrevEl.t1 = CurrEl.t1;
                TimeLine.splice( Index, 1 );
                Index--;
                Count--;
            }
        }

        Count = TimeLine.length;
        var OverallTime = 0;
        for ( var Index = 0; Index < Count; Index++ )
        {
            OverallTime += TimeLine[Index].t1 - TimeLine[Index].t0;
        }

        return OverallTime;
612
    }
613

614
};
615 616

var History = null;