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

3 4 5 6 7
/*var Math_Draw_Time  = false;
var Math_Date = 0;
var Math_NeedResize = true;
var Math_Date_Draw = 0;*/

8 9 10
/**
 * Created by Ilja.Kirillov on 18.03.14.
 */
11 12 13 14

var g_dMathArgSizeKoeff_1 = 0.76;
var g_dMathArgSizeKoeff_2 = 0.76 * 0.855;

15
var g_oMathSettings = {};
16 17 18 19 20
function MathMenu (type)
{
	this.Type = para_Math;
	this.Menu = type;
}
21 22 23 24 25 26 27
MathMenu.prototype =
{
	Get_Type : function()
    {
        return this.Type;
    }
}
28
function ParaMath()
29
{
30 31
    ParaMath.superclass.constructor.call(this);

32 33 34
    this.Id = g_oIdCounter.Get_NewId();
    this.Type  = para_Math;

35
    this.Jc       = undefined;
36 37

    this.Root       = new CMathContent();
38
    this.Root.bRoot = true;
39 40 41 42

    this.X          = 0;
    this.Y          = 0;

43
    this.bInline           = false;
44
    this.bChangeInline     = true;
45
    this.NeedResize        = true;
46 47
    this.bSelectionUse     = false;

48
    //this.State      = new CParaRunState();       // Положение курсора и селекта для данного run
49 50
    this.Paragraph  = null;

51
    this.NearPosArray = [];
52

53 54 55 56 57 58
    this.Width        = 0;
    this.WidthVisible = 0;
    this.Height       = 0;
    this.Ascent       = 0;
    this.Descent      = 0;

59 60
    this.DefaultTextPr = new CTextPr();

61
    this.DefaultTextPr.FontSize   = 11;
62 63 64
    this.DefaultTextPr.FontFamily = {Name  : "Cambria Math", Index : -1 };
    this.DefaultTextPr.RFonts.Set_All("Cambria Math", -1);

65
    // Добавляем данный класс в таблицу Id (обязательно в конце конструктора)
66
	g_oTableId.Add( this, this.Id );
67 68
}

69
Asc.extendClass(ParaMath, CParagraphContentWithContentBase);
70 71 72 73 74 75 76 77 78 79

ParaMath.prototype.Get_Type = function()
{
    return this.Type;
};

ParaMath.prototype.Get_Id = function()
{
    return this.Id;
};
80

81
ParaMath.prototype.Copy = function(Selected)
82
{
83
    var NewMath = new ParaMath();
84
    NewMath.Root.bRoot = true;
85 86

    if(Selected)
87
    {
88
        var result = this.GetSelectContent();
89
        result.Content.CopyTo(NewMath.Root, Selected);
90 91
    }
    else
92
    {
93
        this.Root.CopyTo(NewMath.Root, Selected);
94
    }
95

96
    /// argSize, bDot и bRoot выставить на объединении контентов
97

98
    NewMath.SetNeedResize();
99
    NewMath.Root.Correct_Content(true);
100

101 102
    return NewMath;
};
103

104 105 106 107
ParaMath.prototype.Set_Paragraph = function(Paragraph)
{
    this.Paragraph = Paragraph;
};
108

109 110
ParaMath.prototype.Is_Empty = function()
{
111
    if (this.Root.Content.length <= 0)
112 113
        return true;

114 115
    if (1 === this.Root.Content.length)
        return this.Root.Content[0].Is_Empty({SkipPlcHldr : true});
116 117

    return false;
118
};
119

120 121 122 123 124
ParaMath.prototype.Is_CheckingNearestPos = function()
{
    return this.Root.Is_CheckingNearestPos();
};

125 126 127 128
ParaMath.prototype.Is_StartFromNewLine = function()
{
    return false;
};
129

130 131 132
ParaMath.prototype.Get_TextPr = function(_ContentPos, Depth)
{
    // TODO: ParaMath.Get_TextPr
133

134
    var TextPr = new CTextPr();
135

136 137
    var mTextPr = this.Root.Get_TextPr(_ContentPos, Depth);
    TextPr.Merge( mTextPr );
138 139


140 141
    return TextPr;
};
142

143 144 145
ParaMath.prototype.Get_CompiledTextPr = function(Copy)
{
    // TODO: ParaMath.Get_CompiledTextPr
146

147
    //var TextPr = new CTextPr();
148

149 150
    var oContent = this.GetSelectContent();
    var mTextPr = oContent.Content.Get_CompiledTextPr(Copy);
151
    //TextPr.Merge( mTextPr );
152

153
    return mTextPr;
154
};
155

156 157
ParaMath.prototype.Add = function(Item)
{
158 159
    this.NeedResize = true;

160
    var Type = Item.Type;
161 162 163
    var oSelectedContent = this.GetSelectContent();

    var oContent = oSelectedContent.Content;
164

165
    var StartPos = oSelectedContent.Start;
166
    var Run = oContent.Content[StartPos];
167

168 169 170
    // Мы вставляем только в Run
    if (para_Math_Run !== Run.Type)
        return;
171

172
    var NewElement = null;
173
    if (para_Text === Type)
174
    {
175 176
        if(Item.Value == 38)
        {
177 178
            NewElement = new CMathAmp();
            Run.Add(NewElement, true);
179 180 181
        }
        else
        {
182 183 184
            NewElement = new CMathText(false);
            NewElement.add(Item.Value);
            Run.Add(NewElement, true);
185
        }
186
    }
187
    else if (para_Space === Type)
188
    {
189 190 191
        NewElement = new CMathText(false);
        NewElement.addTxt(" ");
        Run.Add(NewElement, true);
192
    }
193
    else if (para_Math === Type)
194
    {
195 196 197 198 199 200 201 202 203
        var ContentPos = new CParagraphContentPos();

        if(this.bSelectionUse == true)
            this.Get_ParaContentPos(true, true, ContentPos);
        else
            this.Get_ParaContentPos(false, false, ContentPos);

        var MathTxtPr = this.Root.GetMathTextPr(ContentPos, 0);

204 205 206 207
        // Нам нужно разделить данный Run на 2 части
        var RightRun = Run.Split2(Run.State.ContentPos);

        oContent.Internal_Content_Add(StartPos + 1, RightRun, false);
208
        // Выставляем позицию в начало этого рана
209
        oContent.CurPos = StartPos + 1;
210
        RightRun.Cursor_MoveToStartPos();
211

212
        var lng = oContent.Content.length;
213
        oContent.Load_FromMenu(Item.Menu, this.Paragraph);
214

215
        var lng2 = oContent.Content.length;
216
        oContent.Set_MathTextPr2(MathTxtPr.TextPr, MathTxtPr.MathPr, false, StartPos + 1, lng2 - lng);
217
    }
218

219 220 221 222 223 224
    if ((para_Text === Type || para_Space === Type) && null !== NewElement)
    {
        // Пробуем произвести автозамену
        oContent.Process_AutoCorrect(NewElement);
    }

225 226
    // Корректируем данный контент
    oContent.Correct_Content(true);
227
};
228

229 230
ParaMath.prototype.Remove = function(Direction, bOnAddText)
{
231
	this.NeedResize = true;
232
    var oSelectedContent = this.GetSelectContent();
233

234 235 236
    var nStartPos = oSelectedContent.Start;
    var nEndPos = oSelectedContent.End;
    var oContent = oSelectedContent.Content;
237

238 239 240 241 242 243
    if (nStartPos === nEndPos)
    {
        var oElement = oContent.getElem(nStartPos);

        // Если данный элемент - ран, удаляем внутри рана, если нет, тогда удаляем целиком элемент
        if (para_Math_Run === oElement.Type)
244
        {
245
            if (false === oElement.Remove(Direction) && true !== this.bSelectionUse)
246
            {
247
                if ((Direction > 0 && oContent.Content.length - 1 === nStartPos) || (Direction < 0 && 0 === nStartPos))
248 249 250 251 252
                {
                    // Проверяем находимся ли мы на верхнем уровне
                    if (oContent.bRoot)
                        return false;

253
                    // Значит мы в каком-то элементе, тогда надо выделить данный элемент
254
                    oContent.ParentElement.Select_WholeElement();
255 256 257 258 259

                    return true;
                }

                if (Direction > 0)
260
                {
261 262
                    var oNextElement = oContent.getElem(nStartPos + 1);
                    if (para_Math_Run === oNextElement.Type)
263
                    {
264 265 266 267 268 269 270 271 272 273 274 275
                        // Здесь мы не проверяем результат Remove, потому что ран не должен быть пустым после
                        // Correct_Content
                        oNextElement.Cursor_MoveToStartPos();
                        oNextElement.Remove(1);

                        if (oNextElement.Is_Empty())
                        {
                            oContent.Correct_Content();
                            oContent.Correct_ContentPos(1);
                        }

                        this.Selection_Remove();
276
                    }
277
                    else
278
                    {
279
                        oContent.Select_ElementByPos(nStartPos + 1, true);
280 281
                    }
                }
282
                else //if (Direction < 0)
283
                {
284 285
                    var oPrevElement = oContent.getElem(nStartPos - 1);
                    if (para_Math_Run === oPrevElement.Type)
286
                    {
287 288 289 290 291 292
                        // Здесь мы не проверяем результат Remove, потому что ран не должен быть пустым после
                        // Correct_Content
                        oPrevElement.Cursor_MoveToEndPos();
                        oPrevElement.Remove(-1);

                        if (oPrevElement.Is_Empty())
293
                        {
294 295
                            oContent.Correct_Content();
                            oContent.Correct_ContentPos(-1);
296
                        }
297 298 299 300 301

                        this.Selection_Remove();
                    }
                    else
                    {
302
                        oContent.Select_ElementByPos(nStartPos - 1, true);
303 304 305
                    }
                }
            }
306
            else
307
            {
308 309 310 311 312 313 314 315
                if (oElement.Is_Empty())
                {
                    oContent.CurPos = nStartPos;
                    oContent.Correct_Content();
                    oContent.Correct_ContentPos(-1); // -1, потому что нам надо встать перед элементом, а не после
                }

                this.Selection_Remove();
316
            }
317 318 319 320 321 322 323 324

            return true;
        }
        else
        {
            oContent.Remove_FromContent(nStartPos, 1);

            oContent.CurPos = nStartPos;
325

326 327
            if (para_Math_Run === oContent.Content[nStartPos].Type)
                oContent.Content[nStartPos].Cursor_MoveToStartPos();
328

329 330 331 332
            oContent.Correct_Content();
            oContent.Correct_ContentPos(-1); // -1, потому что нам надо встать перед элементом, а не после

            this.Selection_Remove();
333
        }
334 335
    }
    else
336 337 338 339 340 341 342
    {
        if (nStartPos > nEndPos)
        {
            var nTemp = nEndPos;
            nEndPos = nStartPos;
            nStartPos = nTemp;
        }
343

344 345 346
        // Проверяем начальный и конечный элементы
        var oStartElement = oContent.getElem(nStartPos);
        var oEndElement = oContent.getElem(nEndPos);
347

348 349 350 351 352
        // Если последний элемент - ран, удаляем внутри, если нет, тогда удаляем целиком элемент
        if (para_Math_Run === oEndElement.Type)
            oEndElement.Remove(Direction);
        else
            oContent.Remove_FromContent(nEndPos, 1);
353

354 355
        // Удаляем все промежуточные элементы
        oContent.Remove_FromContent(nStartPos + 1, nEndPos - nStartPos - 1);
356

357 358 359 360 361 362 363 364 365 366 367 368
        // Если первый элемент - ран, удаляем внутри рана, если нет, тогда удаляем целиком элемент
        if (para_Math_Run === oStartElement.Type)
            oStartElement.Remove(Direction);
        else
            oContent.Remove_FromContent(nStartPos, 1);

        oContent.CurPos = nStartPos;
        oContent.Correct_Content();
        oContent.Correct_ContentPos(Direction);
        this.Selection_Remove();
    }
};
369

