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

3 4 5 6 7 8 9 10 11 12
/**
 * User: Ilja.Kirillov
 * Date: 29.05.13
 * Time: 12:02
 */

//----------------------------------------------------------------------------------------------------------------------
// CParagraphSearchElement
//         Найденные элементы в параграфе. Записаны в массиве Paragraph.SearchResults
//----------------------------------------------------------------------------------------------------------------------
13
function CParagraphSearchElement(StartPos, EndPos, Type, Id)
14 15 16 17 18
{
    this.StartPos  = StartPos;
    this.EndPos    = EndPos;
    this.Type      = Type;
    this.ResultStr = "";
19 20
    this.Id        = Id;

21 22
    this.ClassesS = [];
    this.ClassesE = [];
23 24 25 26 27 28 29 30
}

//----------------------------------------------------------------------------------------------------------------------
// CDocumentSearch
//         Механизм поиска. Хранит параграфы с найденной строкой
//----------------------------------------------------------------------------------------------------------------------
function CDocumentSearch()
{
31
    this.Text          = "";
32
    this.MatchCase     = false;
33

34 35
    this.Id            = 0;
    this.Count         = 0;
36
    this.Elements      = [];
37 38 39 40
    this.CurId         = -1;
    this.Direction     = true; // направление true - вперед, false - назад
    this.ClearOnRecalc = true; // Флаг, говорящий о том, запустился ли пересчет из-за Replace
    this.Selection     = false;
41 42 43 44
}

CDocumentSearch.prototype =
{
45 46
    Set : function(Text, Props)
    {
47 48
        this.Text      = Text;
        this.MatchCase = Props.MatchCase;
49 50
    },

51 52 53 54 55 56
    Reset : function()
    {
        this.Text          = "";
        this.MatchCase     = false;
    },

57 58
    Compare : function(Text, Props)
    {
59
        if ( this.Text === Text && this.MatchCase === Props.MatchCase )
60 61 62 63 64
            return true;

        return false;
    },

65 66
    Clear : function()
    {
67 68
        this.Text        = "";
        this.MatchCase   = false;
69

70
        // Очищаем предыдущие элементы поиска
71
        for (var Id in this.Elements)
72 73
        {
            var Paragraph = this.Elements[Id];
74
            Paragraph.Clear_SearchResults();
75 76
        }

77 78
        this.Id        = 0;
        this.Count     = 0;
79
        this.Elements  = {};
80 81
        this.CurId     = -1;
        this.Direction = true;
82 83 84 85 86 87 88 89 90 91
    },

    Add : function(Paragraph)
    {
        this.Count++;
        this.Id++;
        this.Elements[this.Id] = Paragraph;
        return this.Id;
    },

92
    Select : function(Id, bUpdateStates)
93 94 95 96 97 98 99 100 101
    {
        var Paragraph = this.Elements[Id];
        if ( undefined != Paragraph )
        {
            var SearchElement = Paragraph.SearchResults[Id];
            if ( undefined != SearchElement )
            {
                Paragraph.Selection.Use      = true;
                Paragraph.Selection.Start    = false;
102

103 104
                Paragraph.Set_SelectionContentPos(SearchElement.StartPos, SearchElement.EndPos);
                Paragraph.Set_ParaContentPos(SearchElement.StartPos, false, -1, -1);
105

106
                Paragraph.Document_SetThisElementCurrent(false !== bUpdateStates ? true : false);
107
            }
108 109

            this.CurId = Id;
110 111 112
        }
    },

113 114 115 116 117
    Reset_Current : function()
    {
        this.CurId = -1;
    },

118
    Replace : function(NewStr, Id, bRestorePos)
119 120 121 122 123 124 125
    {
        var Para = this.Elements[Id];
        if ( undefined != Para )
        {
            var SearchElement = Para.SearchResults[Id];
            if ( undefined != SearchElement )
            {
126 127 128 129 130 131 132 133 134 135 136 137 138 139
                var ContentPos, StartPos, EndPos, bSelection;
                if (true === bRestorePos)
                {
                    // Сохраняем позицию состояние параграфа, чтобы курсор остался в том же месте и после замены.
                    bSelection = Para.Is_SelectionUse();
                    ContentPos = Para.Get_ParaContentPos(false, false);
                    StartPos   = Para.Get_ParaContentPos(true, true);
                    EndPos     = Para.Get_ParaContentPos(true, false);

                    Para.Check_NearestPos({ContentPos : ContentPos});
                    Para.Check_NearestPos({ContentPos : StartPos});
                    Para.Check_NearestPos({ContentPos : EndPos});
                }

140 141 142
                // Сначала в начальную позицию поиска добавляем новый текст
                var StartContentPos = SearchElement.StartPos;
                var StartRun = SearchElement.ClassesS[SearchElement.ClassesS.length - 1];
143

144
                var RunPos = StartContentPos.Get( SearchElement.ClassesS.length - 1 );
145

146 147 148
                var Len = NewStr.length;
                for ( var Pos = 0; Pos < Len; Pos++ )
                {
149
                    StartRun.Add_ToContent(RunPos + Pos, ' ' === NewStr[Pos] ? new ParaSpace() : new ParaText(NewStr[Pos]));
150
                }
151

152 153 154 155
                // Выделяем старый объект поиска и удаляем его
                Para.Selection.Use = true;
                Para.Set_SelectionContentPos( SearchElement.StartPos, SearchElement.EndPos );
                Para.Remove();
156

157 158 159
                // Перемещаем курсор в конец поиска
                Para.Selection_Remove();
                Para.Set_ParaContentPos( SearchElement.StartPos, true, -1, -1 );
160

161 162
                // Удаляем запись о данном элементе
                this.Count--;
163

164 165
                Para.Remove_SearchResult( Id );
                delete this.Elements[Id];
166 167 168 169 170 171 172 173

                if (true === bRestorePos)
                {
                    Para.Set_SelectionContentPos(StartPos, EndPos);
                    Para.Set_ParaContentPos(ContentPos, true, -1, -1 );
                    Para.Selection.Use = bSelection;
                    Para.Clear_NearestPosArray();
                }
174 175 176 177
            }
        }
    },

178
    Replace_All : function(NewStr, bUpdateStates)
179
    {
180
        for (var Id = this.Id; Id >= 0; --Id)
181
        {
182 183
            if (this.Elements[Id])
                this.Replace(NewStr, Id, true);
184
        }
185 186 187 188 189 190 191

        this.Clear();
    },

    Set_Direction : function(bDirection)
    {
        this.Direction = bDirection;
192 193 194 195 196 197
    }
};