370 371 372 373
ParaMath.prototype.GetSelectContent = function()
{
    return this.Root.GetSelectContent();
};
374

375 376
ParaMath.prototype.Get_CurrentParaPos = function()
{
377 378 379 380 381 382 383 384 385 386 387
    var nLinesCount = this.protected_GetLinesCount();
    for (var nLineIndex = 0; nLineIndex < nLinesCount; nLineIndex++)
    {
        var nRangesCount = this.protected_GetRangesCount(nLineIndex);
        for (var nRangeIndex = 0; nRangeIndex < nRangesCount; nRangeIndex++)
        {
            var nEndPos = this.protected_GetRangeEndPos(nLineIndex, nRangeIndex);
            if (nEndPos > 0)
                return new CParaPos(0 === nLineIndex ? this.StartRange + nRangeIndex : nRangeIndex, this.StartLine + nLineIndex, 0, 0);
        }
    }
388

389
    return new CParaPos(this.StartRange, this.StartLine, 0, 0);
390
};
391

392 393 394
ParaMath.prototype.Apply_TextPr = function(TextPr, IncFontSize, ApplyToAll)
{
    // TODO: ParaMath.Apply_TextPr
395

396 397
    this.NeedResize = true;

398

399
    if(ApplyToAll == true) // для ситуации, когда ApplyToAll = true, в Root формулы при этом позиции селекта не проставлены
400
    {
401 402 403
        this.Root.Apply_TextPr(TextPr, IncFontSize, true);
    }
    else
404
    {
405
        var content = this.GetSelectContent().Content;
406

407
        if(IncFontSize == undefined)
408
        {
409
            var FontSize = TextPr.FontSize;
410

411 412 413 414
            if(TextPr.FontSize !== undefined && content.IsNormalTextInRuns() == false)
            {
                var NewTextPr = new CTextPr();
                NewTextPr.FontSize   = FontSize;
415

416 417 418 419 420 421
                this.Root.Apply_TextPr(NewTextPr, IncFontSize, true);

                TextPr.FontSize   = undefined;
            }

            content.Apply_TextPr(TextPr, IncFontSize, ApplyToAll);
422

423 424 425 426 427 428 429 430 431 432
            TextPr.FontSize   = FontSize;

        }
        else
        {
            if(content.IsNormalTextInRuns() == false)
                this.Root.Apply_TextPr(TextPr, IncFontSize, true);
            else
                content.Apply_TextPr(TextPr, IncFontSize, ApplyToAll);
        }
433

434
    }
435 436 437
};
ParaMath.prototype.Clear_TextPr = function()
{
438

439
};
440

441 442
ParaMath.prototype.Check_NearestPos = function(ParaNearPos, Depth)
{
443
    this.Root.Check_NearestPos(ParaNearPos, Depth);
444 445 446 447 448 449 450 451 452 453 454 455 456 457
};

ParaMath.prototype.Get_DrawingObjectRun = function(Id)
{
    return null;
};

ParaMath.prototype.Get_DrawingObjectContentPos = function(Id, ContentPos, Depth)
{
    return false;
};

ParaMath.prototype.Get_Layout = function(DrawingLayout, UseContentPos, ContentPos, Depth)
{
458 459 460 461
    if (true === UseContentPos)
        DrawingLayout.Layout = true;
    else
        DrawingLayout.X += this.Width;
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
};

ParaMath.prototype.Get_NextRunElements = function(RunElements, UseContentPos, Depth)
{
};

ParaMath.prototype.Get_PrevRunElements = function(RunElements, UseContentPos, Depth)
{
};

ParaMath.prototype.Collect_DocumentStatistics = function(ParaStats)
{
    // TODO: ParaMath.Collect_DocumentStatistics
};

ParaMath.prototype.Create_FontMap = function(Map)
{
    // TODO: ParaMath.Create_FontMap

    // Styles.js
    // Document_CreateFontMap
483

484
    this.Root.Create_FontMap(Map);
485

486 487 488 489 490
};

ParaMath.prototype.Get_AllFontNames = function(AllFonts)
{
    // TODO: ParaMath.Get_AllFontNames
491

492 493 494 495 496 497 498 499 500
    // выставить для всех шрифтов, к-ые используются в AllFonts true
    AllFonts["Cambria Math"] = true;

    this.Root.Get_AllFontNames(AllFonts);
};

ParaMath.prototype.Get_SelectedText = function(bAll, bClearText)
{
    if ( true === bAll || true === this.Selection_IsUse() )
501
    {
502 503
        if ( true === bClearText )
            return null;
504 505

        return "";
506
    }
507

508 509
    return "";
};
510

511 512 513 514 515
ParaMath.prototype.Get_SelectionDirection = function()
{
    return this.Root.Get_SelectionDirection();
};

516 517 518
ParaMath.prototype.Clear_TextFormatting = function( DefHyper )
{
};
519

520 521 522 523
ParaMath.prototype.Can_AddDropCap = function()
{
    return false;
};
524

525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
ParaMath.prototype.Get_TextForDropCap = function(DropCapText, UseContentPos, ContentPos, Depth)
{
    if ( true === DropCapText.Check )
        DropCapText.Mixed = true;
};

ParaMath.prototype.Get_StartTabsCount = function(TabsCounter)
{
    return false;
};

ParaMath.prototype.Remove_StartTabs = function(TabsCounter)
{
    return false;
};
540

541 542 543 544
ParaMath.prototype.Add_ToContent = function(Pos, Item, UpdatePosition)
{

};
545 546 547
//-----------------------------------------------------------------------------------
// Функции пересчета
//-----------------------------------------------------------------------------------
548 549 550 551
ParaMath.prototype.Recalculate_Range = function(PRS, ParaPr, Depth)
{
    // TODO: Пока у нас контент здесь состоит из 1 элемента (всего элемента Math). Поэтому у нас в данном
    //       контенте есть 2 позиции 0 и 1, т.е. до или после Math.
552

553
    if ( this.Paragraph !== PRS.Paragraph )
554
    {
555
        this.Paragraph = PRS.Paragraph;
556
        this.protected_UpdateSpellChecking();
557
    }
558

559 560
    var CurLine  = PRS.Line - this.StartLine;
    var CurRange = ( 0 === CurLine ? PRS.Range - this.StartRange : PRS.Range );
Anna.Pavlova's avatar
Anna.Pavlova committed
561

562 563 564
    var Para      = PRS.Paragraph;
    var ParaLine  = PRS.Line;
    var ParaRange = PRS.Range;
Anna.Pavlova's avatar
Anna.Pavlova committed
565 566


567
    var RPI = new CRPI();
568 569
    RPI.bInline       = this.bInline;
    RPI.bChangeInline = this.bChangeInline;
570
    RPI.NeedResize    = this.NeedResize;
571
    RPI.PRS           = PRS;
Anna.Pavlova's avatar
Anna.Pavlova committed
572

573
    var ArgSize = new CMathArgSize();
574

575 576
    if(PRS.NewRange  == false)
        this.Root.Recalculate_Reset(PRS.Range, PRS.Line);
577

578 579
    if(RPI.NeedResize)
    {
580
        this.Root.Set_Paragraph(Para);
581
        this.Root.Set_ParaMath(this);
582 583
        this.Root.PreRecalc(null, this, ArgSize, RPI);
        this.Root.Resize(g_oTextMeasurer, RPI/*recalculate properties info*/);
584 585 586 587
        // когда формула будеат разбиваться на строки, Position придется перерасчитывать
        var pos = new CMathPosition();
        pos.x = 0;
        pos.y = 0;
588

589 590 591 592
        this.Root.setPosition(pos);
    }
    else
        this.Root.Resize_2(g_oTextMeasurer, null, this, RPI/*recalculate properties info*/, ArgSize);
593

594 595
    this.NeedResize = false;

596 597 598
    var OldLineTextAscent  = PRS.LineTextAscent;
    var OldLineTextAscent2 = PRS.LineTextAscent2;
    var OldLineTextDescent = PRS.LineTextDescent;
599

600 601 602 603 604
    this.Width        = this.Root.size.width;
    this.Height       = this.Root.size.height;
    this.WidthVisible = this.Root.size.width;
    this.Ascent       = this.Root.size.ascent;
    this.Descent      = this.Root.size.height - this.Root.size.ascent;
605

606 607 608 609 610
    //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    // TODO: ParaMath.Recalculate_Range
    // Пока логика пересчета здесь аналогична логике пересчета отдельного символа в ParaRun. В будущем надо будет
    // переделать с разбиванием на строки.
    //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Anna.Pavlova's avatar
Anna.Pavlova committed
611

612 613
    var RangeStartPos = this.protected_AddRange(CurLine, CurRange);
    var RangeEndPos   = 0;
Anna.Pavlova's avatar
Anna.Pavlova committed
614

615 616 617 618 619 620 621 622 623 624 625
    // Отмечаем, что началось слово
    PRS.StartWord = true;

    // При проверке, убирается ли слово, мы должны учитывать ширину предшествующих пробелов.
    var LetterLen = this.Width;
    if ( true !== PRS.Word )
    {
        // Слово только началось. Делаем следующее:
        // 1) Если до него на строке ничего не было и данная строка не
        //    имеет разрывов, тогда не надо проверять убирается ли слово в строке.
        // 2) В противном случае, проверяем убирается ли слово в промежутке.
Anna.Pavlova's avatar
Anna.Pavlova committed
626

627 628
        // Если слово только началось, и до него на строке ничего не было, и в строке нет разрывов, тогда не надо проверять убирается ли оно на строке.
        if ( true !== PRS.FirstItemOnLine || false === Para.Internal_Check_Ranges(ParaLine, ParaRange) )
Anna.Pavlova's avatar
Anna.Pavlova committed
629
        {
630
            if ( PRS.X + PRS.SpaceLen + LetterLen > PRS.XEnd )
Anna.Pavlova's avatar
Anna.Pavlova committed
631
            {
632
                PRS.NewRange  = true;
Anna.Pavlova's avatar
Anna.Pavlova committed
633 634 635
            }
        }

636
        if ( true !== PRS.NewRange )
Anna.Pavlova's avatar
Anna.Pavlova committed
637
        {
638 639 640 641
            // Отмечаем начало нового слова
            PRS.Set_LineBreakPos( 0 );
            PRS.WordLen = this.Width;
            PRS.Word    = true;
Anna.Pavlova's avatar
Anna.Pavlova committed
642
        }
643 644 645 646
    }
    else
    {
        if ( PRS.X + PRS.SpaceLen + PRS.WordLen + LetterLen > PRS.XEnd )
Anna.Pavlova's avatar
Anna.Pavlova committed
647
        {
648
            if ( true === PRS.FirstItemOnLine )
Anna.Pavlova's avatar
Anna.Pavlova committed
649
            {
650 651 652 653 654 655 656 657 658 659 660
                // Слово оказалось единственным элементом в промежутке, и, все равно,
                // не умещается целиком. Делаем следующее:
                //
                // 1) Если у нас строка без вырезов, тогда ставим перенос строки на
                //    текущей позиции.
                // 2) Если у нас строка с вырезом, и данный вырез не последний, тогда
                //    ставим перенос внутри строки в начале слова.
                // 3) Если у нас строка с вырезом и вырез последний, тогда ставим перенос
                //    строки в начале слова.

                if ( false === Para.Internal_Check_Ranges(ParaLine, ParaRange)  )
Anna.Pavlova's avatar
Anna.Pavlova committed
661
                {
662 663 664
                    // Слово не убирается в отрезке. Переносим слово в следующий отрезок
                    PRS.MoveToLBP = true;
                    PRS.NewRange  = true; // перенос на новую строку
Anna.Pavlova's avatar
Anna.Pavlova committed
665 666 667
                }
                else
                {
668 669 670 671 672 673
                    PRS.EmptyLine   = false;
                    //PRS.X          += WordLen;

                    // Слово не убирается в отрезке, но, поскольку, слово 1 на строке и отрезок тоже 1,
                    // делим слово в данном месте
                    PRS.NewRange = true; // перенос на новую строку
Anna.Pavlova's avatar
Anna.Pavlova committed
674 675
                }
            }
676
            else
Anna.Pavlova's avatar
Anna.Pavlova committed
677
            {
678 679 680
                // Слово не убирается в отрезке. Переносим слово в следующий отрезок
                PRS.MoveToLBP = true;
                PRS.NewRange  = true;
Anna.Pavlova's avatar
Anna.Pavlova committed
681 682 683
            }
        }

684 685 686 687 688 689
        if ( true !== PRS.NewRange )
        {
            // Мы убираемся в пределах данной строки. Прибавляем ширину буквы к ширине слова
            PRS.WordLen += LetterLen;
        }
    }
690

691 692
    if ( true !== PRS.NewRange )
    {
693
        RangeEndPos = this.Root.Content.length; // RangeEndPos = 1;    to    RangeEndPos = this.Content.length;
694

695 696 697
        // Обновляем метрику строки
        if ( PRS.LineAscent < this.Ascent )
            PRS.LineAscent = this.Ascent;
698

699 700 701
        if ( PRS.LineDescent < this.Descent )
            PRS.LineDescent = this.Descent;
    }
702 703 704 705 706 707
    else
    {
        PRS.LineTextAscent  = OldLineTextAscent ;
        PRS.LineTextAscent2 = OldLineTextAscent2;
        PRS.LineTextDescent = OldLineTextDescent;
    }
708

709
    this.protected_FillRange(CurLine, CurRange, RangeStartPos, RangeEndPos);
710

711 712
    //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
};
Anna.Pavlova's avatar
Anna.Pavlova committed
713

714 715 716 717 718
ParaMath.prototype.Recalculate_Set_RangeEndPos = function(PRS, PRP, Depth)
{
    var CurLine  = PRS.Line - this.StartLine;
    var CurRange = ( 0 === CurLine ? PRS.Range - this.StartRange : PRS.Range );
    var CurPos   = PRP.Get(Depth);
Anna.Pavlova's avatar
Anna.Pavlova committed
719

720 721
    this.protected_FillRangeEndPos(CurLine, CurRange, CurPos);
};
Anna.Pavlova's avatar
Anna.Pavlova committed
722

723 724 725 726
ParaMath.prototype.Recalculate_Range_Width = function(PRSC, _CurLine, _CurRange)
{
    var CurLine = _CurLine - this.StartLine;
    var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
Anna.Pavlova's avatar
Anna.Pavlova committed
727

728 729 730 731 732
    var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
    var EndPos   = this.protected_GetRangeEndPos(CurLine, CurRange);

    if ( EndPos >= 1 )
    {
733
        PRSC.Letters++;
Anna.Pavlova's avatar
Anna.Pavlova committed
734

735
        if ( true !== PRSC.Word )
Anna.Pavlova's avatar
Anna.Pavlova committed
736
        {
737
            PRSC.Word = true;
738
            PRSC.Words++;
739
        }
Anna.Pavlova's avatar
Anna.Pavlova committed
740

741 742
        PRSC.Range.W += this.Width;
        PRSC.Range.W += PRSC.SpaceLen;
Anna.Pavlova's avatar
Anna.Pavlova committed
743

744
        PRSC.SpaceLen = 0;
Anna.Pavlova's avatar
Anna.Pavlova committed
745

746
        // Пробелы перед первым словом в строке не считаем
747 748
        if (PRSC.Words > 1)
            PRSC.Spaces += PRSC.SpacesCount;
Anna.Pavlova's avatar
Anna.Pavlova committed
749
        else
750
            PRSC.SpacesSkip += PRSC.SpacesCount;
Anna.Pavlova's avatar
Anna.Pavlova committed
751

752 753 754
        PRSC.SpacesCount = 0;
    }
};
Anna.Pavlova's avatar
Anna.Pavlova committed
755

756 757 758 759
ParaMath.prototype.Recalculate_Range_Spaces = function(PRSA, _CurLine, _CurRange, _CurPage)
{
    var CurLine = _CurLine - this.StartLine;
    var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
760

761 762
    var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
    var EndPos   = this.protected_GetRangeEndPos(CurLine, CurRange);
763

764
    if ( EndPos >= 1 )
765
    {
766
        if ( 0 !== PRSA.LettersSkip )
767
        {
768 769 770 771 772
            this.WidthVisible = this.Width;
            PRSA.LettersSkip--;
        }
        else
            this.WidthVisible = this.Width + PRSA.JustifyWord;
773

774 775 776 777
        // Позиция в документе для формулы
        //this.Math.absPos = {x: PRSA.X, y: PRSA.Y - this.Root.size.ascent};
        this.X     = PRSA.X;
        this.Y     = PRSA.Y - this.Root.size.ascent;
778

779 780 781 782
        PRSA.X    += this.WidthVisible;
        PRSA.LastW = this.WidthVisible;
    }
};
783