//----------------------------------------------------------------------------------------------------------------------
// CDocument
//----------------------------------------------------------------------------------------------------------------------
198
CDocument.prototype.Search = function(Str, Props, bDraw)
199 200 201
{
    var StartTime = new Date().getTime();

202 203 204
    if ( true === this.SearchEngine.Compare( Str, Props ) )
        return this.SearchEngine;

205
    this.SearchEngine.Clear();
206
    this.SearchEngine.Set( Str, Props );
207 208 209 210 211 212 213 214

    // Поиск в основном документе
    var Count = this.Content.length;
    for ( var Index = 0; Index < Count; Index++ )
    {
        this.Content[Index].Search( Str, Props, this.SearchEngine, search_Common );
    }

215
    // Поиск в колонтитулах
216
    this.SectionsInfo.Search( Str, Props, this.SearchEngine );
217

218 219 220 221 222
    if (false !== bDraw)
    {
        this.DrawingDocument.ClearCachePages();
        this.DrawingDocument.FirePaint();
    }
223

224
    //console.log( "Search logic: " + ((new Date().getTime() - StartTime) / 1000) + " s"  );
225 226 227 228 229 230 231

    return this.SearchEngine;
};

CDocument.prototype.Search_Select = function(Id)
{
    this.Selection_Remove();
232
    this.SearchEngine.Select(Id, true);
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
    this.RecalculateCurPos();

    this.Document_UpdateInterfaceState();
    this.Document_UpdateSelectionState();
    this.Document_UpdateRulersState();
};

CDocument.prototype.Search_Replace = function(NewStr, bAll, Id)
{
    var bResult = false;

    this.Selection_Remove();

    var CheckParagraphs = [];
    if ( true === bAll )
    {
249 250 251 252 253 254 255 256 257 258
        var CheckParagraphsObj = {};
        for (var Id in this.SearchEngine.Elements)
        {
            CheckParagraphsObj[this.SearchEngine.Elements[Id].Get_Id()] = this.SearchEngine.Elements[Id];
        }

        for (var ParaId in CheckParagraphsObj)
        {
            CheckParagraphs.push(CheckParagraphsObj[ParaId]);
        }
259 260 261 262 263 264 265
    }
    else
    {
        if ( undefined !== this.SearchEngine.Elements[Id] )
            CheckParagraphs.push( this.SearchEngine.Elements[Id] );
    }

266 267
    var AllCount = this.SearchEngine.Count;

268 269
    if ( false === this.Document_Is_SelectionLocked( changestype_None, { Type : changestype_2_ElementsArray_and_Type, Elements : CheckParagraphs, CheckType : changestype_Paragraph_Content } ) )
    {
270
        History.Create_NewPoint(bAll ? historydescription_Document_ReplaceAll : historydescription_Document_ReplaceSingle);
271

272 273
        if (true === bAll)
        {
274
            this.SearchEngine.Replace_All(NewStr, true);
275
        }
276
        else
277
        {
278
            this.SearchEngine.Replace(NewStr, Id, false);
279

280 281 282 283 284 285
            // TODO: В будушем надо будет переделать, чтобы искалось заново только в том параграфе, в котором произошла замена
            //       Тут появляется проблема с вложенным поиском, если то что мы заменяем содержится в том, на что мы заменяем.
            if (true === this.Is_TrackRevisions())
                this.SearchEngine.Reset();
        }

286
        this.SearchEngine.ClearOnRecalc = false;
287
        this.Recalculate();
288 289
        this.SearchEngine.ClearOnRecalc = true;

290 291 292
        this.RecalculateCurPos();

        bResult = true;
293 294

        if ( true === bAll )
295
            editor.sync_ReplaceAllCallback(AllCount, AllCount);
296 297 298 299
    }
    else
    {
        if ( true === bAll )
300
            editor.sync_ReplaceAllCallback(0, AllCount);
301 302 303 304 305 306 307 308 309
    }

    this.Document_UpdateInterfaceState();
    this.Document_UpdateSelectionState();
    this.Document_UpdateRulersState();

    return bResult;
};