784 785 786
ParaMath.prototype.Recalculate_PageEndInfo = function(PRSI, _CurLine, _CurRange)
{
};
787

788 789 790 791
ParaMath.prototype.Save_RecalculateObject = function(Copy)
{
    var RecalcObj = new CRunRecalculateObject(this.StartLine, this.StartRange);
    RecalcObj.Save_Lines( this, Copy );
792

793
    // TODO: Сделать сохранение пересчета у формулы
794

795 796
    return RecalcObj;
};
797

798 799 800 801
ParaMath.prototype.Load_RecalculateObject = function(RecalcObj)
{
    RecalcObj.Load_Lines(this);
};
802

803 804 805 806
ParaMath.prototype.Prepare_RecalculateObject = function()
{
    this.protected_ClearLines();
};
807

808 809 810 811
ParaMath.prototype.Is_EmptyRange = function(_CurLine, _CurRange)
{
    var CurLine = _CurLine - this.StartLine;
    var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
812

813 814
    var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
    var EndPos   = this.protected_GetRangeEndPos(CurLine, CurRange);
815

816 817
    if ( EndPos >= 1 )
        return false;
818

819 820
    return true;
};
821

822 823 824
ParaMath.prototype.Check_Range_OnlyMath = function(Checker, CurRange, CurLine)
{
    if (null !== Checker.Math)
825
    {
826 827 828 829 830 831
        Checker.Math   = null;
        Checker.Result = false;
    }
    else
        Checker.Math = this;
};
832

833 834 835 836 837
ParaMath.prototype.Check_MathPara = function(Checker)
{
    Checker.Found  = true;
    Checker.Result = false;
};
838

839 840 841 842
ParaMath.prototype.Check_PageBreak = function()
{
    return false;
};
843

844 845
ParaMath.prototype.Check_BreakPageEnd = function(PBChecker)
{
846
    return true;
847
};
848

849 850 851
ParaMath.prototype.Get_ParaPosByContentPos = function(ContentPos, Depth)
{
    var Pos = ContentPos.Get(Depth);
852

853 854
    var CurLine  = 0;
    var CurRange = 0;
855

856 857
    var LinesCount = this.protected_GetLinesCount();
    for ( ; CurLine < LinesCount; CurLine++ )
858
    {
859 860 861 862 863
        var RangesCount = this.protected_GetRangesCount(CurLine);
        for ( CurRange = 0; CurRange < RangesCount; CurRange++ )
        {
            var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
            var EndPos   = this.protected_GetRangeEndPos(CurLine, CurRange);
864

865 866 867 868
            if (Pos < EndPos && Pos >= StartPos)
                return new CParaPos((CurLine === 0 ? CurRange + this.StartRange : CurRange), CurLine + this.StartLine, 0, 0);
        }
    }
869

870 871
    return new CParaPos((LinesCount === 1 ? this.protected_GetRangesCount(0) - 1 + this.StartRange : this.protected_GetRangesCount(0) - 1), LinesCount - 1 + this.StartLine, 0, 0);
};
872

873 874 875 876
ParaMath.prototype.Recalculate_CurPos = function(_X, Y, CurrentRun, _CurRange, _CurLine, _CurPage, UpdateCurPos, UpdateTarget, ReturnTarget)
{
    var CurLine  = _CurLine - this.StartLine;
    var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
877

878 879
    var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
    var EndPos   = this.protected_GetRangeEndPos(CurLine, CurRange);
880

881
    var result = {X: _X + this.Root.size.width};
882 883


884
    if ( EndPos >= 1 && CurrentRun == true)
885
    {
886 887
        result = this.Root.Recalculate_CurPos(_X, Y, CurrentRun, _CurRange, _CurLine, _CurPage, UpdateCurPos, UpdateTarget, ReturnTarget);
    }
888 889


890 891
    return result;
};
892

893 894 895 896
ParaMath.prototype.Refresh_RecalcData = function(Data)
{
    this.Paragraph.Refresh_RecalcData2(0);
};
897

898 899 900 901
ParaMath.prototype.Refresh_RecalcData2 = function(Data)
{
    this.Paragraph.Refresh_RecalcData2(0);
};
902

903 904
ParaMath.prototype.Recalculate_MinMaxContentWidth = function(MinMax)
{
905 906 907 908 909 910 911 912 913 914 915 916
    if (true === this.NeedResize)
    {
        var RPI = new CRPI();
        RPI.bInline       = this.bInline;
        RPI.bChangeInline = this.bChangeInline;
        RPI.PRS           = this.Paragraph.m_oPRSW;

        this.Root.PreRecalc(null, this,  new CMathArgSize(), RPI);
        this.Root.Resize(g_oTextMeasurer, RPI);

        this.Width        = this.Root.size.width;
    }
917

918
    if ( false === MinMax.bWord )
919
    {
920 921 922 923
        MinMax.bWord    = true;
        MinMax.nWordLen = this.Width;
    }
    else
Ilya.Kirillov's avatar
 
Ilya.Kirillov committed
924
    {
925 926
        MinMax.nWordLen += this.Width;
    }
Ilya.Kirillov's avatar
 
Ilya.Kirillov committed
927

928
    if ( MinMax.nSpaceLen > 0 )
929
    {
930 931 932
        MinMax.nCurMaxWidth += MinMax.nSpaceLen;
        MinMax.nSpaceLen     = 0;
    }
933

934 935
    MinMax.nCurMaxWidth += this.Width;
};
936

937 938 939 940
ParaMath.prototype.Get_Range_VisibleWidth = function(RangeW, _CurLine, _CurRange)
{
    var CurLine = _CurLine - this.StartLine;
    var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
941

942 943
    var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
    var EndPos   = this.protected_GetRangeEndPos(CurLine, CurRange);
944

945
    if ( EndPos >= 1 )
946
    {
947 948 949
        RangeW.W += this.Width;
    }
};
950

951 952 953 954
ParaMath.prototype.Shift_Range = function(Dx, Dy, _CurLine, _CurRange)
{
    var CurLine = _CurLine - this.StartLine;
    var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
955

956 957
    var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
    var EndPos   = this.protected_GetRangeEndPos(CurLine, CurRange);
958

959 960
    if ( EndPos >= 1 )
    {
961 962
        this.X += Dx;
        this.Y += Dy;
963 964
    }
};
965
//-----------------------------------------------------------------------------------
966 967
// Функция для работы с формулой
// в тч с  дефолтными текстовыми настройками и argSize
968
//-----------------------------------------------------------------------------------
969
ParaMath.prototype.Set_Inline = function(value)
970
{
971 972 973 974 975 976
    if(value !== this.bInline)
    {
        this.bChangeInline = true;
        this.NeedResize   = true;
    }

977 978
    this.bInline = value;
};
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 1004 1005
ParaMath.prototype.Get_Inline = function()
{
    return this.bInline;
};
ParaMath.prototype.Get_Align = function()
{
    if (undefined !== this.Jc)
        return this.Jc;

    return align_Center;
};
ParaMath.prototype.Set_Align = function(Align)
{
    if (align_Center !== Align && align_Left !== Align && align_Right !== Align)
        Align = align_Center;

    if (this.Jc !== Align)
    {
        History.Add(this, new CChangesMathParaJc(Align, this.Jc));
        this.raw_SetAlign(Align);
    }
};
ParaMath.prototype.raw_SetAlign = function(Align)
{
    this.Jc = Align;
    this.SetNeedResize();
};
1006 1007 1008
ParaMath.prototype.SetNeedResize = function()
{
    this.NeedResize = true;
1009 1010 1011 1012 1013
};
ParaMath.prototype.NeedCompiledCtrPr = function()
{
    this.Root.NeedCompiledCtrPr();
};
Oleg.Korshul's avatar
Oleg.Korshul committed
1014
ParaMath.prototype.MathToImageConverter = function(bCopy, _canvasInput, _widthPx, _heightPx, raster_koef)
1015
{
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
    var bTurnOnId = false, bTurnOnHistory = false;
    if (false === g_oTableId.m_bTurnOff)
    {
        g_oTableId.m_bTurnOff = true;
        bTurnOnId = true;
    }

    if (true === History.Is_On())
    {
        bTurnOnHistory = true;
        History.TurnOff();
    }
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 1069

    var oldDefTabStop = Default_Tab_Stop;
    Default_Tab_Stop = 1;

    var hdr = new CHeaderFooter(editor.WordControl.m_oLogicDocument.HdrFtr, editor.WordControl.m_oLogicDocument, editor.WordControl.m_oDrawingDocument, hdrftr_Header);
    var _dc = hdr.Content;

    var par = new Paragraph(editor.WordControl.m_oDrawingDocument, _dc, 0, 0, 0, 0, false);

    if (bCopy)
        par.Internal_Content_Add(0, this.Copy(false), false);
    else
        par.Internal_Content_Add(0, this, false);

    _dc.Internal_Content_Add(0, par, false);

    par.Set_Align(align_Left);
    par.Set_Tabs(new CParaTabs());

    var _ind = new CParaInd();
    _ind.FirstLine = 0;
    _ind.Left = 0;
    _ind.Right = 0;
    par.Set_Ind(_ind, false);

    var _sp = new CParaSpacing();
    _sp.Line              = 1;
    _sp.LineRule          = linerule_Auto;
    _sp.Before            = 0;
    _sp.BeforeAutoSpacing = false;
    _sp.After             = 0;
    _sp.AfterAutoSpacing  = false;
    par.Set_Spacing(_sp, false);

    _dc.Reset(0, 0, 10000, 10000);
    _dc.Recalculate_Page(0, true);

    _dc.Reset(0, 0, par.Lines[0].Ranges[0].W + 0.001, 10000);
    _dc.Recalculate_Page(0, true);

    Default_Tab_Stop = oldDefTabStop;

1070 1071 1072 1073
    if (true === bTurnOnId)
        g_oTableId.m_bTurnOff = false;

    if (true === bTurnOnHistory)
Oleg.Korshul's avatar
Oleg.Korshul committed
1074
        History.TurnOn();
1075

1076
    window.IsShapeToImageConverter = true;
1077

1078 1079 1080 1081 1082
    var dKoef = g_dKoef_mm_to_pix;
    var w_mm = this.Width;
    var h_mm = this.Height;
    var w_px = (w_mm * dKoef) >> 0;
    var h_px = (h_mm * dKoef) >> 0;
1083

Oleg.Korshul's avatar
Oleg.Korshul committed
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
    if (undefined !== raster_koef)
    {
        w_px *= raster_koef;
        h_px *= raster_koef;

        if (undefined !== _widthPx)
            _widthPx *= raster_koef;
        if (undefined !== _heightPx)
            _heightPx *= raster_koef;
    }

Oleg.Korshul's avatar
Oleg.Korshul committed
1095 1096 1097 1098
    var _canvas = (_canvasInput === undefined) ? document.createElement('canvas') : _canvasInput;

    _canvas.width   = (undefined == _widthPx) ? w_px : _widthPx;
    _canvas.height  = (undefined == _heightPx) ? h_px : _heightPx;
1099

1100
    var _ctx = _canvas.getContext('2d');
1101

1102 1103 1104
    var g = new CGraphics();
    g.init(_ctx, w_px, h_px, w_mm, h_mm);
    g.m_oFontManager = g_fontManager;
1105

1106 1107
    g.m_oCoordTransform.tx = 0;
    g.m_oCoordTransform.ty = 0;
Oleg.Korshul's avatar
Oleg.Korshul committed
1108 1109 1110 1111 1112 1113 1114

    if (_widthPx !== undefined && _heightPx !== undefined)
    {
        g.m_oCoordTransform.tx = (_widthPx - w_px) / 2;
        g.m_oCoordTransform.ty = (_heightPx - h_px) / 2;
    }

1115
    g.transform(1,0,0,1,0,0);
1116

1117
    this.Root.draw(0, 0, g);
1118

1119
    window.IsShapeToImageConverter = false;
1120

Oleg.Korshul's avatar
Oleg.Korshul committed
1121
    if (undefined === _canvasInput)
1122
    {
Oleg.Korshul's avatar
Oleg.Korshul committed
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
        var _ret = { ImageNative: _canvas, ImageUrl: "" };
        try
        {
            _ret.ImageUrl = _canvas.toDataURL("image/png");
        }
        catch (err)
        {
            _ret.ImageUrl = "";
        }
        return _ret;
1133
    }
Oleg.Korshul's avatar
Oleg.Korshul committed
1134
    return null;
1135
};
1136

1137
ParaMath.prototype.ApplyArgSize = function(FontSize, argSize)
1138
{
1139
    var ResultFontSize = FontSize;
1140 1141
    if(argSize == -1)
    {
1142
        ResultFontSize *= g_dMathArgSizeKoeff_1;
1143 1144 1145
    }
    else if(argSize == -2)
    {
1146
        ResultFontSize *= g_dMathArgSizeKoeff_2;
1147
    }
1148

1149
    return ResultFontSize;
1150
};
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160

ParaMath.prototype.GetFirstRPrp = function()
{
    return this.Root.getFirstRPrp(this);
};

ParaMath.prototype.GetShiftCenter = function(oMeasure, font)
{
    oMeasure.SetFont(font);
    var metrics = oMeasure.Measure2Code(0x2217); // "+"
1161

1162 1163
    return 0.6*metrics.Height;
};
1164

1165 1166 1167
ParaMath.prototype.SetMathProperties = function(props)
{
    //*****  FOR FORMULA  *****//
1168

1169
    // В документации везде, где нет примера использования свояства, означает, что Word не поддерживает это свойство !
1170

1171 1172
    if(props.naryLim == NARY_UndOvr || props.naryLim  == NARY_SubSup)
        this.MathPr.naryLim = props.naryLim;
1173

1174 1175
    if(props.intLim == NARY_UndOvr || props.intLim  == NARY_SubSup)
        this.MathPr.intLim = props.intLim;
1176

1177 1178
    if(props.brkBin == BREAK_BEFORE || props.brkBin == BREAK_AFTER || props.brkBin == BREAK_REPEAT)
        this.MathPr.brkBin = props.brkBin;
1179

1180 1181 1182 1183
    // for minus operator
    // when brkBin is set to repeat
    if(props.brkSubBin == BREAK_MIN_MIN || props.brkSubBin == BREAK_PLUS_MIN || props.brkSubBin == BREAK_MIN_PLUS)
        this.MathPr.brkSubBin = props.brkSubBin;
1184

1185 1186 1187
    // в случае если smallFrac = true,
    if(props.smallFrac == true || props.smallFrac == false)
        this.MathPr.smallFrac = props.smallFrac;
1188

1189 1190
    if(props.wrapIndent + 0 == props.wrapIndent && isNaN(props.wrapIndent)) // проверка на число
        this.MathPr.wrapIndent = props.wrapIndent/1440;
1191

1192 1193 1194 1195 1196 1197
    //********  check for element 0x1FFD - 0xA721  *******//
    // This element specifies the right justification of the wrapped line of an instance of mathematical text
    // Instance : Arrows 0x2190-0x21B3, 0x21B6, 0x21B7, 0x21BA-0x21E9, 0x21F4-0x21FF,
    // 0x3D, 0x2234 - 0x2237, 0x2239, 0x223B - 0x228B, 0x228F - 0x2292, 0x22A2 - 0x22B9,
    // 0x22C8-0x22CD, 0x22D0, 0x22D1, 0x22D5 - 0x22EE,0x22F0-0x22FF, 0x27F0 - 0x297F (arrows and fishes), 0x29CE - 0x29D5
    // 0x2A66 - 0x2AF0 (equals), 0x2AF2-0x2AF3, 0x2AF7 - 0x2AFA
1198 1199


1200 1201
    if(props.wrapRight == true || props.wrapRight == false)
        this.MathPr.wrapRight = props.wrapRight;
1202 1203


1204
    //*****  FOR DOCUMENT  *****//
1205

1206 1207
    // defaultJc
    // выравнивание формулы в документе
1208

1209
    this.MathPr.defJc = props.defJc;
1210

1211 1212
    // dispDef
    // свойство: применять/ не применять paragraph settings (в тч defaultJc)
1213

1214
    this.MathPr.dispDef = props.dispDef;
1215

1216 1217 1218
    // added to paragraph settings for margins
    // rMargin
    // lMargin
1219

1220 1221
    this.MathPr.lMargin = props.lMargin;
    this.MathPr.rMargin = props.rMargin;
1222

1223
    //*****  НЕПОДДЕРЖИВАЕМЫЕ Вордом свойства  *****//
1224

1225 1226
    // mathFont: в качестве font поддерживается только Cambria Math
    // остальные шрифты  возможно будут поддержаны MS в будущем
1227

1228
    this.MathPr.mathFont = props.mathFont;
1229

1230 1231 1232
    // Default font for math zones
    // Gives a drop-down list of math fonts that can be used as the default math font to be used in the document.
    // Currently only Cambria Math has thorough math support, but others such as the STIX fonts are coming soon.
1233

1234
    // http://blogs.msdn.com/b/murrays/archive/2008/10/27/default-document-math-properties.aspx
1235 1236


1237
    //*****  FOR FORMULA  *****//
1238

1239 1240 1241
    // http://msdn.microsoft.com/en-us/library/ff529906(v=office.12).aspx
    // Word ignores the interSp attribute and fails to write it back out.
    this.MathPr.interSp = props.interSp;
1242

1243 1244 1245
    // http://msdn.microsoft.com/en-us/library/ff529301(v=office.12).aspx
    // Word does not implement this feature and does not write the intraSp element.
    this.MathPr.intraSp = intraSp;
1246

1247
    //*****  FOR DOCUMENT  *****//
1248

1249 1250 1251 1252
    // http://msdn.microsoft.com/en-us/library/ff533406(v=office.12).aspx
    // Word ignores and discards postSp
    this.MathPr.postSp = props.postSp;
    this.MathPr.preSp = props.preSp;
1253

1254 1255
    // RichEdit Hot Keys
    // http://blogs.msdn.com/b/murrays/archive/2013/10/30/richedit-hot-keys.aspx
1256

1257 1258 1259 1260 1261 1262
};

ParaMath.prototype.GetMathPr = function()
{
    return this.MathPr;
};
1263