310 311 312 313 314 315 316 317
CDocument.prototype.Search_GetId = function(bNext)
{
    this.SearchEngine.Set_Direction( bNext );

    // Получим Id найденного элемента
    if ( docpostype_DrawingObjects === this.CurPos.Type )
    {
        var ParaDrawing = this.DrawingObjects.getMajorParaDrawing();
318 319 320 321 322

        var Id = ParaDrawing.Search_GetId( bNext, true );
        if ( null != Id )
            return Id;

323
        this.DrawingObjects.resetSelection();
324
        ParaDrawing.GoTo_Text( true === bNext ? false : true, false );
325 326 327 328 329 330 331 332 333 334
    }

    if ( docpostype_Content === this.CurPos.Type )
    {
        var Id = null;

        var Pos = this.CurPos.ContentPos;
        if ( true === this.Selection.Use && selectionflag_Common === this.Selection.Flag )
            Pos = ( true === bNext ? Math.max(this.Selection.StartPos, this.Selection.EndPos) : Math.min(this.Selection.StartPos, this.Selection.EndPos) );

335
        var StartPos = Pos;
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355

        if ( true === bNext )
        {
            Id = this.Content[Pos].Search_GetId(true, true);

            if ( null != Id )
                return Id;

            Pos++;

            var Count = this.Content.length;
            while ( Pos < Count )
            {
                Id = this.Content[Pos].Search_GetId(true, false);

                if ( null != Id )
                    return Id;

                Pos++;
            }
356 357 358 359 360 361 362 363 364 365 366 367 368

            Pos = 0;
            while ( Pos <= StartPos )
            {
                Id = this.Content[Pos].Search_GetId(true, false);

                if ( null != Id )
                    return Id;

                Pos++;
            }

            return null;
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
        }
        else
        {
            Id = this.Content[Pos].Search_GetId(false, true);

            if ( null != Id )
                return Id;

            Pos--;

            while ( Pos >= 0 )
            {
                Id = this.Content[Pos].Search_GetId(false, false);

                if ( null != Id )
                    return Id;

                Pos--;
            }
388 389 390 391 392 393 394 395 396 397 398 399 400

            Pos = this.Content.length - 1;
            while ( Pos >= StartPos )
            {
                Id = this.Content[Pos].Search_GetId(false, false);

                if ( null != Id )
                    return Id;

                Pos--;
            }

            return null;
401 402 403 404
        }
    }
    else if ( docpostype_HdrFtr === this.CurPos.Type )
    {
405
        return this.SectionsInfo.Search_GetId( bNext, this.HdrFtr.CurHdrFtr );
406
    }
407 408

    return null;
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
};

CDocument.prototype.Search_Set_Selection = function(bSelection)
{
    var OldValue = this.SearchEngine.Selection;
    if ( OldValue === bSelection )
        return;

    this.SearchEngine.Selection = bSelection;
    this.DrawingDocument.ClearCachePages();
    this.DrawingDocument.FirePaint();
};

CDocument.prototype.Search_Get_Selection = function()
{
    return this.SearchEngine.Selection;
};

427 428 429 430 431 432 433 434 435 436 437 438 439
//----------------------------------------------------------------------------------------------------------------------
// CDocumentContent
//----------------------------------------------------------------------------------------------------------------------
CDocumentContent.prototype.Search = function(Str, Props, SearchEngine, Type)
{
    // Поиск в основном документе
    var Count = this.Content.length;
    for ( var Index = 0; Index < Count; Index++ )
    {
        this.Content[Index].Search( Str, Props, SearchEngine, Type );
    }
};