1264 1265
ParaMath.prototype.Get_Default_TPrp = function()
{
1266
    return this.DefaultTextPr;
1267
};
1268
//-----------------------------------------------------------------------------------
1269 1270
// Функции отрисовки
//-----------------------------------------------------------------------------------
1271 1272 1273 1274
ParaMath.prototype.Draw_HighLights = function(PDSH)
{
    var CurLine  = PDSH.Line - this.StartLine;
    var CurRange = ( 0 === CurLine ? PDSH.Range - this.StartRange : PDSH.Range );
1275

1276 1277
    var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
    var EndPos   = this.protected_GetRangeEndPos(CurLine, CurRange);
1278

1279 1280
    var X = PDSH.X;

1281
    if ( EndPos >= 1 )
1282
    {
1283
      this.Root.Draw_HighLights(PDSH, false);
1284 1285 1286 1287 1288 1289
    }
};
ParaMath.prototype.Draw_Elements = function(PDSE)
{
    var CurLine  = PDSE.Line - this.StartLine;
    var CurRange = ( 0 === CurLine ? PDSE.Range - this.StartRange : PDSE.Range );
1290

1291 1292
    var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
    var EndPos   = this.protected_GetRangeEndPos(CurLine, CurRange);
1293

1294 1295
    /*PDSE.Graphics.p_color(255,0,0, 255);
     PDSE.Graphics.drawHorLine(0, PDSE.Y - this.Ascent, PDSE.X - 30, PDSE.X + this.Width + 30 , 1);*/
1296

1297 1298 1299 1300 1301 1302
    if ( EndPos >= 1 )
    {
        //this.Math.Draw( PDSE.X, PDSE.Y, PDSE.Graphics );
        // CMathComposition     =>   this.Root.draw(this.absPos.x, this.absPos.y , pGraphics);
        // this.absPos.x ~> this.X
        // this.absPos.y ~> this.Y
1303

1304
        this.Root.draw( PDSE.X, PDSE.Y - this.Ascent, PDSE.Graphics);
1305

1306
        PDSE.X += this.Width;
1307

1308

1309
    }
1310

1311 1312 1313 1314 1315 1316 1317 1318
    /*PDSE.Graphics.p_color(255,0,0, 255);
     PDSE.Graphics.drawHorLine(0, PDSE.Y - this.Ascent + this.Height, PDSE.X - 30, PDSE.X + this.Width + 30 , 1);*/
};

ParaMath.prototype.Draw_Lines = function(PDSL)
{
    var CurLine  = PDSL.Line - this.StartLine;
    var CurRange = ( 0 === CurLine ? PDSL.Range - this.StartRange : PDSL.Range );
1319

1320 1321
    var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
    var EndPos   = this.protected_GetRangeEndPos(CurLine, CurRange);
1322

1323 1324 1325
    if ( EndPos >= 1 )
    {
        PDSL.X += this.Width;
1326

1327 1328
    }
};
1329

1330 1331 1332
//-----------------------------------------------------------------------------------
// Функции для работы с курсором
//-----------------------------------------------------------------------------------
1333 1334 1335 1336
ParaMath.prototype.Is_CursorPlaceable = function()
{
    return true;
};
1337

1338 1339 1340
ParaMath.prototype.Cursor_Is_Start = function()
{
    // TODO: ParaMath.Cursor_Is_Start
1341

1342 1343
    return this.Root.Cursor_Is_Start();
};
1344

1345 1346 1347 1348
ParaMath.prototype.Cursor_Is_NeededCorrectPos = function()
{
    return false;
};
1349

1350 1351 1352
ParaMath.prototype.Cursor_Is_End = function()
{
    // TODO: ParaMath.Cursor_Is_End
1353

1354 1355
    return this.Root.Cursor_Is_End();
};
1356

1357 1358 1359
ParaMath.prototype.Cursor_MoveToStartPos = function()
{
    // TODO: ParaMath.Cursor_MoveToStartPos
1360

1361 1362
    this.Root.Cursor_MoveToStartPos();
};
1363

1364 1365 1366
ParaMath.prototype.Cursor_MoveToEndPos = function(SelectFromEnd)
{
    // TODO: ParaMath.Cursor_MoveToEndPos
1367

1368 1369
    this.Root.Cursor_MoveToEndPos(SelectFromEnd);
};
1370

1371 1372 1373
ParaMath.prototype.Get_ParaContentPosByXY = function(SearchPos, Depth, _CurLine, _CurRange, StepEnd, Flag) // получить логическую позицию по XY
{
    var Result = false;
1374

1375 1376
    var CurLine  = _CurLine - this.StartLine;
    var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange ); // если находимся в нулевой строке (для текущей позиции), то CurRange мб ненулевой
1377

1378
    var EndPos   = this.protected_GetRangeEndPos(CurLine, CurRange);
1379

1380
    // Проверяем, попали ли мы в формулу
1381

1382 1383 1384 1385
    if ( EndPos >= 1 )
    {
        var Dx = this.Root.size.width;
        var D = SearchPos.X - SearchPos.CurX;
1386

1387
        var CurX = SearchPos.CurX;
1388

1389 1390
        Result = this.Root.Get_ParaContentPosByXY(SearchPos, Depth, _CurLine, _CurRange, StepEnd);

1391 1392
        if ( D >= - 0.001 && D <= Dx + 0.001 )
        {
1393 1394 1395
            SearchPos.InText = true;
            SearchPos.DiffX  = 0.001;

1396
            SearchPos.InTextPos.Copy_FromDepth(SearchPos.Pos, Depth);
1397 1398
        }

1399 1400
        SearchPos.CurX = CurX + Dx;
    }
1401

1402 1403
    return Result;
};
1404

1405 1406 1407 1408
ParaMath.prototype.Get_ParaContentPos = function(bSelection, bStart, ContentPos) // получить текущую логическую позицию
{
    this.Root.Get_ParaContentPos(bSelection, bStart, ContentPos);
};
1409

1410 1411 1412 1413
ParaMath.prototype.Set_ParaContentPos = function(ContentPos, Depth) // выставить логическую позицию в контенте
{
    this.Root.Set_ParaContentPos(ContentPos, Depth);
};
1414

1415 1416 1417 1418
ParaMath.prototype.Get_PosByElement = function(Class, ContentPos, Depth, UseRange, Range, Line)
{
    if ( this === Class )
        return true;
1419

1420
    // TODO: ParaMath.Get_PosByElement
1421 1422 1423 1424 1425 1426 1427

    return false;
};

ParaMath.prototype.Get_ElementByPos = function(ContentPos, Depth)
{
    return this.Root.Get_ElementByPos(ContentPos, Depth);
1428
};
1429

1430 1431 1432 1433
ParaMath.prototype.Get_PosByDrawing = function(Id, ContentPos, Depth)
{
    return false;
};
1434

1435 1436 1437 1438
ParaMath.prototype.Get_RunElementByPos = function(ContentPos, Depth)
{
    return null;
};
1439

1440 1441 1442 1443
ParaMath.prototype.Get_LastRunInRange = function(_CurLine, _CurRange)
{
    return null;
};
Anna.Pavlova's avatar
 
Anna.Pavlova committed
1444

1445 1446 1447 1448
ParaMath.prototype.Get_LeftPos = function(SearchPos, ContentPos, Depth, UseContentPos)
{
    return this.Root.Get_LeftPos(SearchPos, ContentPos, Depth, UseContentPos, false);
};
1449

1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
ParaMath.prototype.Get_RightPos = function(SearchPos, ContentPos, Depth, UseContentPos, StepEnd)
{
    return this.Root.Get_RightPos(SearchPos, ContentPos, Depth, UseContentPos, StepEnd, false);
};

ParaMath.prototype.Get_WordStartPos = function(SearchPos, ContentPos, Depth, UseContentPos)
{
    this.Root.Get_WordStartPos(SearchPos, ContentPos, Depth, UseContentPos, false);
};

ParaMath.prototype.Get_WordEndPos = function(SearchPos, ContentPos, Depth, UseContentPos, StepEnd)
{
    this.Root.Get_WordEndPos(SearchPos, ContentPos, Depth, UseContentPos, StepEnd, false);
};
1464

1465 1466
ParaMath.prototype.Get_EndRangePos = function(_CurLine, _CurRange, SearchPos, Depth)
{
1467 1468
    var CurLine = _CurLine - this.StartLine;
    var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
1469

1470
    var EndPos   = this.protected_GetRangeEndPos(CurLine, CurRange);
1471

1472 1473 1474 1475 1476
    if (EndPos >= 1)
    {
        // TODO: ParaMath.Get_EndRangePos Сделать для случая, когда формула будет занимать несколько строк
        return this.Root.Get_EndPos(false, SearchPos.Pos, Depth);
    }
1477

1478
    return false;
1479
};
1480

1481 1482
ParaMath.prototype.Get_StartRangePos = function(_CurLine, _CurRange, SearchPos, Depth)
{
1483 1484
    var CurLine = _CurLine - this.StartLine;
    var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
1485

1486
    var EndPos   = this.protected_GetRangeEndPos(CurLine, CurRange);
1487

1488 1489 1490 1491 1492
    if (EndPos >= 1)
    {
        // TODO: ParaMath.Get_StartRangePos Сделать для случая, когда формула будет занимать несколько строк
        return this.Root.Get_StartPos(SearchPos.Pos, Depth);
    }
1493

1494
    return false;
1495
};
1496

1497 1498
ParaMath.prototype.Get_StartRangePos2 = function(_CurLine, _CurRange, ContentPos, Depth)
{
1499 1500
    var CurLine = _CurLine - this.StartLine;
    var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
1501

1502
    var EndPos   = this.protected_GetRangeEndPos(CurLine, CurRange);
1503

1504 1505 1506 1507 1508
    if (EndPos >= 1)
    {
        // TODO: ParaMath.Get_StartRangePos2 Сделать для случая, когда формула будет занимать несколько строк
        return this.Root.Get_StartPos(ContentPos, Depth);
    }
1509

1510
    return false;};