440 441
CDocumentContent.prototype.Search_GetId = function(bNext, bCurrent)
{
442 443 444
    // Получим Id найденного элемента
    var Id = null;

445 446 447 448
    if ( true === bCurrent )
    {
        if ( docpostype_DrawingObjects === this.CurPos.Type )
        {
449
            var ParaDrawing = this.DrawingObjects.getMajorParaDrawing();
450

451 452 453 454
            Id = ParaDrawing.Search_GetId( bNext, true );
            if ( null != Id )
                return Id;

455
            ParaDrawing.GoTo_Text( true === bNext ? false : true, false );
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

        var Pos = this.CurPos.ContentPos;
        if ( true === this.Selection.Use && selectionflag_Common === this.Selection.Flag )
            Pos = ( true === bNext ? Math.max(this.Selection.StartPos, this.Selection.EndPos) : Math.min(this.Selection.StartPos, this.Selection.EndPos) );

        if ( true === bNext )
        {
            Id = this.Content[Pos].Search_GetId(true, true);

            if ( null != Id )
                return Id;

            Pos++;

            var Count = this.Content.length;
            while ( Pos < Count )
            {
                Id = this.Content[Pos].Search_GetId(true, false);
                if ( null != Id )
                    return Id;

                Pos++;
            }
        }
        else
        {
            Id = this.Content[Pos].Search_GetId(false, true);

            if ( null != Id )
                return Id;

            Pos--;

            while ( Pos >= 0 )
            {
                Id = this.Content[Pos].Search_GetId(false, false);
                if ( null != Id )
                    return Id;

                Pos--;
            }
        }
    }
    else
    {
        var Count = this.Content.length;
        if ( true === bNext )
        {
            var Pos = 0;
            while ( Pos < Count )
            {
                Id = this.Content[Pos].Search_GetId(true, false);
                if ( null != Id )
                    return Id;

                Pos++;
            }
        }
        else
        {
            var Pos = Count - 1;
            while ( Pos >= 0 )
            {
                Id = this.Content[Pos].Search_GetId(false, false);
                if ( null != Id )
                    return Id;

                Pos--;
            }
        }
    }

    return null;
};

532 533 534 535 536 537 538 539
//----------------------------------------------------------------------------------------------------------------------
// CHeaderFooter
//----------------------------------------------------------------------------------------------------------------------
CHeaderFooter.prototype.Search = function(Str, Props, SearchEngine, Type)
{
    this.Content.Search( Str, Props, SearchEngine, Type );
};

540 541 542 543 544
CHeaderFooter.prototype.Search_GetId = function(bNext, bCurrent)
{
    return this.Content.Search_GetId( bNext, bCurrent );
};

545
//----------------------------------------------------------------------------------------------------------------------
546
// CDocumentSectionsInfo
547
//----------------------------------------------------------------------------------------------------------------------
548
CDocumentSectionsInfo.prototype.Search = function(Str, Props, SearchEngine)
549
{
550 551 552
    var bEvenOdd = EvenAndOddHeaders;
    var Count = this.Elements.length;
    for ( var Index = 0; Index < Count; Index++ )
553
    {
554 555 556 557 558
        var SectPr = this.Elements[Index].SectPr;
        var bFirst = SectPr.Get_TitlePage();
        
        if ( null != SectPr.HeaderFirst && true === bFirst )
            SectPr.HeaderFirst.Search( Str, Props, SearchEngine, search_Header );
559

560 561
        if ( null != SectPr.HeaderEven && true === bEvenOdd )
            SectPr.HeaderEven.Search( Str, Props, SearchEngine, search_Header );
562

563 564
        if ( null != SectPr.HeaderDefault )
            SectPr.HeaderDefault.Search( Str, Props, SearchEngine, search_Header );
565

566 567
        if ( null != SectPr.FooterFirst && true === bFirst )
            SectPr.FooterFirst.Search( Str, Props, SearchEngine, search_Footer );
568

569 570
        if ( null != SectPr.FooterEven && true === bEvenOdd )
            SectPr.FooterEven.Search( Str, Props, SearchEngine, search_Footer );
571

572 573 574
        if ( null != SectPr.FooterDefault )
            SectPr.FooterDefault.Search( Str, Props, SearchEngine, search_Footer );                
    }            
575 576
};

577 578
CDocumentSectionsInfo.prototype.Search_GetId = function(bNext, CurHdrFtr)
{       
579
    var HdrFtrs = [];
580 581
    var CurPos  = -1;

582 583 584
    var bEvenOdd = EvenAndOddHeaders;
    var Count = this.Elements.length;
    for ( var Index = 0; Index < Count; Index++ )
585
    {
586 587
        var SectPr = this.Elements[Index].SectPr;
        var bFirst = SectPr.Get_TitlePage();
588

589 590 591
        if ( null != SectPr.HeaderFirst && true === bFirst )
        {
            HdrFtrs.push( SectPr.HeaderFirst );
592

593 594 595
            if ( CurHdrFtr === SectPr.HeaderFirst )
                CurPos = HdrFtrs.length - 1;
        }
596

597 598 599
        if ( null != SectPr.HeaderEven && true === bEvenOdd )
        {
            HdrFtrs.push( SectPr.HeaderEven );
600

601 602 603
            if ( CurHdrFtr === SectPr.HeaderEven )
                CurPos = HdrFtrs.length - 1;
        }
604

605 606 607
        if ( null != SectPr.HeaderDefault )
        {
            HdrFtrs.push( SectPr.HeaderDefault );
608

609 610 611
            if ( CurHdrFtr === SectPr.HeaderDefault )
                CurPos = HdrFtrs.length - 1;
        }
612

613 614 615
        if ( null != SectPr.FooterFirst && true === bFirst )
        {
            HdrFtrs.push( SectPr.FooterFirst );
616

617 618 619
            if ( CurHdrFtr === SectPr.FooterFirst )
                CurPos = HdrFtrs.length - 1;
        }
620

621 622 623
        if ( null != SectPr.FooterEven && true === bEvenOdd )
        {
            HdrFtrs.push( SectPr.FooterEven );
624

625 626 627
            if ( CurHdrFtr === SectPr.FooterEven )
                CurPos = HdrFtrs.length - 1;
        }
628

629 630 631
        if ( null != SectPr.FooterDefault )
        {
            HdrFtrs.push( SectPr.FooterDefault );
632

633 634 635 636 637
            if ( CurHdrFtr === SectPr.FooterDefault )
                CurPos = HdrFtrs.length - 1;
        }
    }
    
638 639 640 641
    var Count = HdrFtrs.length;

    if ( -1 != CurPos )
    {
642
        var Id = CurHdrFtr.Search_GetId( bNext, true );
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
        if ( null != Id )
            return Id;

        if ( true === bNext )
        {
            for ( var Index = CurPos + 1; Index < Count; Index++ )
            {
                Id = HdrFtrs[Index].Search_GetId( bNext, false );

                if ( null != Id )
                    return Id;
            }
        }
        else
        {
            for ( var Index = CurPos - 1; Index >= 0; Index-- )
            {
                Id = HdrFtrs[Index].Search_GetId( bNext, false );

                if ( null != Id )
                    return Id;
            }
        }
    }

    return null;
};
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
//----------------------------------------------------------------------------------------------------------------------
// CTable
//----------------------------------------------------------------------------------------------------------------------
CTable.prototype.Search = function(Str, Props, SearchEngine, Type)
{
    for ( var CurRow = 0; CurRow < this.Content.length; CurRow++ )
    {
        var Row = this.Content[CurRow];
        var CellsCount = Row.Get_CellsCount();

        for ( var CurCell = 0; CurCell < CellsCount; CurCell++ )
        {
            Row.Get_Cell( CurCell ).Content.Search( Str, Props, SearchEngine, Type );
        }
    }
};

687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
CTable.prototype.Search_GetId = function(bNext, bCurrent)
{
    if ( true === bCurrent )
    {
        var Id = null;
        var CurRow  = 0;
        var CurCell = 0;
        if ( true === this.Selection.Use && table_Selection_Cell === this.Selection.Type )
        {
            var Pos = ( true === bNext ? this.Selection.Data[this.Selection.Data.length - 1] : this.Selection.Data[0] );
            CurRow  = Pos.Row;
            CurCell = Pos.CurCell;
        }
        else
        {
            Id = this.CurCell.Content.Search_GetId(bNext, true);
703 704 705
            if ( Id != null )
                return Id;

706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
            CurRow  = this.CurCell.Row.Index;
            CurCell = this.CurCell.Index;
        }

        var Rows_Count = this.Content.length;
        if ( true === bNext )
        {
            for ( var _CurRow = CurRow; _CurRow < Rows_Count; _CurRow++ )
            {
                var Row = this.Content[_CurRow];
                var Cells_Count = Row.Get_CellsCount();
                var StartCell = ( _CurRow === CurRow ? CurCell + 1 : 0 );
                for ( var _CurCell = StartCell; _CurCell < Cells_Count; _CurCell++ )
                {
                    var Cell = Row.Get_Cell(_CurCell);
                    Id = Cell.Content.Search_GetId( true, false );
                    if ( null != Id )
                        return Id;
                }
            }
        }
        else
        {
            for ( var _CurRow = CurRow; _CurRow >= 0; _CurRow-- )
            {
                var Row = this.Content[_CurRow];
                var Cells_Count = Row.Get_CellsCount();
                var StartCell = ( _CurRow === CurRow ? CurCell - 1 : Cells_Count - 1 );
                for ( var _CurCell = StartCell; _CurCell >= 0; _CurCell-- )
                {
                    var Cell = Row.Get_Cell(_CurCell);
737
                    Id = Cell.Content.Search_GetId( false, false );
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
                    if ( null != Id )
                        return Id;
                }
            }

        }
    }
    else
    {
        var Rows_Count = this.Content.length;
        if ( true === bNext )
        {
            for ( var _CurRow = 0; _CurRow < Rows_Count; _CurRow++ )
            {
                var Row = this.Content[_CurRow];
                var Cells_Count = Row.Get_CellsCount();
                for ( var _CurCell = 0; _CurCell < Cells_Count; _CurCell++ )
                {
                    var Cell = Row.Get_Cell(_CurCell);
                    Id = Cell.Content.Search_GetId( true, false );
                    if ( null != Id )
                        return Id;
                }
            }
        }
        else
        {
            for ( var _CurRow = Rows_Count - 1; _CurRow >= 0; _CurRow-- )
            {
                var Row = this.Content[_CurRow];
                var Cells_Count = Row.Get_CellsCount();
                for ( var _CurCell = Cells_Count - 1; _CurCell >= 0; _CurCell-- )
                {
                    var Cell = Row.Get_Cell(_CurCell);
772
                    Id = Cell.Content.Search_GetId( false, false );
773 774 775 776 777 778 779 780 781 782
                    if ( null != Id )
                        return Id;
                }
            }

        }
    }

    return Id;
};
783 784 785 786 787 788
//----------------------------------------------------------------------------------------------------------------------
// Paragraph
//----------------------------------------------------------------------------------------------------------------------
Paragraph.prototype.Search = function(Str, Props, SearchEngine, Type)
{
    var bMatchCase = Props.MatchCase;
789 790 791
    var ParaSearch = new CParagraphSearch(this, Str, Props, SearchEngine, Type);
    var ContentLen = this.Content.length;
    for ( var CurPos = 0; CurPos < ContentLen; CurPos++ )
792
    {
793
        var Element = this.Content[CurPos];
794

795
        ParaSearch.ContentPos.Update( CurPos, 0 );
796

797 798
        Element.Search( ParaSearch, 1 );
    }
799

800 801 802 803 804 805
    var MaxShowValue = 100;
    for ( var FoundId in this.SearchResults )
    {
        var StartPos = this.SearchResults[FoundId].StartPos;
        var EndPos   = this.SearchResults[FoundId].EndPos;
        var ResultStr = new String();
806

807
        var _Str = Str;
808

809 810 811 812 813 814
        // Теперь мы должны сформировать строку
        if ( _Str.length >= MaxShowValue )
        {
            ResultStr = "\<b\>";
            for ( var Index = 0; Index < MaxShowValue - 1; Index++ )
                ResultStr += _Str[Index];
815

816
            ResultStr += "\</b\>...";
817
        }
818
        else
819
        {
820
            ResultStr = "\<b\>" + _Str + "\</b\>";
821

822 823 824
            var LeaveCount = MaxShowValue - _Str.length;
            var RunElementsAfter  = new CParagraphRunElements(EndPos, LeaveCount);
            var RunElementsBefore = new CParagraphRunElements(StartPos, LeaveCount);
825

826 827
            this.Get_NextRunElements(RunElementsAfter);
            this.Get_PrevRunElements(RunElementsBefore);
828

829
            var LeaveCount_2 = LeaveCount / 2;
830

831
            if ( RunElementsAfter.Elements.length >= LeaveCount_2 && RunElementsBefore.Elements.length >= LeaveCount_2 )
832
            {
833 834 835 836
                for ( var Index = 0; Index < LeaveCount_2; Index++ )
                {
                    var ItemB = RunElementsBefore.Elements[Index];
                    var ItemA = RunElementsAfter.Elements[Index];
837

838 839
                    ResultStr = (para_Text === ItemB.Type ? ItemB.Value : " ") + ResultStr + (para_Text === ItemA.Type ? ItemA.Value : " ");
                }
840
            }
841
            else if ( RunElementsAfter.Elements.length < LeaveCount_2 )
842
            {
843 844
                var TempCount = RunElementsAfter.Elements.length;
                for ( var Index = 0; Index < TempCount; Index++ )
845
                {
846 847 848
                    var ItemA = RunElementsAfter.Elements[Index];
                    ResultStr = ResultStr + (para_Text === ItemA.Type ? ItemA.Value : " ");
                }
849

850 851 852 853 854
                var TempCount = Math.min( 2 * LeaveCount_2 - RunElementsAfter.Elements.length, RunElementsBefore.Elements.length );
                for ( var Index = 0; Index < TempCount; Index++ )
                {
                    var ItemB = RunElementsBefore.Elements[Index];
                    ResultStr = (para_Text === ItemB.Type ? ItemB.Value : " ") + ResultStr;
855
                }
856 857 858 859 860
            }
            else
            {
                var TempCount = RunElementsAfter.Elements.length;
                for ( var Index = 0; Index < TempCount; Index++ )
861
                {
862 863
                    var ItemA = RunElementsAfter.Elements[Index];
                    ResultStr = ResultStr + (para_Text === ItemA.Type ? ItemA.Value : " ");
864
                }
865 866 867

                var TempCount = RunElementsBefore.Elements.length;
                for ( var Index = 0; Index < TempCount; Index++ )
868
                {
869 870
                    var ItemB = RunElementsBefore.Elements[Index];
                    ResultStr = (para_Text === ItemB.Type ? ItemB.Value : " ") + ResultStr;
871 872 873
                }
            }
        }
874 875

        this.SearchResults[FoundId].ResultStr = ResultStr;
876 877 878 879 880
    }
};

Paragraph.prototype.Search_GetId = function(bNext, bCurrent)
{
881 882 883 884
    // Определим позицию, начиная с которой мы будем искать ближайший найденный элемент
    var ContentPos = null;

    if ( true === bCurrent )
885
    {
886
        if ( true === this.Selection.Use )
887
        {
888 889
            var SSelContentPos = this.Get_ParaContentPos( true, true );
            var ESelContentPos = this.Get_ParaContentPos( true, false );
890

891
            if ( SSelContentPos.Compare( ESelContentPos ) > 0 )
892
            {
893 894 895
                var Temp = ESelContentPos;
                ESelContentPos = SSelContentPos;
                SSelContentPos = Temp;
896
            }
897

898 899 900 901
            if ( true === bNext )
                ContentPos = ESelContentPos;
            else
                ContentPos = SSelContentPos;
902 903
        }
        else
904
            ContentPos = this.Get_ParaContentPos( false, false );
905 906 907
    }
    else
    {
908 909 910 911 912
        if ( true === bNext )
            ContentPos = this.Get_StartPos();
        else
            ContentPos = this.Get_EndPos( false );
    }
913

914 915 916 917 918
    // Производим поиск ближайшего элемента
    if ( true === bNext )
    {
        var StartPos = ContentPos.Get(0);
        var ContentLen = this.Content.length;
919

920
        for ( var CurPos = StartPos; CurPos < ContentLen; CurPos++ )
921
        {
922 923 924
            var ElementId = this.Content[CurPos].Search_GetId( true, CurPos === StartPos ? true : false, ContentPos, 1 );
            if ( null !== ElementId )
                return ElementId;
925
        }
926 927 928 929 930
    }
    else
    {
        var StartPos = ContentPos.Get(0);
        var ContentLen = this.Content.length;
931

932
        for ( var CurPos = StartPos; CurPos >= 0; CurPos-- )
933
        {
934 935 936
            var ElementId = this.Content[CurPos].Search_GetId( false, CurPos === StartPos ? true : false, ContentPos, 1 );
            if ( null !== ElementId )
                return ElementId;
937
        }
938
    }
939 940

    return null;
941 942
};

943
Paragraph.prototype.Add_SearchResult = function(Id, StartContentPos, EndContentPos, Type)
944
{
945 946 947 948 949 950 951 952 953 954 955 956 957 958
    var SearchResult = new CParagraphSearchElement( StartContentPos, EndContentPos, Type, Id );

    this.SearchResults[Id] = SearchResult;

    SearchResult.ClassesS.push( this );
    SearchResult.ClassesE.push( this );

    this.Content[StartContentPos.Get(0)].Add_SearchResult( SearchResult, true, StartContentPos, 1 );
    this.Content[EndContentPos.Get(0)].Add_SearchResult( SearchResult, false, EndContentPos, 1 );
};

Paragraph.prototype.Clear_SearchResults = function()
{
    for ( var Id in this.SearchResults )
959
    {
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
        var SearchResult = this.SearchResults[Id];

        var ClassesCount = SearchResult.ClassesS.length;
        for ( var Pos = 1; Pos < ClassesCount; Pos++ )
        {
            SearchResult.ClassesS[Pos].Clear_SearchResults();
        }

        var ClassesCount = SearchResult.ClassesE.length;
        for ( var Pos = 1; Pos < ClassesCount; Pos++ )
        {
            SearchResult.ClassesE[Pos].Clear_SearchResults();
        }
    }

975
    this.SearchResults = {};
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
};

Paragraph.prototype.Remove_SearchResult = function(Id)
{
    var SearchResult = this.SearchResults[Id];
    if ( undefined !== SearchResult )
    {
        var ClassesCount = SearchResult.ClassesS.length;
        for ( var Pos = 1; Pos < ClassesCount; Pos++ )
        {
            SearchResult.ClassesS[Pos].Remove_SearchResult(SearchResult);
        }

        var ClassesCount = SearchResult.ClassesE.length;
        for ( var Pos = 1; Pos < ClassesCount; Pos++ )
        {
            SearchResult.ClassesE[Pos].Remove_SearchResult(SearchResult);
        }

        delete this.SearchResults[Id];
    }
};

//----------------------------------------------------------------------------------------------------------------------
// ParaRun
//----------------------------------------------------------------------------------------------------------------------
ParaRun.prototype.Search = function(ParaSearch, Depth)
{
1004
    this.SearchMarks = [];
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025

    var Para         = ParaSearch.Paragraph;
    var Str          = ParaSearch.Str;
    var Props        = ParaSearch.Props;
    var SearchEngine = ParaSearch.SearchEngine;
    var Type         = ParaSearch.Type;

    var MatchCase    = Props.MatchCase;

    var ContentLen = this.Content.length;

    for ( var Pos = 0; Pos < ContentLen; Pos++ )
    {
        var Item = this.Content[Pos];

        if ( para_Drawing === Item.Type )
        {
            Item.Search( Str, Props, SearchEngine, Type );
            ParaSearch.Reset();
        }

1026
        if ( (" " === Str[ParaSearch.SearchIndex] && para_Space === Item.Type)|| (para_Math_Text == Item.Type && Item.value === Str.charCodeAt(ParaSearch.SearchIndex)) || ( para_Text === Item.Type && (  ( true != MatchCase && (String.fromCharCode(Item.Value)).toLowerCase() === Str[ParaSearch.SearchIndex].toLowerCase() ) || ( true === MatchCase && Item.Value === Str.charCodeAt(ParaSearch.SearchIndex) ) ) ) )
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
        {
            if ( 0 === ParaSearch.SearchIndex )
            {
                var StartContentPos = ParaSearch.ContentPos.Copy();
                StartContentPos.Update( Pos, Depth );
                ParaSearch.StartPos = StartContentPos;
            }

            ParaSearch.SearchIndex++;

            if ( ParaSearch.SearchIndex === Str.length )
            {
                var EndContentPos = ParaSearch.ContentPos.Copy();
                EndContentPos.Update( Pos + 1, Depth );

                var Id = SearchEngine.Add( Para );
                Para.Add_SearchResult( Id, ParaSearch.StartPos, EndContentPos, Type );

                // Обнуляем поиск
                ParaSearch.Reset();
            }
        }
        else if ( 0 !== ParaSearch.SearchIndex )
        {
            // Обнуляем поиск
            ParaSearch.Reset();
        }
    }
};

ParaRun.prototype.Add_SearchResult = function(SearchResult, Start, ContentPos, Depth)
{
    if ( true === Start )
        SearchResult.ClassesS.push( this );
    else
        SearchResult.ClassesE.push( this );

    this.SearchMarks.push( new CParagraphSearchMark( SearchResult, Start, Depth ) );
};

ParaRun.prototype.Clear_SearchResults = function()
{
1069
    this.SearchMarks = [];
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
};

ParaRun.prototype.Remove_SearchResult = function(SearchResult)
{
    var MarksCount = this.SearchMarks.length;
    for ( var Index = 0; Index < MarksCount; Index++ )
    {
        var Mark = this.SearchMarks[Index];
        if ( SearchResult === Mark.SearchResult )
        {
            this.SearchMarks.splice( Index, 1 );
            Index--;
            MarksCount--;
        }
    }
};

ParaRun.prototype.Search_GetId = function(bNext, bUseContentPos, ContentPos, Depth)
{
    var StartPos = 0;

    if ( true === bUseContentPos )
    {
        StartPos = ContentPos.Get( Depth );
1094 1095 1096 1097
    }
    else
    {
        if ( true === bNext )
1098 1099 1100
        {
            StartPos = 0;
        }
1101
        else
1102 1103 1104
        {
            StartPos = this.Content.length;
        }
1105 1106
    }

1107
    var NearElementId = null;
1108 1109 1110

    if ( true === bNext )
    {
1111 1112 1113 1114
        var NearPos = this.Content.length;

        var SearchMarksCount = this.SearchMarks.length;
        for ( var SPos = 0; SPos < SearchMarksCount; SPos++)
1115
        {
1116 1117 1118 1119
            var Mark = this.SearchMarks[SPos];
            var MarkPos = Mark.SearchResult.StartPos.Get(Mark.Depth);

            if ( MarkPos >= StartPos && MarkPos < NearPos )
1120
            {
1121 1122
                NearElementId = Mark.SearchResult.Id;
                NearPos       = MarkPos;
1123 1124
            }
        }
1125

1126
        for ( var CurPos = StartPos; CurPos < NearPos; CurPos++ )
1127
        {
1128
            var Item = this.Content[CurPos];
1129 1130 1131 1132 1133 1134 1135
            if ( para_Drawing === Item.Type )
            {
                var TempElementId = Item.Search_GetId( true, false );
                if ( null != TempElementId )
                    return TempElementId;
            }
        }
1136 1137 1138
    }
    else
    {
1139 1140 1141 1142
        var NearPos = -1;

        var SearchMarksCount = this.SearchMarks.length;
        for ( var SPos = 0; SPos < SearchMarksCount; SPos++)
1143
        {
1144 1145 1146 1147
            var Mark = this.SearchMarks[SPos];
            var MarkPos = Mark.SearchResult.StartPos.Get(Mark.Depth);

            if ( MarkPos < StartPos && MarkPos > NearPos )
1148
            {
1149 1150
                NearElementId = Mark.SearchResult.Id;
                NearPos       = MarkPos;
1151 1152
            }
        }
1153

1154
        StartPos = Math.min( this.Content.length - 1, StartPos - 1 );
1155
        for ( var CurPos = StartPos; CurPos > NearPos; CurPos-- )
1156
        {
1157
            var Item = this.Content[CurPos];
1158 1159 1160 1161 1162 1163 1164
            if ( para_Drawing === Item.Type )
            {
                var TempElementId = Item.Search_GetId( false, false );
                if ( null != TempElementId )
                    return TempElementId;
            }
        }
1165

1166 1167 1168
    }

    return NearElementId;
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
};

//----------------------------------------------------------------------------------------------------------------------
// ParaComment
//----------------------------------------------------------------------------------------------------------------------
ParaComment.prototype.Search = function(ParaSearch, Depth)
{
};

ParaComment.prototype.Add_SearchResult = function(SearchResult, Start, ContentPos, Depth)
{
};

ParaComment.prototype.Clear_SearchResults = function()
{
};

ParaComment.prototype.Remove_SearchResult = function(SearchResult)
{
};

ParaComment.prototype.Search_GetId = function(bNext, bUseContentPos, ContentPos, Depth)
{
    return null;
};
1194 1195 1196
//----------------------------------------------------------------------------------------------------------------------
// ParaMath
//----------------------------------------------------------------------------------------------------------------------
Ilya.Kirillov's avatar
Ilya.Kirillov committed
1197
ParaMath.prototype.Search = function(ParaSearch, Depth)
1198 1199
{
    // Обнуляем поиск
1200 1201 1202 1203 1204 1205
    //ParaSearch.Reset();

    this.SearchMarks = [];
    this.Root.Search(ParaSearch, Depth);


1206 1207
};

Ilya.Kirillov's avatar
Ilya.Kirillov committed
1208
ParaMath.prototype.Add_SearchResult = function(SearchResult, Start, ContentPos, Depth)
1209
{
1210
    this.Root.Add_SearchResult(SearchResult, Start, ContentPos, Depth);
1211 1212
};

Ilya.Kirillov's avatar
Ilya.Kirillov committed
1213
ParaMath.prototype.Clear_SearchResults = function()
1214
{
1215
    this.Root.Clear_SearchResults();
1216 1217
};

Ilya.Kirillov's avatar
Ilya.Kirillov committed
1218
ParaMath.prototype.Remove_SearchResult = function(SearchResult)
1219
{
1220
    this.Root.Remove_SearchResult(SearchResult);
1221
};
1222

Ilya.Kirillov's avatar
Ilya.Kirillov committed
1223
ParaMath.prototype.Search_GetId = function(bNext, bUseContentPos, ContentPos, Depth)
1224
{
1225 1226
    return this.Root.Search_GetId(bNext, bUseContentPos, ContentPos, Depth);
    //return null;
1227
};
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260

//----------------------------------------------------------------------------------------------------------------------
// Вспомогательные классы для поиска внутри параграфа
//----------------------------------------------------------------------------------------------------------------------
function CParagraphSearch(Paragraph, Str, Props, SearchEngine, Type)
{
    this.Paragraph    = Paragraph;
    this.Str          = Str;
    this.Props        = Props;
    this.SearchEngine = SearchEngine;
    this.Type         = Type;

    this.ContentPos   = new CParagraphContentPos();

    this.StartPos     = null; // Запоминаем здесь стартовую позицию поиска
    this.SearchIndex  = 0;    // Номер символа, с которым мы проверяем совпадение
}

CParagraphSearch.prototype =
{
    Reset : function()
    {
        this.StartPos    = null;
        this.SearchIndex = 0;
    }
};

function CParagraphSearchMark(SearchResult, Start, Depth)
{
    this.SearchResult = SearchResult;
    this.Start        = Start;
    this.Depth        = Depth;
}