1511

1512 1513 1514 1515 1516 1517 1518 1519 1520
ParaMath.prototype.Get_StartPos = function(ContentPos, Depth)
{
    this.Root.Get_StartPos(ContentPos, Depth);
};

ParaMath.prototype.Get_EndPos = function(BehindEnd, ContentPos, Depth)
{
    this.Root.Get_EndPos(BehindEnd, ContentPos, Depth);
};
1521 1522 1523
//-----------------------------------------------------------------------------------
// Функции для работы с селектом
//-----------------------------------------------------------------------------------
1524 1525 1526 1527 1528
ParaMath.prototype.Set_SelectionContentPos = function(StartContentPos, EndContentPos, Depth, StartFlag, EndFlag)
{
    this.Root.Set_SelectionContentPos(StartContentPos, EndContentPos, Depth, StartFlag, EndFlag);
    this.bSelectionUse = true;
};
1529

1530 1531 1532 1533
ParaMath.prototype.Selection_IsUse = function()
{
    return this.bSelectionUse;
};
1534

1535 1536 1537
ParaMath.prototype.Selection_Stop = function()
{
};
1538

1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
ParaMath.prototype.Selection_Remove = function()
{
    this.bSelectionUse = false;
    this.Root.Selection_Remove();
};

ParaMath.prototype.Select_All = function(Direction)
{
    this.bSelectionUse = true;
    this.Root.Select_All();
};
1550

1551 1552 1553 1554
ParaMath.prototype.Selection_DrawRange = function(_CurLine, _CurRange, SelectionDraw)
{
    var CurLine = _CurLine - this.StartLine;
    var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
1555

1556
    var EndPos   = this.protected_GetRangeEndPos(CurLine, CurRange);
1557

1558
    if (EndPos >= 1)
1559
    {
1560
        if (true === this.bSelectionUse)
1561
        {
1562 1563
            var oSelectedContent = this.GetSelectContent();
            oSelectedContent.Content.Selection_DrawRange(_CurLine, _CurRange, SelectionDraw);
1564 1565 1566 1567
        }
        else
        {
            if ( true === SelectionDraw.FindStart )
1568
            {
1569
                SelectionDraw.StartX += this.Width;
1570
            }
1571
        }
1572 1573
    }
};
1574

1575 1576 1577
ParaMath.prototype.Selection_IsEmpty = function(CheckEnd)
{
    // TODO: ParaMath.Selection_IsEmpty
1578

1579 1580
    return this.Root.Selection_IsEmpty();
};
1581

1582 1583 1584 1585 1586 1587 1588
ParaMath.prototype.Selection_IsPlaceholder = function()
{
    var bPlaceholder = false;
    var result = this.GetSelectContent(),
        SelectContent = result.Content;
    var start = result.Start,
        end = result.End;
1589

1590
    if(start == end)
1591
    {
1592 1593
        bPlaceholder = SelectContent.IsPlaceholder();
    }
1594

1595 1596 1597 1598 1599 1600 1601 1602
    return bPlaceholder;
};

ParaMath.prototype.Selection_CheckParaEnd = function()
{
    return false;
};

1603 1604 1605 1606 1607
ParaMath.prototype.Selection_CheckParaContentPos = function(ContentPos, Depth, bStart, bEnd)
{
    return this.Root.Selection_CheckParaContentPos(ContentPos, Depth, bStart, bEnd);
};

1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
ParaMath.prototype.Is_SelectedAll = function(Props)
{
    // TODO: ParaMath.Is_SelectedAll
    return this.Root.Is_SelectedAll(Props);
};

ParaMath.prototype.Selection_CorrectLeftPos = function(Direction)
{
    return false;
};
1618 1619 1620
//----------------------------------------------------------------------------------------------------------------------
// Функции совместного редактирования
//----------------------------------------------------------------------------------------------------------------------
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
ParaMath.prototype.Undo = function(Data)
{
    Data.Undo(this);
};

ParaMath.prototype.Redo = function(Data)
{
    Data.Redo(this);
};

1631 1632
ParaMath.prototype.Save_Changes = function(Data, Writer)
{
1633
    WriteChanges_ToBinary(Data, Writer);
1634
};
1635

1636 1637
ParaMath.prototype.Load_Changes = function(Reader)
{
1638
    ReadChanges_FromBinary(Reader, this);
1639
};
1640 1641 1642 1643

ParaMath.prototype.Write_ToBinary2 = function(Writer)
{
    Writer.WriteLong( historyitem_type_Math );
1644 1645 1646 1647 1648 1649 1650 1651

    // String : this.Id
    // Long   : this.Type
    // String : Root.Id

    Writer.WriteString2(this.Id);
    Writer.WriteLong(this.Type);
    Writer.WriteString2(this.Root.Id);
1652 1653 1654 1655
};

ParaMath.prototype.Read_FromBinary2 = function(Reader)
{
1656 1657 1658
    // String : this.Id
    // Long   : this.Type
    // String : Root.Id
1659

1660 1661 1662 1663
    this.Id   = Reader.GetString2();
    this.Type = Reader.GetLong();
    this.Root = g_oTableId.Get_ById(Reader.GetString2());
    this.Root.bRoot = true;
1664 1665 1666 1667 1668 1669
};

ParaMath.prototype.Get_ContentSelection = function()
{
    var oContent = this.GetSelectContent().Content;

1670
    if (oContent.bRoot)
1671 1672
        return null;

1673 1674 1675 1676
    var X = oContent.pos.x + this.X;
    var Y = oContent.pos.y + this.Y;

    return {X : X, Y : Y, W : oContent.size.width, H : oContent.size.height};
1677 1678
};

1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
/**
 * Проверяем находимся ли мы во внутреннем (не самом верхнем) контенте формулы.
 */
ParaMath.prototype.Is_InInnerContent = function()
{
    var oContent = this.GetSelectContent().Content;

    if (oContent.bRoot)
        return false;

    return true;
};

/**
 * Обработка нажатия Enter внутри формулы
 */
ParaMath.prototype.Handle_AddNewLine = function()
{
1697 1698 1699
    var ContentPos = new CParagraphContentPos();

    var CurrContent = this.GetSelectContent().Content;
1700 1701 1702 1703

    if (true === CurrContent.bRoot)
        return false;

1704 1705 1706 1707
    CurrContent.Get_ParaContentPos(this.bSelectionUse, true, ContentPos);

    var NeedRecalculate = false;

1708
    if(MATH_EQ_ARRAY === CurrContent.ParentElement.kind)
1709
    {
1710
        var NewContent = CurrContent.Parent.addRow();
1711 1712 1713 1714
        CurrContent.SplitContent(NewContent, ContentPos, 0);
        NewContent.Correct_Content(true);
        CurrContent.Correct_Content(true);

1715 1716
        NewContent.Cursor_MoveToStartPos();

1717 1718
        NeedRecalculate = true;
    }
1719
    else if(MATH_MATRIX !== CurrContent.ParentElement.kind)
1720
    {
1721
        var ctrPrp = CurrContent.Parent.CtrPrp.Copy();
1722 1723 1724
        var props = {row: 2, ctrPrp: ctrPrp};
        var EqArray = new CEqArray(props);

1725 1726
        var FirstContent  = EqArray.getElementMathContent(0);
        var SecondContent = EqArray.getElementMathContent(1);
1727 1728 1729 1730 1731 1732 1733 1734 1735

        CurrContent.SplitContent(SecondContent, ContentPos, 0);
        CurrContent.CopyTo(FirstContent, false);

        // остаим пустой Run в Content, чтобы не упала ф-ия Remove_FromContent
        // первый элемент всегда Run
        var Run = CurrContent.getElem(0);
        Run.Remove_FromContent(0, Run.Content.length, true);

1736
        CurrContent.Remove_FromContent(1, CurrContent.Content.length);
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
        CurrContent.Add_ToContent(1, EqArray);
        CurrContent.Correct_Content(true);

        var CurrentContent = new CParagraphContentPos();
        this.Get_ParaContentPos(false, false, CurrentContent);

        var RightContentPos = new CParagraphSearchPos();
        this.Get_RightPos(RightContentPos, CurrentContent, 0, true);
        this.Set_ParaContentPos(RightContentPos.Pos, 0);

1747 1748 1749
        EqArray.CurPos = 1;
        SecondContent.Cursor_MoveToStartPos();

1750 1751 1752
        NeedRecalculate = true;
    }

1753 1754
    if (true === NeedRecalculate)
        this.SetNeedResize();
1755 1756

    return NeedRecalculate;
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
};

/**
 * Разделение формулы на 2 части в заданной позиции. В текущем объекте остается левая часть формулы.
 * @param ContentPos Позиция
 * @param Depth
 * @returns Возвращается правая часть формулы.
 */
ParaMath.prototype.Split = function (ContentPos, Depth)
{
1767 1768
    var NewParaMath = new ParaMath();
    NewParaMath.Jc = this.Jc;
1769

1770 1771 1772
    this.Root.SplitContent(NewParaMath.Root, ContentPos, Depth);

    //var Pos = ContentPos.Get(Depth);
1773

1774
    /*if(this.Root.Content[Pos].Type == para_Math_Run)
1775
    {
1776

1777

1778
        var NewRun = this.Root.Content[Pos].Split(ContentPos, Depth+1);
1779 1780
        NewParaMath.Root.Add_ToContent(0, NewRun);

1781
        var len = this.Root.Content.length;
1782 1783 1784

        if(Pos < len - 1)
        {
1785
            NewParaMath.Root.Concat_ToContent( this.Root.Content.slice(Pos + 1) );
1786 1787 1788 1789 1790 1791
            this.Root.Remove_FromContent(Pos+1, len - Pos - 1);
        }

        this.SetNeedResize();
        NewParaMath.SetNeedResize();

1792
    }*/
1793 1794

    return NewParaMath;
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804
};

/**
 * Пытаемся выполнить автозамену в формуле.
 * @returns {boolean} Выполнилась ли автозамена.
 */
ParaMath.prototype.Make_AutoCorrect = function()
{
    return false;
};
1805

1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
/**
 * Получаем рект формулы
 * @constructor
 */
ParaMath.prototype.Get_Bounds = function()
{
    if (undefined === this.Paragraph || null === this.Paragraph)
        return {X : this.X, Y : this.Y, W : this.Width, H : this.Height, Page : 0};
    else
    {
        var LinesCount = this.protected_GetLinesCount();
        var CurLine = this.StartLine + LinesCount - 1;

        var CurPage = this.Paragraph.Get_PageByLine(CurLine);

        var Y = this.Paragraph.Pages[CurPage].Y      + this.Paragraph.Lines[CurLine].Top;
        var H = this.Paragraph.Lines[CurLine].Bottom - this.Paragraph.Lines[CurLine].Top;

        return {X : this.X, Y : Y, W : this.Width, H : H, Page : this.Paragraph.Get_StartPage_Absolute() + CurPage};
    }
};

1828 1829 1830 1831 1832 1833 1834

//----------------------------------------------------------------------------------------------------------------------
// Классы с изменениями
//----------------------------------------------------------------------------------------------------------------------
var historyitem_Math_AddItem                   =  1; // Добавляем элемент
var historyitem_Math_RemoveItem                =  2; // Удаляем элемент
var historyitem_Math_CtrPrpFSize               =  3; // CtrPrp
1835
var historyitem_Math_ParaJc                    =  4; // ParaMath.Jc
1836
var historyitem_Math_CtrPrpShd                 =  5;
1837
var historyitem_Math_AddItems_ToMathBase       =  6;
1838
var historyitem_Math_EqArrayPr                 =  7; // Изменение настроек у CEqArray
1839 1840 1841 1842 1843 1844 1845 1846

function ReadChanges_FromBinary(Reader, Class)
{
    var Type = Reader.GetLong();
    var Changes = null;

    switch(Type)
    {
1847
        case historyitem_Math_CtrPrpFSize         : Changes = new CChangesMathFontSize(); break;
1848
        case historyitem_Math_ParaJc              : Changes = new CChangesMathParaJc(); break;
1849 1850
        case historyitem_Math_CtrPrpShd           : Changes = new CChangesMathShd(); break;
        case historyitem_Math_AddItems_ToMathBase : Changes = new CChangesMathAddItems(); break;
1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883
    }

    if (null !== Changes)
        Changes.Load_Changes(Reader, Class);
}

function WriteChanges_ToBinary(Changes, Writer)
{
    Writer.WriteLong(Changes.Type);
    Changes.Save_Changes(Writer);
}

//----------------------------------------------------------------------------------------------------------------------
// Классы с изменениями
//----------------------------------------------------------------------------------------------------------------------
function CChangesMathFontSize(NewValue, OldValue)
{
    this.New = NewValue;
    this.Old = OldValue;
}

CChangesMathFontSize.prototype.Type = historyitem_Math_CtrPrpFSize;

CChangesMathFontSize.prototype.Undo = function(Class)
{
    Class.raw_SetFontSize(this.Old);
};
CChangesMathFontSize.prototype.Redo = function(Class)
{
    Class.raw_SetFontSize(this.New);
};
CChangesMathFontSize.prototype.Save_Changes = function(Writer)
{
1884
    // Bool : IsUndefined
1885
    // Long : New
1886 1887 1888 1889 1890 1891 1892
    if (undefined === this.New)
        Writer.WriteBool(true);
    else
    {
        Writer.WriteBool(false);
        Writer.WriteLong(this.New);
    }
1893 1894 1895
};
CChangesMathFontSize.prototype.Load_Changes = function(Reader, Class)
{
1896 1897 1898 1899 1900 1901 1902 1903
    // Bool : IsUndefined
    // Long : New

    if (true === Reader.GetBool())
        this.New = undefined;
    else
        this.New = Reader.GetLong();

1904
    this.Redo(Class);
1905 1906
};

1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
function CChangesMathShd(NewValue, OldValue)
{
    this.New = NewValue;
    this.Old = OldValue;
}
CChangesMathShd.prototype.Type = historyitem_Math_CtrPrpShd;
CChangesMathShd.prototype.Undo = function(Class)
{
    Class.raw_SetShd(this.Old);
};
CChangesMathShd.prototype.Redo = function(Class)
{
    Class.raw_SetShd(this.New);
};
CChangesMathShd.prototype.Save_Changes = function(Writer)
{
    // Long : New

    if ( undefined !== this.New )
    {
        Writer.WriteBool(false);
        this.New.Write_ToBinary(Writer);
    }
    else
        Writer.WriteBool(true);

    //Writer.WriteLong(this.New);
};
CChangesMathShd.prototype.Load_Changes = function(Reader, Class)
{
    /*this.New = Reader.GetLong();
    this.Redo(Class);*/

    if ( Reader.GetBool() == false)
    {
        this.New = new CDocumentShd();
        this.New.Read_FromBinary( Reader );
    }
    else
    {
        this.New = undefined;
    }

    this.Redo(Class);
};

1953 1954 1955 1956 1957 1958 1959 1960
function CChangesMathAddItems(Pos, Items)
{
    this.Pos   = Pos;
    this.Items = Items;
}
CChangesMathAddItems.prototype.Type = historyitem_Math_AddItems_ToMathBase;
CChangesMathAddItems.prototype.Undo = function(Class)
{
1961
    Class.raw_RemoveFromContent(this.Pos, this.Items.length);
1962 1963 1964
};
CChangesMathAddItems.prototype.Redo = function(Class)
{
1965
    Class.raw_AddToContent(this.Pos, this.Items, false);
1966 1967 1968
};
CChangesMathAddItems.prototype.Save_Changes = function(Writer)
{
1969 1970 1971 1972
    // Long : Count
    // Long : Pos
    // Array of String : Id

1973 1974
    var Count = this.Items.length;
    Writer.WriteLong(Count);
1975
    Writer.WriteLong(this.Pos);
1976 1977 1978 1979 1980 1981 1982 1983

    for(var Index = 0; Index < Count; Index++)
    {
        Writer.WriteString2(this.Items[Index].Get_Id());
    }
};
CChangesMathAddItems.prototype.Load_Changes = function(Reader, Class)
{
1984 1985 1986
    // Long : Count
    // Long : Pos
    // Array of String : Id
1987

1988 1989
    var Count = Reader.GetLong();
    this.Pos  = Reader.GetLong();
1990

1991
    this.Items = [];
1992 1993
    for(var Index = 0; Index < Count; Index++)
    {
1994
        var Element = g_oTableId.Get_ById(Reader.GetString2());
1995

1996
        if (null !== Element)
1997 1998 1999 2000 2001 2002
            this.Items.push(Element);
    }

    this.Redo(Class);
};

2003 2004 2005 2006 2007
function CChangesMathParaJc(NewValue, OldValue)
{
    this.New = NewValue;
    this.Old = OldValue;
}
2008
CChangesMathParaJc.prototype.Type = historyitem_Math_ParaJc;
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
CChangesMathParaJc.prototype.Undo = function(Class)
{
    Class.raw_SetAlign(this.Old);
};
CChangesMathParaJc.prototype.Redo = function(Class)
{
    Class.raw_SetAlign(this.New);
};
CChangesMathParaJc.prototype.Save_Changes = function(Writer)
{
    // Bool : undefined?
    // Long : value
    if (undefined === this.New)
        Writer.WriteBool(true);
    else
    {
        Writer.WriteBool(false);
        Writer.WriteLong(this.New);
    }
};
CChangesMathParaJc.prototype.Load_Changes = function(Reader, Class)
{
    if (true === Reader.GetBool())
        this.New = undefined;
    else
        this.New = Reader.GetLong();

    this.Redo(Class);
};
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077

function CChangesMathEqArrayPr(NewPr, OldPr)
{
    this.New = NewPr;
    this.Old = OldPr;
}

CChangesMathEqArrayPr.prototype.Type = historyitem_Math_EqArrayPr;
CChangesMathEqArrayPr.prototype.Undo = function(Class)
{
    Class.raw_SetPr(this.Old);
};
CChangesMathEqArrayPr.prototype.Redo = function(Class)
{
    Class.raw_SetPr(this.New);
};
CChangesMathEqArrayPr.prototype.Save_Changes = function(Writer)
{
    // Bool : undefined?
    // Long : value
    if (undefined === this.New)
        Writer.WriteBool(true);
    else
    {
        Writer.WriteBool(false);
        this.New.Write_ToBinary(Writer);
    }
};
CChangesMathEqArrayPr.prototype.Load_Changes = function(Reader, Class)
{
    if (true === Reader.GetBool())
        this.New = undefined;
    else
    {
        this.New = new CMathEqArrPr();
        this.New.Read_FromBinary(Reader);
    }

    this.Redo(Class);
};