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

3 4 5 6 7 8 9 10 11 12
function CAscSection()
{
    this.PageWidth = 0;
    this.PageHeight = 0;

    this.MarginLeft = 0;
    this.MarginRight = 0;
    this.MarginTop = 0;
    this.MarginBottom = 0;
}
13 14 15 16 17 18
CAscSection.prototype.get_PageWidth = function() { return this.PageWidth; };
CAscSection.prototype.get_PageHeight = function() { return this.PageHeight; };
CAscSection.prototype.get_MarginLeft = function() { return this.MarginLeft; };
CAscSection.prototype.get_MarginRight = function() { return this.MarginRight; };
CAscSection.prototype.get_MarginTop = function() { return this.MarginTop; };
CAscSection.prototype.get_MarginBottom = function() { return this.MarginBottom; };
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

function CImagePositionH(obj)
{
    if ( obj )
    {
        this.RelativeFrom = ( undefined === obj.RelativeFrom ) ? undefined : obj.RelativeFrom;
        this.UseAlign     = ( undefined === obj.UseAlign     ) ? undefined : obj.UseAlign;
        this.Align        = ( undefined === obj.Align        ) ? undefined : obj.Align;
        this.Value        = ( undefined === obj.Value        ) ? undefined : obj.Value;
    }
    else
    {
        this.RelativeFrom = undefined;
        this.UseAlign     = undefined;
        this.Align        = undefined;
        this.Value        = undefined;
    }
}

38 39 40 41 42 43 44 45
CImagePositionH.prototype.get_RelativeFrom = function()  { return this.RelativeFrom; };
CImagePositionH.prototype.put_RelativeFrom = function(v) { this.RelativeFrom = v; };
CImagePositionH.prototype.get_UseAlign = function()  { return this.UseAlign; };
CImagePositionH.prototype.put_UseAlign = function(v) { this.UseAlign = v; };
CImagePositionH.prototype.get_Align = function()  { return this.Align; };
CImagePositionH.prototype.put_Align = function(v) { this.Align = v; };
CImagePositionH.prototype.get_Value = function()  { return this.Value; };
CImagePositionH.prototype.put_Value = function(v) { this.Value = v; };
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

function CImagePositionV(obj)
{
    if ( obj )
    {
        this.RelativeFrom = ( undefined === obj.RelativeFrom ) ? undefined : obj.RelativeFrom;
        this.UseAlign     = ( undefined === obj.UseAlign     ) ? undefined : obj.UseAlign;
        this.Align        = ( undefined === obj.Align        ) ? undefined : obj.Align;
        this.Value        = ( undefined === obj.Value        ) ? undefined : obj.Value;
    }
    else
    {
        this.RelativeFrom = undefined;
        this.UseAlign     = undefined;
        this.Align        = undefined;
        this.Value        = undefined;
    }
}

65 66 67 68 69 70 71 72
CImagePositionV.prototype.get_RelativeFrom = function()  { return this.RelativeFrom; };
CImagePositionV.prototype.put_RelativeFrom = function(v) { this.RelativeFrom = v; };
CImagePositionV.prototype.get_UseAlign = function()  { return this.UseAlign; };
CImagePositionV.prototype.put_UseAlign = function(v) { this.UseAlign = v; };
CImagePositionV.prototype.get_Align = function()  { return this.Align; };
CImagePositionV.prototype.put_Align = function(v) { this.Align = v; };
CImagePositionV.prototype.get_Value = function()  { return this.Value; };
CImagePositionV.prototype.put_Value = function(v) { this.Value = v; };
73 74 75 76 77 78 79 80 81 82 83 84 85 86

function CPosition( obj )
{
	if (obj)
	{
		this.X = (undefined == obj.X) ? null : obj.X;
		this.Y = (undefined == obj.Y) ? null : obj.Y;
	}
	else
	{
		this.X = null;
		this.Y = null;
	}
}
87 88 89 90
CPosition.prototype.get_X = function() { return this.X; };
CPosition.prototype.put_X = function(v) { this.X = v; };
CPosition.prototype.get_Y = function() { return this.Y; };
CPosition.prototype.put_Y = function(v) { this.Y = v; };
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110






function CHeaderProp( obj )
{
	/*{
		Type : hdrftr_Footer (hdrftr_Header),
		Position : 12.5,
		DifferentFirst : true/false,
		DifferentEvenOdd : true/false,
	}*/
	if( obj )
	{
		this.Type = (undefined != obj.Type) ? obj.Type: null;
		this.Position = (undefined != obj.Position) ? obj.Position : null;
		this.DifferentFirst = (undefined != obj.DifferentFirst) ? obj.DifferentFirst : null;
		this.DifferentEvenOdd = (undefined != obj.DifferentEvenOdd) ? obj.DifferentEvenOdd : null;
Ilya.Kirillov's avatar
Ilya.Kirillov committed
111
        this.LinkToPrevious   = (undefined != obj.LinkToPrevious)   ? obj.LinkToPrevious   : null;
112 113 114 115 116 117 118 119
        this.Locked = (undefined != obj.Locked) ? obj.Locked : false;
	}
	else
	{
		this.Type = hdrftr_Footer;
		this.Position = 12.5;
		this.DifferentFirst = false;
		this.DifferentEvenOdd = false;
Ilya.Kirillov's avatar
Ilya.Kirillov committed
120
        this.LinkToPrevious   = null;
121 122 123 124
        this.Locked = false;
	}
}

125 126 127 128 129 130 131 132 133 134
CHeaderProp.prototype.get_Type = function(){ return this.Type; };
CHeaderProp.prototype.put_Type = function(v){ this.Type = v; };
CHeaderProp.prototype.get_Position = function(){ return this.Position; };
CHeaderProp.prototype.put_Position = function(v){ this.Position = v; };
CHeaderProp.prototype.get_DifferentFirst = function(){ return this.DifferentFirst; };
CHeaderProp.prototype.put_DifferentFirst = function(v){ this.DifferentFirst = v; };
CHeaderProp.prototype.get_DifferentEvenOdd = function(){ return this.DifferentEvenOdd; };
CHeaderProp.prototype.put_DifferentEvenOdd = function(v){ this.DifferentEvenOdd = v; };
CHeaderProp.prototype.get_LinkToPrevious = function() { return this.LinkToPrevious; };
CHeaderProp.prototype.get_Locked = function() { return this.Locked; };
135 136 137 138 139


// [!dirty hack for minimizer - don't delete this comment!] function CStylesPainter ()
// [!dirty hack for minimizer - don't delete this comment!] function CStyleImage ()
// [!dirty hack for minimizer - don't delete this comment!] function CFont ()
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
CStylesPainter.prototype.get_DefaultStylesImage = function() { return this.defaultStylesImage; };
CStylesPainter.prototype.get_DocStylesImage = function() { return this.docStylesImage; };
CStylesPainter.prototype.get_MergedStyles = function() { return this.mergedStyles; };
CStylesPainter.prototype.get_STYLE_THUMBNAIL_WIDTH = function() { return this.STYLE_THUMBNAIL_WIDTH; };
CStylesPainter.prototype.get_STYLE_THUMBNAIL_HEIGHT = function() { return this.STYLE_THUMBNAIL_HEIGHT; };
CStylesPainter.prototype.get_IsRetinaEnabled = function() { return this.IsRetinaEnabled; };

CStyleImage.prototype.get_ThumbnailOffset = function() { return this.ThumbnailOffset; };
CStyleImage.prototype.get_Type = function() { return this.Type; };
CStyleImage.prototype.get_Name = function() { return this.Name; };

CFont.prototype.asc_getFontId = function() { return this.id; };
CFont.prototype.asc_getFontName = function() { return this.name; };
CFont.prototype.asc_getFontThumbnail = function() { return this.thumbnail; };
CFont.prototype.asc_getFontType = function() { return this.type; };
155 156 157

var DocumentPageSize = new function() {
    this.oSizes = [{name:"US Letter", w_mm: 215.9, h_mm: 279.4, w_tw: 12240, h_tw: 15840},
Sergey.Konovalov's avatar
Sergey.Konovalov committed
158
        {name:"US Legal", w_mm: 215.9, h_mm: 355.6, w_tw: 12240, h_tw: 20160},
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
        {name:"A4", w_mm: 210, h_mm: 297, w_tw: 11907, h_tw: 16839},
        {name:"A5", w_mm: 148.1, h_mm: 209.9, w_tw: 8391, h_tw: 11907},
        {name:"B5", w_mm: 176, h_mm: 250.1, w_tw: 9979, h_tw: 14175},
        {name:"Envelope #10", w_mm: 104.8, h_mm: 241.3, w_tw: 5940, h_tw: 13680},
        {name:"Envelope DL", w_mm: 110.1, h_mm: 220.1, w_tw: 6237, h_tw: 12474},
        {name:"Tabloid", w_mm: 279.4, h_mm: 431.7, w_tw: 15842, h_tw: 24477},
        {name:"A3", w_mm: 297, h_mm: 420.1, w_tw: 16840, h_tw: 23820},
        {name:"Tabloid Oversize", w_mm: 304.8, h_mm: 457.1, w_tw: 17282, h_tw: 25918},
        {name:"ROC 16K", w_mm: 196.8, h_mm: 273, w_tw: 11164, h_tw: 15485},
        {name:"Envelope Coukei 3", w_mm: 119.9, h_mm: 234.9, w_tw: 6798, h_tw: 13319},
        {name:"Super B/A3", w_mm: 330.2, h_mm: 482.5, w_tw: 18722, h_tw: 27358}
    ];
    this.sizeEpsMM = 0.5;
    this.getSize = function(widthMm, heightMm)
    {
174
        for( var index in this.oSizes)
175 176 177 178 179 180 181 182 183
        {
            var item = this.oSizes[index];
            if(Math.abs(widthMm - item.w_mm) < this.sizeEpsMM && Math.abs(heightMm - item.h_mm) < this.sizeEpsMM)
                return item;
        }
        return {w_mm: widthMm, h_mm: heightMm};
    };
};

184 185 186
function CMailMergeSendData (obj){
	if(obj){
		if (typeof obj.from != 'undefined'){
187
			this["from"] = obj.from;
188 189
		}
		if (typeof obj.to != 'undefined'){
190
			this["to"] = obj.to;
191 192
		}
		if (typeof obj.subject != 'undefined'){
193
			this["subject"] = obj.subject;
194 195
		}
		if (typeof obj.mailFormat != 'undefined'){
196
			this["mailFormat"] = obj.mailFormat;
197 198
		}
		if (typeof obj.fileName != 'undefined'){
199
			this["fileName"] = obj.fileName;
200 201
		}
		if (typeof obj.message != 'undefined'){
202
			this["message"] = obj.message;
203 204
		}
		if (typeof obj.recordFrom != 'undefined'){
205
			this["recordFrom"] = obj.recordFrom;
206 207
		}
		if (typeof obj.recordTo != 'undefined'){
208
			this["recordTo"] = obj.recordTo;
209 210 211 212
		}
	}
	else
    {
213 214 215 216 217 218 219 220 221 222
		this["from"] = null;
		this["to"] = null;
		this["subject"] = null;
		this["mailFormat"] = null;
		this["fileName"] = null;
		this["message"] = null;
		this["recordFrom"] = null;
		this["recordTo"] = null;
		this["recordCount"] = null;
		this["userId"] = null;
223 224
	}
}
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
CMailMergeSendData.prototype.get_From = function(){return this["from"]};
CMailMergeSendData.prototype.put_From = function(v){this["from"] = v;};
CMailMergeSendData.prototype.get_To = function(){return this["to"]};
CMailMergeSendData.prototype.put_To = function(v){this["to"] = v;};
CMailMergeSendData.prototype.get_Subject = function(){return this["subject"]};
CMailMergeSendData.prototype.put_Subject = function(v){this["subject"] = v;};
CMailMergeSendData.prototype.get_MailFormat = function(){return this["mailFormat"]};
CMailMergeSendData.prototype.put_MailFormat = function(v){this["mailFormat"] = v;};
CMailMergeSendData.prototype.get_FileName = function(){return this["fileName"]};
CMailMergeSendData.prototype.put_FileName = function(v){this["fileName"] = v;};
CMailMergeSendData.prototype.get_Message = function(){return this["message"]};
CMailMergeSendData.prototype.put_Message = function(v){this["message"] = v;};
CMailMergeSendData.prototype.get_RecordFrom = function(){return this["recordFrom"]};
CMailMergeSendData.prototype.put_RecordFrom = function(v){this["recordFrom"] = v;};
CMailMergeSendData.prototype.get_RecordTo = function(){return this["recordTo"]};
CMailMergeSendData.prototype.put_RecordTo = function(v){this["recordTo"] = v;};
CMailMergeSendData.prototype.get_RecordCount = function(){return this["recordCount"]};
CMailMergeSendData.prototype.put_RecordCount = function(v){this["recordCount"] = v;};
CMailMergeSendData.prototype.get_UserId = function(){return this["userId"]};
CMailMergeSendData.prototype.put_UserId = function(v){this["userId"] = v;};
245

246 247 248 249 250 251
// пользоваться так:
// подрубить его последним из скриптов к страничке
// и вызвать, после подгрузки (конец метода OnInit <- Drawing/HtmlPage.js)
// var _api = new asc_docs_api();
// _api.init(oWordControl);

252 253 254 255 256 257
/**
 *
 * @param name
 * @constructor
 * @extends {baseEditorsApi}
 */
258 259
function asc_docs_api(name)
{
260
  asc_docs_api.superclass.constructor.call(this, name);
261

262 263 264 265 266
    if (window["AscDesktopEditor"])
    {
        window["AscDesktopEditor"]["CreateEditorApi"]();
    }

Oleg.Korshul's avatar
Oleg.Korshul committed
267 268
    var CSpellCheckApi  = window["CSpellCheckApi"];

269 270 271
    History    = new CHistory();
    g_oTableId = new CTableId();

272 273 274 275
	/************ private!!! **************/
    this.WordControl = new CEditorPage(this);
    this.WordControl.Name = this.HtmlElementName;

276 277
  this.documentFormatSave = c_oAscFileType.DOCX;

278 279
	//todo убрать из native, copypaste, chart, loadfont
    //this.DocumentUrl = "";
280
	this.InterfaceLocale = null;
281 282
        
    this.ShowParaMarks = false;
283
    this.ShowSnapLines = true;
284 285 286 287
	this.isAddSpaceBetweenPrg = false;
    this.isPageBreakBefore = false;
    this.isKeepLinesTogether = false;

288
    this.isPaintFormat = c_oAscFormatPainterState.kOff;
289 290 291 292 293
    this.isMarkerFormat = false;
    this.isViewMode = false;
    this.isStartAddShape = false;
    this.addShapePreset = "";
    this.isShowTableEmptyLine = true;
Oleg.Korshul's avatar
Oleg.Korshul committed
294
    this.isShowTableEmptyLineAttack = false;
295

296 297
    this.isApplyChangesOnOpen = false;
    this.isApplyChangesOnOpenEnabled = true;
Oleg.Korshul's avatar
Oleg.Korshul committed
298 299
	
	this.IsSpellCheckCurrentWord = false;
300

301
	this.mailMergeFileData = null;
302

303
  this.isCoMarksDraw = false;
304
	this.isDocumentCanSave = false;			// Флаг, говорит о возможности сохранять документ (активна кнопка save или нет)
305 306

	// Spell Checking
Oleg.Korshul's avatar
Oleg.Korshul committed
307
	this.SpellCheckApi = (window["AscDesktopEditor"] === undefined) ? new CSpellCheckApi() : new CSpellCheckApi_desktop();
308
	this.isSpellCheckEnable = true;
309

Oleg.Korshul's avatar
Oleg.Korshul committed
310 311
    // это чтобы сразу показать ридер, без возможности вернуться в редактор/вьюер
    this.isOnlyReaderMode = false;
312
	
313 314 315 316 317 318 319
    /**************************************/

    this.bInit_word_control = false;
	this.isDocumentModify = false;

    this.isImageChangeUrl = false;
    this.isShapeImageChangeUrl = false;
Oleg.Korshul's avatar
Oleg.Korshul committed
320 321 322

    this.FontAsyncLoadType = 0;
    this.FontAsyncLoadParam = null;
323 324 325 326 327 328 329 330 331 332
	
    this.isPasteFonts_Images = false;
    this.isLoadNoCutFonts = false;

    this.pasteCallback = null;
    this.pasteImageMap = null;
    this.EndActionLoadImages = 0;

    this.isSaveFonts_Images = false;
    this.saveImageMap = null;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
333

334 335 336 337 338 339 340 341
    this.isLoadImagesCustom = false;
    this.loadCustomImageMap = null;

    this.ServerIdWaitComplete = false;
    this.ServerImagesWaitComplete = false;

    this.DocumentOrientation = orientation_Portrait ? true : false;

342
    this.SelectedObjectsStack = [];
343

344
    this.nCurPointItemsLength = 0;
345
	this.isDocumentEditor = true;
346

347 348 349 350 351 352 353 354
    this.CurrentTranslate = translations_map["en"];

    this.CollaborativeMarksShowType = c_oAscCollaborativeMarksShowType.All;

    // объекты, нужные для отправки в тулбар (шрифты, стили)
    this._gui_control_colors = null;
    this._gui_color_schemes = null;

Oleg.Korshul's avatar
Oleg.Korshul committed
355
    //window["USE_FONTS_WIN_PARAMS"] = true;
356

357 358 359
    //выставляем тип copypaste
    g_bIsDocumentCopyPaste = true;
    this.DocumentReaderMode = null;
360

Oleg.Korshul's avatar
Oleg.Korshul committed
361 362
    this.IsLongActionCurrent = 0;
    this.LongActionCallbacks = [];
Oleg.Korshul's avatar
 
Oleg.Korshul committed
363
    this.LongActionCallbacksParams = [];
Oleg.Korshul's avatar
Oleg.Korshul committed
364

Oleg.Korshul's avatar
Oleg.Korshul committed
365
    this.ParcedDocument = false;
366
	this.isStartCoAuthoringOnEndLoad = false;	// Подсоединились раньше, чем документ загрузился
Alexander.Trofimov's avatar
Alexander.Trofimov committed
367

368
	var oThis = this;
369 370
	// init OnMessage
	InitOnMessage(function (error, url) {
371
		if (c_oAscError.ID.No !== error)
372 373 374
			oThis.sync_ErrorCallback(error, c_oAscError.Level.NoCritical);
		else
			oThis.AddImageUrl(url);
375

376 377
		editor.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.UploadImage);
	});
378 379
	// init drag&drop
	InitDragAndDrop(document.getElementById(this.HtmlElementName), function (error, files) {
380
		oThis._uploadCallback(error, files);
381
	});
Oleg.Korshul's avatar
Oleg.Korshul committed
382 383 384

    if (window.editor == undefined)
    {
Oleg.Korshul's avatar
 
Oleg.Korshul committed
385
        window.editor = this;
386
		window.editor;
Oleg.Korshul's avatar
Oleg.Korshul committed
387
        window['editor'] = window.editor;
Oleg.Korshul's avatar
Oleg.Korshul committed
388 389 390
        
        if (window["NATIVE_EDITOR_ENJINE"])
            editor = window.editor;
Oleg.Korshul's avatar
Oleg.Korshul committed
391
    }
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
392
    CHART_STYLE_MANAGER = new CChartStyleManager();
393 394

    this.RevisionChangesStack = [];
395
}
396
asc.extendClass(asc_docs_api, baseEditorsApi);
397

398 399 400 401
asc_docs_api.prototype.sendEvent = function() {
  this.asc_fireCallback.apply(this, arguments);
};

402 403 404
asc_docs_api.prototype.LoadFontsFromServer = function(_fonts)
{
    if (undefined === _fonts)
405
        _fonts = ["Arial","Symbol","Wingdings","Courier New","Times New Roman"];
406
    this.FontLoader.LoadFontsFromServer(_fonts);
407
};
408 409 410

asc_docs_api.prototype.SetCollaborativeMarksShowType = function(Type)
{
411
    if (c_oAscCollaborativeMarksShowType.None !== this.CollaborativeMarksShowType && c_oAscCollaborativeMarksShowType.None === Type && this.WordControl && this.WordControl.m_oLogicDocument)
412 413 414 415 416 417 418 419
    {
        this.CollaborativeMarksShowType = Type;
        CollaborativeEditing.Clear_CollaborativeMarks(true);
    }
    else
    {
        this.CollaborativeMarksShowType = Type;
    }
420
};
421 422 423 424

asc_docs_api.prototype.GetCollaborativeMarksShowType = function(Type)
{
    return this.CollaborativeMarksShowType;
425
};
426 427 428 429

asc_docs_api.prototype.Clear_CollaborativeMarks = function()
{
    CollaborativeEditing.Clear_CollaborativeMarks(true);
430
};
431 432 433 434 435 436

asc_docs_api.prototype.SetLanguage = function(langId)
{
    langId = langId.toLowerCase();
    if (undefined !== translations_map[langId])
        this.CurrentTranslate = translations_map[langId];
437
};
438 439 440 441 442 443 444 445 446

asc_docs_api.prototype.TranslateStyleName = function(style_name)
{
    var ret = this.CurrentTranslate.DefaultStyles[style_name];

    if (ret !== undefined)
        return ret;

    return style_name;
447
};
448 449 450 451 452 453 454 455 456 457 458 459
asc_docs_api.prototype.CheckChangedDocument = function()
{
    if (true === History.Have_Changes())
    {
        // дублирование евента. когда будет undo-redo - тогда
        // эти евенты начнут отличаться
        this.SetDocumentModified(true);
    }
    else
    {
        this.SetDocumentModified(false);
    }
460

461 462
    this._onUpdateDocumentCanSave();
};
463 464
asc_docs_api.prototype.SetUnchangedDocument = function()
{
Oleg.Korshul's avatar
Oleg.Korshul committed
465 466 467 468 469 470 471
    this.SetDocumentModified(false);
    this._onUpdateDocumentCanSave();
};

asc_docs_api.prototype.SetDocumentModified = function(bValue)
{
    this.isDocumentModify = bValue;
472
    this.asc_fireCallback("asc_onDocumentModifiedChanged");
Oleg.Korshul's avatar
 
Oleg.Korshul committed
473 474 475 476 477

    if (undefined !== window["AscDesktopEditor"])
    {
        window["AscDesktopEditor"]["onDocumentModifiedChanged"](bValue);
    }
478
};
479 480 481

asc_docs_api.prototype.isDocumentModified = function()
{
482 483 484 485
	if (!this.canSave) {
		// Пока идет сохранение, мы не закрываем документ
		return true;
	}
486
    return this.isDocumentModify;
487
};
488

489 490 491 492 493 494 495
/**
 * Эта функция возвращает true, если есть изменения или есть lock-и в документе
 */
asc_docs_api.prototype.asc_isDocumentCanSave = function () {
	return this.isDocumentCanSave;
};

496 497 498 499
asc_docs_api.prototype.sync_BeginCatchSelectedElements = function()
{
    if (0 != this.SelectedObjectsStack.length)
        this.SelectedObjectsStack.splice(0, this.SelectedObjectsStack.length);
Oleg.Korshul's avatar
Oleg.Korshul committed
500 501 502

    if (this.WordControl && this.WordControl.m_oDrawingDocument)
        this.WordControl.m_oDrawingDocument.StartTableStylesCheck();
503
};
504 505
asc_docs_api.prototype.sync_EndCatchSelectedElements = function()
{
Oleg.Korshul's avatar
Oleg.Korshul committed
506 507
    if (this.WordControl && this.WordControl.m_oDrawingDocument)
        this.WordControl.m_oDrawingDocument.EndTableStylesCheck();
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
508

509
    this.asc_fireCallback("asc_onFocusObject", this.SelectedObjectsStack);
510
};
Ilya.Kirillov's avatar
Ilya.Kirillov committed
511
asc_docs_api.prototype.getSelectedElements = function(bUpdate)
512
{
Ilya.Kirillov's avatar
Ilya.Kirillov committed
513
    if ( true === bUpdate )
Oleg.Korshul's avatar
Oleg.Korshul committed
514
        this.WordControl.m_oLogicDocument.Document_UpdateInterfaceState();
Ilya.Kirillov's avatar
Ilya.Kirillov committed
515

516
    return this.SelectedObjectsStack;
517
};
518 519 520 521 522 523
asc_docs_api.prototype.sync_ChangeLastSelectedElement = function(type, obj)
{			
	var oUnkTypeObj = null;
			
	switch( type )
	{
524
		case c_oAscTypeSelectElement.Paragraph: oUnkTypeObj = new asc_CParagraphProperty( obj );
525
			break;
526
		case c_oAscTypeSelectElement.Image: oUnkTypeObj = new asc_CImgProperty( obj );
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
			break;
		case c_oAscTypeSelectElement.Table: oUnkTypeObj = new CTableProp( obj );
			break;
		case c_oAscTypeSelectElement.Header: oUnkTypeObj = new CHeaderProp( obj );
			break;
	}
			
    var _i = this.SelectedObjectsStack.length - 1;
    var bIsFound = false;
    while (_i >= 0)
    {
        if (this.SelectedObjectsStack[_i].Type == type)
        {

            this.SelectedObjectsStack[_i].Value = oUnkTypeObj;
            bIsFound = true;
            break;
        }
        _i--;
    }

    if (!bIsFound)
    {
550
        this.SelectedObjectsStack[this.SelectedObjectsStack.length] = new asc_CSelectedObject( type, oUnkTypeObj );
551
    }
552
};
553 554 555 556

asc_docs_api.prototype.Init = function()
{
	this.WordControl.Init();
557
};
558

559 560 561
asc_docs_api.prototype._onEndPermissions = function() {
  if (this.isOnFirstConnectEnd) {
    this.asc_fireCallback('asc_onGetEditorPermissions', new window['Asc'].asc_CAscEditorPermissions());
562
  }
563
};
564

565 566 567 568
asc_docs_api.prototype.asc_setDocInfo = function(c_DocInfo) {
  if (c_DocInfo) {
    this.DocInfo = c_DocInfo;
  }
569

570
  if (this.DocInfo) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
571
    this.documentId = this.DocInfo.get_Id();
572
    this.documentUserId = this.DocInfo.get_UserId();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
573
    this.documentUrl = this.DocInfo.get_Url();
574
    this.documentTitle = this.DocInfo.get_Title();
575
    this.documentFormat = this.DocInfo.get_Format();
576
    this.documentCallbackUrl = this.DocInfo.get_CallbackUrl();
577
    this.documentVKey = this.DocInfo.get_VKey();
578
    var sProtocol = window.location.protocol;
579
    this.documentOrigin = ((sProtocol && '' !== sProtocol) ? sProtocol + '//' : '') + window.location.host;
580 581 582 583 584 585 586

    this.User = new Asc.asc_CUser();
    this.User.asc_setId(this.DocInfo.get_UserId());
    this.User.asc_setUserName(this.DocInfo.get_UserName());
  }

  if (undefined !== window["AscDesktopEditor"]) {
587
    window["AscDesktopEditor"]["SetDocumentName"](this.documentTitle);
588
  }
589 590 591 592 593
};
asc_docs_api.prototype.asc_setLocale = function(val)
{
	this.InterfaceLocale = val;
};
594
asc_docs_api.prototype.LoadDocument = function(isVersionHistory) {
595 596 597 598 599 600 601
  this.CoAuthoringApi.auth(this.isViewMode);

  this.WordControl.m_oDrawingDocument.m_bIsOpeningDocument = true;

  // Меняем тип состояния (на открытие)
  this.advancedOptionsAction = c_oAscAdvancedOptionsAction.Open;

Alexander.Trofimov's avatar
Alexander.Trofimov committed
602
  if (offlineMode !== this.documentUrl) {
603 604
    var rData = {
      "c": 'open',
Alexander.Trofimov's avatar
Alexander.Trofimov committed
605
      "id": this.documentId,
606
      "userid": this.documentUserId,
607
      "format": this.documentFormat,
608
      "vkey": this.documentVKey,
609
      "editorid": c_oEditorId.Word,
Alexander.Trofimov's avatar
Alexander.Trofimov committed
610
      "url": this.documentUrl,
611
      "title": this.documentTitle,
612 613 614
      "embeddedfonts": this.isUseEmbeddedCutFonts,
      "viewmode": this.isViewMode
    };
615 616 617 618 619
    if (isVersionHistory) {
      //чтобы результат пришел только этому соединению, а не всем кто в документе
      rData["userconnectionid"] = this.CoAuthoringApi.getUserConnectionId();
    }

620 621 622 623
    this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.Open);
    sendCommand2(this, null, rData);
  } else {
    // ToDo убрать зависимость от this.FontLoader.fontFilesPath
Alexander.Trofimov's avatar
Alexander.Trofimov committed
624
    this.documentUrl = this.FontLoader.fontFilesPath + "../Word/document/";
625
    this.DocInfo.put_OfflineApp(true);
626

627
    this._OfflineAppDocumentStartLoad();
628
  }
629

630
  this.sync_zoomChangeCallback(this.WordControl.m_nZoomValue, 0);
631
};
632 633 634 635

asc_docs_api.prototype.SetFontsPath = function(path)
{
	this.FontLoader.fontFilesPath = path;
636
};
637 638 639 640

asc_docs_api.prototype.SetTextBoxInputMode = function(bIsEA)
{
    this.WordControl.SetTextBoxMode(bIsEA);
641
};
642 643 644
asc_docs_api.prototype.GetTextBoxInputMode = function()
{
    return this.WordControl.TextBoxInputMode;
645
};
646 647 648 649

asc_docs_api.prototype.ChangeReaderMode = function()
{
    return this.WordControl.ChangeReaderMode();
650
};
Oleg.Korshul's avatar
Oleg.Korshul committed
651 652 653 654
asc_docs_api.prototype.SetReaderModeOnly = function()
{
    this.isOnlyReaderMode = true;
    this.ImageLoader.bIsAsyncLoadDocumentImages = false;
655
};
656 657 658 659

asc_docs_api.prototype.IncreaseReaderFontSize = function()
{
    return this.WordControl.IncreaseReaderFontSize();
660
};
661 662 663
asc_docs_api.prototype.DecreaseReaderFontSize = function()
{
    return this.WordControl.DecreaseReaderFontSize();
664
};
665 666 667

asc_docs_api.prototype.CreateCSS = function()
{
Oleg.Korshul's avatar
Oleg.Korshul committed
668 669
    if (window["flat_desine"] === true)
    {
Oleg.Korshul's avatar
Oleg.Korshul committed
670
        GlobalSkin = GlobalSkinFlat;
Oleg.Korshul's avatar
Oleg.Korshul committed
671 672
    }

673 674 675 676 677 678 679 680 681 682
    var _head = document.getElementsByTagName('head')[0];

    var style0 = document.createElement('style');
    style0.type = 'text/css';
    style0.innerHTML = ".block_elem { position:absolute;padding:0;margin:0; }";
    _head.appendChild(style0);

    var style2 = document.createElement('style');
    style2.type = 'text/css';
    style2.innerHTML = ".buttonRuler {\
Oleg.Korshul's avatar
Oleg.Korshul committed
683
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAwCAYAAAAYX/pXAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwwAADsMBx2+oZAAAABp0RVh0U29mdHdhcmUAUGFpbnQuTkVUIHYzLjUuMTAw9HKhAAABhElEQVRIS62Uwa6CMBBF/VQNQcOCBS5caOICApEt3+Wv+AcmfQ7pbdreqY+CJifTdjpng727aZrMFmbB+/3erYEE+/3egMPhMPP57QR/EJCgKAoTs1hQlqURjsdjAESyPp1O7pwEVVWZ1+s1VyB7DemRoK5rN+CvNaRPgqZpgqHz+UwSnEklweVyCQbivX8mlQTX65UGfG63m+vLXRLc7/ekQHoAexK0bWs0uq5TKwli8Afq+94Mw+CQPe78K5D6eDzMOI4GVcCdr4IlOMEWfiP4fJpVkEDLA38ghgR+DgB/ICYQ5OYBCez7d1mAvQZ6gcBmAK010A8ENg8c9u2rZ6iBwL51R7z3z1ADgc2DJDYPZnA3ENi3rhLlgauBAO8/JpUHJEih5QF6iwRaHqC3SPANJ9jCbwTP53MVJNDywB+IIYGfA8AfiAkEqTyQDEAO+HlAgtw8IEFuHpAgNw9IkJsHJMjNAxLk5gEJ8P5jUnlAghRaHqC3SKDlAXqLBN9wgvVM5g/dFuEU6U2wnAAAAABJRU5ErkJggg==);\
684 685 686 687 688 689 690 691
background-position: 0px 0px;\
background-repeat: no-repeat;\
}";
    _head.appendChild(style2);

    var style3 = document.createElement('style');
    style3.type = 'text/css';
    style3.innerHTML = ".buttonPrevPage {\
Anna.Pavlova's avatar
Anna.Pavlova committed
692
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAABgBAMAAADm/++TAAAABGdBTUEAALGPC/xhBQAAABJQTFRFAAAA////UVNVu77Cenp62Nrc3x8hMQAAAAF0Uk5TAEDm2GYAAABySURBVCjPY2AgETDBGEoKUAElJcJSxANjKGAwDQWDYAKMIBhDSRXCCFJSIixF0GS4M+AMExcwcCbAcIQxBEUgDEdBQcJSBE2GO4PU6IJHASxS4NGER4p28YWIAlikwKMJjxTt4gsRBbBIgUcTHini4wsAwMmIvYZODL0AAAAASUVORK5CYII=);\
693 694 695 696 697 698 699 700
background-position: 0px 0px;\
background-repeat: no-repeat;\
}";
    _head.appendChild(style3);

    var style4 = document.createElement('style');
    style4.type = 'text/css';
    style4.innerHTML = ".buttonNextPage {\
Anna.Pavlova's avatar
Anna.Pavlova committed
701
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAABgBAMAAADm/++TAAAABGdBTUEAALGPC/xhBQAAABJQTFRFAAAA////UVNVu77Cenp62Nrc3x8hMQAAAAF0Uk5TAEDm2GYAAABySURBVCjPY2AgETDBGEoKUAElJcJSxANjKGAwDQWDYAKMIBhDSRXCCFJSIixF0GS4M+AMExcwcCbAcIQxBEUgDEdBQcJSBE2GO4PU6IJHASxS4NGER4p28YWIAlikwKMJjxTt4gsRBbBIgUcTHini4wsAwMmIvYZODL0AAAAASUVORK5CYII=);\
702 703 704 705
background-position: 0px -48px;\
background-repeat: no-repeat;\
}";
    _head.appendChild(style4);
706
};
707 708 709 710 711 712 713

asc_docs_api.prototype.CreateComponents = function()
{
    this.CreateCSS();

	var element = document.getElementById(this.HtmlElementName);
	if (element != null)
Oleg.Korshul's avatar
Oleg.Korshul committed
714
		element.innerHTML = "<div id=\"id_main\" class=\"block_elem\" style=\"-moz-user-select:none;-khtml-user-select:none;user-select:none;background-color:" + GlobalSkin.BackgroundColor + ";overflow:hidden;\" UNSELECTABLE=\"on\">\
715
								<div id=\"id_panel_left\" class=\"block_elem\">\
716
									<canvas id=\"id_buttonTabs\" class=\"block_elem\"></canvas>\
717 718 719 720 721 722
									<canvas id=\"id_vert_ruler\" class=\"block_elem\"></canvas>\
								</div>\
									<div id=\"id_panel_top\" class=\"block_elem\">\
									<canvas id=\"id_hor_ruler\" class=\"block_elem\"></canvas>\
									</div>\
                                    <div id=\"id_main_view\" class=\"block_elem\" style=\"overflow:hidden\">\
723 724 725
                                        <canvas id=\"id_viewer\" class=\"block_elem\" style=\"-webkit-user-select: none; background-color:" + GlobalSkin.BackgroundColor + ";z-index:1\"></canvas>\
									    <canvas id=\"id_viewer_overlay\" class=\"block_elem\" style=\"-webkit-user-select: none; z-index:2\"></canvas>\
									    <canvas id=\"id_target_cursor\" class=\"block_elem\" width=\"1\" height=\"1\" style=\"-webkit-user-select: none;width:2px;height:13px;display:none;z-index:3;\"></canvas>\
726 727
                                    </div>\
								</div>\
Oleg.Korshul's avatar
Oleg.Korshul committed
728
									<div id=\"id_panel_right\" class=\"block_elem\" style=\"margin-right:1px;background-color:" + GlobalSkin.BackgroundScroll + ";\">\
729
									<div id=\"id_buttonRulers\" class=\"block_elem buttonRuler\"></div>\
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
730 731
									<div id=\"id_vertical_scroll\" style=\"left:0;top:0px;width:14px;overflow:hidden;position:absolute;\">\
									<div id=\"panel_right_scroll\" class=\"block_elem\" style=\"left:0;top:0;width:1px;height:6000px;\"></div>\
732 733 734 735
									</div>\
									<div id=\"id_buttonPrevPage\" class=\"block_elem buttonPrevPage\"></div>\
									<div id=\"id_buttonNextPage\" class=\"block_elem buttonNextPage\"></div>\
								</div>\
Oleg.Korshul's avatar
Oleg.Korshul committed
736
									<div id=\"id_horscrollpanel\" class=\"block_elem\" style=\"margin-bottom:1px;background-color:" + GlobalSkin.BackgroundScroll + ";\">\
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
737 738
									<div id=\"id_horizontal_scroll\" style=\"left:0px;top:0;height:14px;overflow:hidden;position:absolute;width:100%;\">\
										<div id=\"panel_hor_scroll\" class=\"block_elem\" style=\"left:0;top:0;width:6000px;height:1px;\"></div>\
739 740
									</div>\
									</div>";
741
};
742 743 744 745 746 747

asc_docs_api.prototype.GetCopyPasteDivId = function()
{
    if (this.isMobileVersion)
        return this.WordControl.Name;
    return "";
748
};
749 750 751 752

asc_docs_api.prototype.ContentToHTML = function(bIsRet)
{
    this.DocumentReaderMode = new CDocumentReaderMode();
Igor.Zotov's avatar
Igor.Zotov committed
753 754
    var _old = copyPasteUseBinary;
    copyPasteUseBinary = false;
Oleg.Korshul's avatar
Oleg.Korshul committed
755
    this.WordControl.m_oLogicDocument.Select_All();
756
    Editor_Copy(this);
Oleg.Korshul's avatar
Oleg.Korshul committed
757
    this.WordControl.m_oLogicDocument.Selection_Remove();
Igor.Zotov's avatar
Igor.Zotov committed
758
    copyPasteUseBinary = _old;
759 760
    this.DocumentReaderMode = null;
    return document.getElementById("SelectId").innerHTML;
761
};
762 763 764 765 766

asc_docs_api.prototype.InitEditor = function()
{
    this.WordControl.m_oLogicDocument   = new CDocument(this.WordControl.m_oDrawingDocument);
    this.WordControl.m_oDrawingDocument.m_oLogicDocument = this.WordControl.m_oLogicDocument;
767 768
	if (!this.isSpellCheckEnable)
		this.WordControl.m_oLogicDocument.TurnOff_CheckSpelling();
769 770 771

    if (this.WordControl.MobileTouchManager)
        this.WordControl.MobileTouchManager.LogicDocument = this.WordControl.m_oLogicDocument;
772
};
773 774 775 776

asc_docs_api.prototype.SetInterfaceDrawImagePlaceShape = function(div_id)
{
    this.WordControl.m_oDrawingDocument.InitGuiCanvasShape(div_id);
777
};
778 779 780 781

asc_docs_api.prototype.InitViewer = function()
{
    this.WordControl.m_oDrawingDocument.m_oDocumentRenderer = new CDocMeta();
782
};
783 784 785

asc_docs_api.prototype.OpenDocument = function(url, gObject)
{
Oleg.Korshul's avatar
Oleg.Korshul committed
786
    this.isOnlyReaderMode = false;
787 788 789 790 791
    this.InitViewer();
    this.LoadedObject = null;
    this.DocumentType = 1;
    this.ServerIdWaitComplete = true;

792 793
    this.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.Open);

794 795
    this.WordControl.m_oDrawingDocument.m_oDocumentRenderer.Load(url, gObject);
    this.FontLoader.LoadDocumentFonts(this.WordControl.m_oDrawingDocument.m_oDocumentRenderer.Fonts, true);
796
};
797 798 799 800 801 802 803 804 805 806 807 808 809

asc_docs_api.prototype.OpenDocument2 = function(url, gObject)
{
	this.InitEditor();
	this.DocumentType = 2;
	this.LoadedObjectDS = Common_CopyObj(this.WordControl.m_oLogicDocument.Get_Styles().Style);

	g_oIdCounter.Set_Load(true);

	var openParams = {checkFileSize: this.isMobileVersion, charCount: 0, parCount: 0};
	var oBinaryFileReader = new BinaryFileReader(this.WordControl.m_oLogicDocument, openParams);
	if(oBinaryFileReader.Read(gObject))
	{
810 811 812 813
        if (History && History.Update_FileDescription)
            History.Update_FileDescription(oBinaryFileReader.stream);

        g_oIdCounter.Set_Load(false);
814 815 816 817 818 819 820 821
		this.LoadedObject = 1;

		this.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.Open);

		// проверяем какие шрифты нужны
		this.WordControl.m_oDrawingDocument.CheckFontNeeds();
		window.global_pptx_content_loader.CheckImagesNeeds(this.WordControl.m_oLogicDocument);

822
		//this.FontLoader.LoadEmbeddedFonts(this.DocumentUrl, this.WordControl.m_oLogicDocument.EmbeddedFonts);
823 824 825 826
		this.FontLoader.LoadDocumentFonts(this.WordControl.m_oLogicDocument.Fonts, false);
	}
	else
		editor.asc_fireCallback("asc_onError",c_oAscError.ID.MobileUnexpectedCharCount,c_oAscError.Level.Critical);
827
    
828 829 830 831 832 833 834 835 836 837
	//callback
	editor.DocumentOrientation = (null == editor.WordControl.m_oLogicDocument) ? true : !editor.WordControl.m_oLogicDocument.Orientation;
	var sizeMM;
	if(editor.DocumentOrientation)
		sizeMM = DocumentPageSize.getSize(Page_Width, Page_Height);
	else
		sizeMM = DocumentPageSize.getSize(Page_Height, Page_Width);
	editor.sync_DocSizeCallback(sizeMM.w_mm, sizeMM.h_mm);
	editor.sync_PageOrientCallback(editor.get_DocumentOrientation());
							
Oleg.Korshul's avatar
Oleg.Korshul committed
838
    this.ParcedDocument = true;
839 840 841 842
	if (this.isStartCoAuthoringOnEndLoad) {
		this.CoAuthoringApi.onStartCoAuthoring(true);
		this.isStartCoAuthoringOnEndLoad = false;
	}
Oleg.Korshul's avatar
Oleg.Korshul committed
843

Oleg.Korshul's avatar
Oleg.Korshul committed
844 845 846 847 848 849 850
    if (this.isMobileVersion)
    {
        window.USER_AGENT_SAFARI_MACOS = false;
        PASTE_ELEMENT_ID = "wrd_pastebin";
        ELEMENT_DISPAY_STYLE = "none";
    }

Oleg.Korshul's avatar
Oleg.Korshul committed
851 852
    if (window.USER_AGENT_SAFARI_MACOS)
        setInterval(SafariIntervalFocus, 10);
853
};
854 855 856 857 858 859 860
// Callbacks
/* все имена callback'оф начинаются с On. Пока сделаны:
	OnBold,
	OnItalic,
	OnUnderline,
	OnTextPrBaseline(возвращается расположение строки - supstring, superstring, baseline),
	OnPrAlign(выравнивание по ширине, правому краю, левому краю, по центру),
861
	OnListType( возвращается asc_CListType )
862 863 864 865 866

	фейк-функции ожидающие TODO:
	Print,Undo,Redo,Copy,Cut,Paste,Share,Save,Download & callbacks
	OnFontName, OnFontSize, OnLineSpacing

867
	OnFocusObject( возвращается массив asc_CSelectedObject )
868 869
	OnInitEditorStyles( возвращается CStylesPainter )
	OnSearchFound( возвращается CSearchResult );
870
	OnParaSpacingLine( возвращается asc_CParagraphSpacing )
871 872 873 874
	OnLineSpacing( не используется? )
	OnTextColor( возвращается CColor )
	OnTextHightLight( возвращается CColor )
	OnInitEditorFonts( возвращается массив объектов СFont )
875
	OnFontFamily( возвращается asc_CTextFontFamily )
876 877 878 879 880 881 882
*/
var _callbacks = {};

asc_docs_api.prototype.asc_registerCallback = function(name, callback) {
	if (!_callbacks.hasOwnProperty(name))
		_callbacks[name] = [];
	_callbacks[name].push(callback);
883
};
884 885 886 887 888 889 890 891

asc_docs_api.prototype.asc_unregisterCallback = function(name, callback) {
	if (_callbacks.hasOwnProperty(name)) {
		for (var i = _callbacks[name].length - 1; i >= 0 ; --i) {
			if (_callbacks[name][i] == callback)
				_callbacks[name].splice(i, 1);
		}
	}
892
};
893 894 895 896 897 898 899 900 901 902 903

asc_docs_api.prototype.asc_fireCallback = function(name) {
	if (_callbacks.hasOwnProperty(name))
    {
		for (var i = 0; i < _callbacks[name].length; ++i)
        {
			_callbacks[name][i].apply(this || window, Array.prototype.slice.call(arguments, 1));
		}
        return true;
	}
    return false;
904
};
905 906 907 908 909 910 911

asc_docs_api.prototype.asc_checkNeedCallback = function(name) {
    if (_callbacks.hasOwnProperty(name))
    {
        return true;
    }
    return false;
912
};
913

Oleg.Korshul's avatar
Oleg.Korshul committed
914 915 916 917 918
// тут методы, замены евентов
asc_docs_api.prototype.get_PropertyEditorShapes = function()
{
    var ret = [g_oAutoShapesGroups, g_oAutoShapesTypes];
    return ret;
919
};
920 921 922 923 924
asc_docs_api.prototype.get_PropertyEditorTextArts = function()
{
    var ret = [g_oPresetTxWarpGroups, g_PresetTxWarpTypes];
    return ret;
};
Oleg.Korshul's avatar
Oleg.Korshul committed
925 926 927 928 929 930
asc_docs_api.prototype.get_PropertyStandartTextures = function()
{
    var _count = g_oUserTexturePresets.length;
    var arr = new Array(_count);
    for (var i = 0; i < _count; ++i)
    {
931
        arr[i] = new asc_CTexture();
Oleg.Korshul's avatar
Oleg.Korshul committed
932 933 934 935
        arr[i].Id = i;
        arr[i].Image = g_oUserTexturePresets[i];
    }
    return arr;
936
};
Oleg.Korshul's avatar
Oleg.Korshul committed
937 938 939 940
asc_docs_api.prototype.get_PropertyThemeColors = function()
{
    var _ret = [this._gui_control_colors.Colors, this._gui_control_colors.StandartColors];
    return _ret;
941
};
Oleg.Korshul's avatar
Oleg.Korshul committed
942 943 944
asc_docs_api.prototype.get_PropertyThemeColorSchemes = function()
{
    return this._gui_color_schemes;
945
};
Oleg.Korshul's avatar
Oleg.Korshul committed
946 947
// -------

948 949 950 951
/////////////////////////////////////////////////////////////////////////
///////////////////CoAuthoring and Chat api//////////////////////////////
/////////////////////////////////////////////////////////////////////////
// Init CoAuthoring
952 953 954
asc_docs_api.prototype._coAuthoringSetChange = function(change, oColor)
{
	var oChange = new CCollaborativeChanges();
955
	oChange.Set_Data( change );
956 957 958 959
	oChange.Set_Color( oColor );
	CollaborativeEditing.Add_Changes( oChange );
};

Oleg.Korshul's avatar
Oleg.Korshul committed
960 961
asc_docs_api.prototype._coAuthoringSetChanges = function(e, oColor)
{
962 963 964 965
	var Count = e.length;
	for (var Index = 0; Index < Count; ++Index)
		this._coAuthoringSetChange(e[Index], oColor);
};
Oleg.Korshul's avatar
Oleg.Korshul committed
966

967 968 969 970 971 972 973
asc_docs_api.prototype._coAuthoringInit = function() {
  //Если User не задан, отключаем коавторинг.
  if (null == this.User || null == this.User.asc_getId()) {
    this.User = new Asc.asc_CUser();
    this.User.asc_setId("Unknown");
    this.User.asc_setUserName("Unknown");
  }
974

975 976 977 978 979 980 981 982 983 984 985 986
  var t = this;
  this.CoAuthoringApi.onParticipantsChanged = function(e, CountEditUsers) {
    t.asc_fireCallback("asc_onParticipantsChanged", e, CountEditUsers);
  };
  this.CoAuthoringApi.onAuthParticipantsChanged = function(e, count) {
    t.asc_fireCallback("asc_onAuthParticipantsChanged", e, count);
  };
  this.CoAuthoringApi.onMessage = function(e, clear) {
    t.asc_fireCallback("asc_onCoAuthoringChatReceiveMessage", e, clear);
  };
  this.CoAuthoringApi.onCursor = function(e) {
    if (true === CollaborativeEditing.Is_Fast()) {
987
      t.WordControl.m_oLogicDocument.Update_ForeignCursor(e[e.length - 1]['cursor'], e[e.length - 1]['user'], true);
988 989 990
    }
  };
  this.CoAuthoringApi.onConnectionStateChanged = function(e) {
991 992
    if (true === CollaborativeEditing.Is_Fast() && false === e['state']) {
      editor.WordControl.m_oLogicDocument.Remove_ForeignCursor(e['id']);
993 994 995
    }
    t.asc_fireCallback("asc_onConnectionStateChanged", e);
  };
Alexander.Trofimov's avatar
Alexander.Trofimov committed
996 997 998
  this.CoAuthoringApi.onLocksAcquired = function(e) {
    if (t.isApplyChangesOnOpenEnabled) {
      // Пока документ еще не загружен, будем сохранять функцию и аргументы
999 1000 1001
      t.arrPreOpenLocksObjects.push(function() {
        t.CoAuthoringApi.onLocksAcquired(e);
      });
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
      return;
    }

    if (2 != e["state"]) {
      var Id = e["block"];
      var Class = g_oTableId.Get_ById(Id);
      if (null != Class) {
        var Lock = Class.Lock;

        var OldType = Class.Lock.Get_Type();
        if (locktype_Other2 === OldType || locktype_Other3 === OldType) {
          Lock.Set_Type(locktype_Other3, true);
        } else {
          Lock.Set_Type(locktype_Other, true);
1016 1017
        }

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
        // Выставляем ID пользователя, залочившего данный элемент
        Lock.Set_UserId(e["user"]);

        if (Class instanceof CHeaderFooterController) {
          editor.sync_LockHeaderFooters();
        } else if (Class instanceof CDocument) {
          editor.sync_LockDocumentProps();
        } else if (Class instanceof CComment) {
          editor.sync_LockComment(Class.Get_Id(), e["user"]);
        } else if (Class instanceof CGraphicObjects) {
          editor.sync_LockDocumentSchema();
1029
        }
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1030

1031
        // Теперь обновлять состояние необходимо, чтобы обновить локи в режиме рецензирования.
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1032 1033 1034 1035 1036 1037 1038 1039 1040
        editor.WordControl.m_oLogicDocument.Document_UpdateInterfaceState();
      } else {
        CollaborativeEditing.Add_NeedLock(Id, e["user"]);
      }
    }
  };
  this.CoAuthoringApi.onLocksReleased = function(e, bChanges) {
    if (t.isApplyChangesOnOpenEnabled) {
      // Пока документ еще не загружен, будем сохранять функцию и аргументы
1041 1042 1043
      t.arrPreOpenLocksObjects.push(function() {
        t.CoAuthoringApi.onLocksReleased(e, bChanges);
      });
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
      return;
    }

    var Id = e["block"];
    var Class = g_oTableId.Get_ById(Id);
    if (null != Class) {
      var Lock = Class.Lock;
      if ("undefined" != typeof(Lock)) {
        var CurType = Lock.Get_Type();

        var NewType = locktype_None;

        if (CurType === locktype_Other) {
          if (true != bChanges) {
            NewType = locktype_None;
          } else {
            NewType = locktype_Other2;
            CollaborativeEditing.Add_Unlock(Class);
          }
        } else if (CurType === locktype_Mine) {
          // Такого быть не должно
          NewType = locktype_Mine;
        } else if (CurType === locktype_Other2 || CurType === locktype_Other3) {
          NewType = locktype_Other2;
1068
        }
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1069 1070

        Lock.Set_Type(NewType, true);
1071 1072 1073

        // Теперь обновлять состояние необходимо, чтобы обновить локи в режиме рецензирования.
        editor.WordControl.m_oLogicDocument.Document_UpdateInterfaceState();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1074 1075 1076 1077 1078
      }
    } else {
      CollaborativeEditing.Remove_NeedLock(Id);
    }
  };
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
  this.CoAuthoringApi.onSaveChanges = function(e, userId, bFirstLoad) {
    var bUseColor;
    if (bFirstLoad) {
      bUseColor = -1 === CollaborativeEditing.m_nUseType;
    }
    if (editor.CollaborativeMarksShowType === c_oAscCollaborativeMarksShowType.None) {
      bUseColor = false;
    }

    var oUser = t.CoAuthoringApi.getUser(userId);
    var nColor = oUser ? oUser.asc_getColorValue() : null;
    var oColor = false === bUseColor ? null : (null !== nColor ? new CDocumentColor((nColor >> 16) & 0xFF, (nColor >> 8) & 0xFF, nColor & 0xFF) : new CDocumentColor(191, 255, 199));

    t._coAuthoringSetChange(e, oColor);
    // т.е. если bSendEvent не задан, то посылаем  сообщение + когда загрузился документ
    if (!bFirstLoad && t.bInit_word_control) {
      t.sync_CollaborativeChanges();
    }
  };
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
  this.CoAuthoringApi.onFirstLoadChangesEnd = function() {
    t.asyncServerIdEndLoaded();
  };
  this.CoAuthoringApi.onSpellCheckInit = function(e) {
    t.SpellCheckUrl = e;
    t._coSpellCheckInit();
  };
  this.CoAuthoringApi.onSetIndexUser = function(e) {
    g_oIdCounter.Set_UserId('' + e);
  };
1108 1109 1110
  this.CoAuthoringApi.onStartCoAuthoring = function(isStartEvent) {
    CollaborativeEditing.Start_CollaborationEditing();
    t.asc_setDrawCollaborationMarks(true);
1111

1112 1113
    if (t.ParcedDocument) {
      t.WordControl.m_oLogicDocument.DrawingDocument.Start_CollaborationEditing();
1114

1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
      if (!isStartEvent) {
        if (true != History.Is_Clear()) {
          CollaborativeEditing.Apply_Changes();
          CollaborativeEditing.Send_Changes();
        } else {
          // Изменений нет, но нужно сбросить lock
          t.CoAuthoringApi.unLockDocument(true);
        }
      }
    } else {
      t.isStartCoAuthoringOnEndLoad = true;
      if (!isStartEvent) {
        // Документ еще не подгрузился, но нужно сбросить lock
        t.CoAuthoringApi.unLockDocument(false);
      }
    }
  };
  this.CoAuthoringApi.onEndCoAuthoring = function(isStartEvent) {
    CollaborativeEditing.End_CollaborationEditing();
    editor.asc_setDrawCollaborationMarks(false);
  };
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1136
  this.CoAuthoringApi.onFirstConnect = function() {
1137
    t.isOnFirstConnectEnd = true;
1138
    t._onEndPermissions();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1139
  };
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
  /**
   * Event об отсоединении от сервера
   * @param {jQuery} e  event об отсоединении с причиной
   * @param {Bool} isDisconnectAtAll  окончательно ли отсоединяемся(true) или будем пробовать сделать reconnect(false) + сами отключились
   * @param {Bool} isCloseCoAuthoring
   */
  this.CoAuthoringApi.onDisconnect = function(e, isDisconnectAtAll, isCloseCoAuthoring) {
    if (ConnectionState.None === t.CoAuthoringApi.get_state()) {
      t.asyncServerIdEndLoaded();
    }
    if (isDisconnectAtAll) {
      // Посылаем наверх эвент об отключении от сервера
      t.asc_fireCallback("asc_onCoAuthoringDisconnect");
      t.SetViewMode(true);
      t.sync_ErrorCallback(isCloseCoAuthoring ? c_oAscError.ID.UserDrop : c_oAscError.ID.CoAuthoringDisconnect, c_oAscError.Level.NoCritical);
    }
  };
  this.CoAuthoringApi.onWarning = function(e) {
    t.sync_ErrorCallback(c_oAscError.ID.Warning, c_oAscError.Level.NoCritical);
  };
1160 1161 1162 1163 1164 1165 1166 1167 1168 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 1194 1195 1196
  this.CoAuthoringApi.onDocumentOpen = function(inputWrap) {
    if (inputWrap["data"]) {
      var input = inputWrap["data"];
      switch (input["type"]) {
        case 'reopen':
        case 'open':
        {
          switch (input["status"]) {
            case "updateversion":
            case "ok":
              var urls = input["data"];
              g_oDocumentUrls.init(urls);
              if (null != urls['Editor.bin']) {
                if ('ok' === input["status"] || editor.isViewMode) {
                  _onOpenCommand(function() {
                  }, {'data': urls['Editor.bin']});
                } else {
                  editor.asc_fireCallback("asc_onDocumentUpdateVersion", function() {
                    if (editor.isCoAuthoringEnable) {
                      editor.asc_coAuthoringDisconnect();
                    }
                    _onOpenCommand(function() {
                    }, {'data': urls['Editor.bin']});
                  });
                }
              } else {
                t.asc_fireCallback("asc_onError", c_oAscError.ID.ConvertationError, c_oAscError.Level.Critical);
              }
              break;
            case "needparams":
              var cp = {'codepage': c_oAscCodePageUtf8, 'encodings': getEncodingParams()};
              t.asc_fireCallback("asc_onAdvancedOptions", new asc.asc_CAdvancedOptions(c_oAscAdvancedOptionsID.TXT, cp), t.advancedOptionsAction);
              break;
            case "err":
              t.asc_fireCallback("asc_onError", g_fMapAscServerErrorToAscError(parseInt(input["data"])), c_oAscError.Level.Critical);
              break;
          }
1197
        }
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
          break;
        default:
          if (t.fCurCallback) {
            t.fCurCallback(input);
            t.fCurCallback = null;
          } else {
            t.asc_fireCallback("asc_onError", c_oAscError.ID.Unknown, c_oAscError.Level.NoCritical);
          }
          break;
      }
    }
  };
  //в обычном серверном режиме портим ссылку, потому что CoAuthoring теперь имеет встроенный адрес
  //todo надо использовать проверку get_OfflineApp, но она инициализируется только после loadDocument
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1212
  if (!(window["NATIVE_EDITOR_ENJINE"] || offlineMode === this.documentUrl)) {
1213 1214
    this.CoAuthoringApi.set_url(null);
  }
1215
  this.CoAuthoringApi.init(this.User, this.documentId, this.documentCallbackUrl, 'fghhfgsjdgfjs', c_oEditorId.Word, this.documentFormatSave);
1216
};
1217 1218 1219 1220

// server disconnect
asc_docs_api.prototype.asc_coAuthoringDisconnect = function () {
	this.CoAuthoringApi.disconnect();
1221
	this.isCoAuthoringEnable = false;
1222 1223 1224

	// Выставляем view-режим
	this.SetViewMode(true);
1225
};
1226

1227 1228 1229 1230
/////////////////////////////////////////////////////////////////////////
//////////////////////////SpellChecking api//////////////////////////////
/////////////////////////////////////////////////////////////////////////
// Init SpellCheck
1231
asc_docs_api.prototype._coSpellCheckInit = function() {
1232 1233 1234 1235
	if (!this.SpellCheckApi) {
		return; // Error
	}

1236 1237 1238
    if (!window["AscDesktopEditor"]) {
        if (this.SpellCheckUrl && this.isSpellCheckEnable)
            this.SpellCheckApi.set_url(this.SpellCheckUrl);
1239

Oleg.Korshul's avatar
Oleg.Korshul committed
1240 1241 1242 1243 1244
        this.SpellCheckApi.onSpellCheck	= function (e) {
            var incomeObject = JSON.parse(e);
            SpellCheck_CallBack(incomeObject);
        };
    }
1245

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1246
	this.SpellCheckApi.init(this.documentId);
1247
};
1248

1249 1250 1251
asc_docs_api.prototype.asc_getSpellCheckLanguages = function() {
	return g_spellCheckLanguages;
};
1252 1253 1254 1255
asc_docs_api.prototype.asc_SpellCheckDisconnect = function() {
	if (!this.SpellCheckApi)
		return; // Error
	this.SpellCheckApi.disconnect();
1256 1257 1258
	this.isSpellCheckEnable = false;
	if (this.WordControl.m_oLogicDocument)
		this.WordControl.m_oLogicDocument.TurnOff_CheckSpelling();
1259
};
1260

1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
asc_docs_api.prototype._onUpdateDocumentCanSave = function () {
	// Можно модифицировать это условие на более быстрое (менять самим состояние в аргументах, а не запрашивать каждый раз)
	var tmp = this.isDocumentModified() || (0 >= CollaborativeEditing.m_nUseType &&
		0 !== CollaborativeEditing.getOwnLocksLength());
	if (tmp !== this.isDocumentCanSave) {
		this.isDocumentCanSave = tmp;
		this.asc_fireCallback('asc_onDocumentCanSaveChanged', this.isDocumentCanSave);
	}
};

1271 1272 1273 1274
// Update user alive
asc_docs_api.prototype.setUserAlive = function () {
};

1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
// get functions
// Возвращает
//{
// ParaPr :
// {
//    ContextualSpacing : false,            // Удалять ли интервал между параграфами одинакового стиля
//
//    Ind :
//    {
//        Left      : 0,                    // Левый отступ
//        Right     : 0,                    // Правый отступ
//        FirstLine : 0                     // Первая строка
//    },
//
//    Jc : align_Left,                      // Прилегание параграфа
//
//    KeepLines : false,                    // переносить параграф на новую страницу,
//                                          // если на текущей он целиком не убирается
//    KeepNext  : false,                    // переносить параграф вместе со следующим параграфом
//
//    PageBreakBefore : false,              // начинать параграф с новой страницы
//
//    Spacing :
//    {
//        Line     : 1.15,                  // Расстояние между строками внутри абзаца
//        LineRule : linerule_Auto,         // Тип расстрояния между строками
//        Before   : 0,                     // Дополнительное расстояние до абзаца
//        After    : 10 * g_dKoef_pt_to_mm  // Дополнительное расстояние после абзаца
//    },
//
//    Shd :
//    {
//        Value : shd_Nil,
//        Color :
//        {
//            r : 255,
//            g : 255,
//            b : 255
//        }
//    },
//
//    WidowControl : true,                  // Запрет висячих строк
//
//    Tabs : []
// },
//
// TextPr :
// {
//    Bold       : false,
//    Italic     : false,
//    Underline  : false,
//    Strikeout  : false,
//    FontFamily :
//    {
//        Name  : "Times New Roman",
//        Index : -1
//    },
//    FontSize   : 12,
//    Color      :
//    {
//        r : 0,
//        g : 0,
//        b : 0
//    },
//    VertAlign : vertalign_Baseline,
//    HighLight : highlight_None
// }
//}

1344 1345 1346

asc_docs_api.prototype.put_FramePr = function(Obj)
{
1347 1348 1349
    if ( undefined != Obj.FontFamily )
    {
        var loader   = window.g_font_loader;
1350
        var fontinfo = g_fontApplication.GetFontInfo(Obj.FontFamily);
1351
        var isasync  = loader.LoadFont(fontinfo, editor.asyncFontEndLoaded_DropCap, Obj);
1352
        Obj.FontFamily = new asc_CTextFontFamily( { Name : fontinfo.Name, Index : -1 } );
1353 1354 1355 1356 1357

        if (false === isasync)
        {
            if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Properties) )
            {
1358
                this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetFramePrWithFontFamily);
1359 1360 1361 1362 1363 1364 1365 1366
                this.WordControl.m_oLogicDocument.Set_ParagraphFramePr( Obj );
            }
        }
    }
    else
    {
        if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Properties) )
        {
1367
            this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetFramePr);
1368 1369 1370
            this.WordControl.m_oLogicDocument.Set_ParagraphFramePr( Obj );
        }
    }
1371
};
1372

Oleg.Korshul's avatar
Oleg.Korshul committed
1373 1374 1375
asc_docs_api.prototype.asyncFontEndLoaded_MathDraw = function(Obj)
{
    this.sync_EndAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.LoadFont);
Oleg.Korshul's avatar
Oleg.Korshul committed
1376
    Obj.Generate2();
1377
};
Oleg.Korshul's avatar
Oleg.Korshul committed
1378 1379 1380
asc_docs_api.prototype.sendMathTypesToMenu = function(_math)
{
    this.asc_fireCallback("asc_onMathTypes", _math);
1381
};
Oleg.Korshul's avatar
Oleg.Korshul committed
1382

1383 1384 1385
asc_docs_api.prototype.asyncFontEndLoaded_DropCap = function(Obj)
{
    this.sync_EndAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.LoadFont);
1386 1387
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Properties) )
    {
1388
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetFramePrWithFontFamilyLong);
1389 1390
        this.WordControl.m_oLogicDocument.Set_ParagraphFramePr( Obj );
    }
1391
    // отжать заморозку меню
1392
};
1393

1394 1395 1396
asc_docs_api.prototype.asc_addDropCap = function(bInText)
{
    this.WordControl.m_oLogicDocument.Add_DropCap( bInText );
1397
};
1398

Ilya.Kirillov's avatar
Ilya.Kirillov committed
1399 1400 1401
asc_docs_api.prototype.removeDropcap = function(bDropCap)
{
    this.WordControl.m_oLogicDocument.Remove_DropCap( bDropCap );
1402
};
Ilya.Kirillov's avatar
Ilya.Kirillov committed
1403

1404 1405 1406 1407 1408 1409 1410
function CMathProp(obj)
{
    this.Type = c_oAscMathInterfaceType.Common;
    this.Pr   = null;

    if (obj)
    {
1411 1412
        this.Type = (undefined !== obj.Type ? obj.Type : this.Type);
        this.Pr   = (undefined !== obj.Pr   ? obj.Pr   : this.Pr);
1413 1414 1415
    }
}

1416
CMathProp.prototype.get_Type = function() {return this.Type;};
1417

1418 1419 1420 1421 1422 1423 1424

// Paragraph properties
function CParagraphPropEx (obj)
{
	if (obj)
	{
		this.ContextualSpacing = (undefined != obj.ContextualSpacing) ? obj.ContextualSpacing : null;
1425
		this.Ind = (undefined != obj.Ind && null != obj.Ind) ? new asc_CParagraphInd(obj.Ind) : null;
1426 1427 1428 1429
		this.Jc = (undefined != obj.Jc) ? obj.Jc : null;
		this.KeepLines = (undefined != obj.KeepLines) ? obj.KeepLines : null;
		this.KeepNext = (undefined != obj.KeepNext) ? obj.KeepNext : null;
		this.PageBreakBefore = (undefined != obj.PageBreakBefore) ? obj.PageBreakBefore : null;
1430 1431
		this.Spacing = (undefined != obj.Spacing && null != obj.Spacing) ? new asc_CParagraphSpacing(obj.Spacing) : null;
		this.Shd = (undefined != obj.Shd && null != obj.Shd) ? new asc_CParagraphShd(obj.Shd) : null;
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
		this.WidowControl = (undefined != obj.WidowControl) ? obj.WidowControl : null;                  // Запрет висячих строк
		this.Tabs = obj.Tabs;
	}
	else
	{
		//ContextualSpacing : false,            // Удалять ли интервал между параграфами одинакового стиля
		//
		//    Ind :
		//    {
		//        Left      : 0,                    // Левый отступ
		//        Right     : 0,                    // Правый отступ
		//        FirstLine : 0                     // Первая строка
		//    },
		//
		//    Jc : align_Left,                      // Прилегание параграфа
		//
		//    KeepLines : false,                    // переносить параграф на новую страницу,
		//                                          // если на текущей он целиком не убирается
		//    KeepNext  : false,                    // переносить параграф вместе со следующим параграфом
		//
		//    PageBreakBefore : false,              // начинать параграф с новой страницы
		this.ContextualSpacing = false;
1454
		this.Ind = new asc_CParagraphInd();
1455 1456 1457 1458
		this.Jc = align_Left;
		this.KeepLines = false;
		this.KeepNext = false;
		this.PageBreakBefore = false;
1459 1460
		this.Spacing = new asc_CParagraphSpacing();
		this.Shd = new asc_CParagraphShd();
1461 1462 1463 1464 1465 1466 1467
		this.WidowControl = true;                  // Запрет висячих строк
		this.Tabs = null;
	}
}
CParagraphPropEx.prototype.get_ContextualSpacing = function ()
{
	return this.ContextualSpacing;
1468
};
1469 1470 1471
CParagraphPropEx.prototype.get_Ind = function ()
{
	return this.Ind;
1472
};
1473 1474 1475
CParagraphPropEx.prototype.get_Jc = function ()
{
	return this.Jc;
1476
};
1477 1478 1479
CParagraphPropEx.prototype.get_KeepLines = function ()
{
	return this.KeepLines;
1480
};
1481 1482 1483
CParagraphPropEx.prototype.get_KeepNext = function ()
{
	return this.KeepNext;
1484
};
1485 1486 1487
CParagraphPropEx.prototype.get_PageBreakBefore = function ()
{
	return this.PageBreakBefore;
1488
};
1489 1490 1491
CParagraphPropEx.prototype.get_Spacing = function ()
{
	return this.Spacing;
1492
};
1493 1494 1495
CParagraphPropEx.prototype.get_Shd = function ()
{
	return this.Shd;
1496
};
1497 1498 1499
CParagraphPropEx.prototype.get_WidowControl = function ()
{
	return this.WidowControl;
1500
};
1501 1502 1503
CParagraphPropEx.prototype.get_Tabs = function ()
{
	return this.Tabs;
1504
};
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527

// Text properties
// TextPr :
// {
//    Bold       : false,
//    Italic     : false,
//    Underline  : false,
//    Strikeout  : false,
//    FontFamily :
//    {
//        Name  : "Times New Roman",
//        Index : -1
//    },
//    FontSize   : 12,
//    Color      :
//    {
//        r : 0,
//        g : 0,
//        b : 0
//    },
//    VertAlign : vertalign_Baseline,
//    HighLight : highlight_None
// }
1528

1529 1530 1531 1532 1533 1534 1535 1536 1537
// CTextProp
function CTextProp (obj)
{
	if (obj)
	{
		this.Bold       = (undefined != obj.Bold) ? obj.Bold : null;
		this.Italic     = (undefined != obj.Italic) ? obj.Italic : null;
		this.Underline  = (undefined != obj.Underline) ? obj.Underline : null;
		this.Strikeout  = (undefined != obj.Strikeout) ? obj.Strikeout : null;
1538
		this.FontFamily = (undefined != obj.FontFamily && null != obj.FontFamily) ? new asc_CTextFontFamily (obj.FontFamily) : null;
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
		this.FontSize   = (undefined != obj.FontSize) ? obj.FontSize : null;
		this.Color      = (undefined != obj.Color && null != obj.Color) ? CreateAscColorCustom(obj.Color.r, obj.Color.g, obj.Color.b) : null;
		this.VertAlign  = (undefined != obj.VertAlign) ? obj.VertAlign : null;
		this.HighLight  = (undefined != obj.HighLight) ? obj.HighLight == highlight_None ? obj.HighLight : new CColor (obj.HighLight.r, obj.HighLight.g, obj.HighLight.b) : null;
        this.DStrikeout = (undefined != obj.DStrikeout) ? obj.DStrikeout : null;
        this.Spacing    = (undefined != obj.Spacing)    ? obj.Spacing    : null;
        this.Caps       = (undefined != obj.Caps)       ? obj.Caps       : null;
        this.SmallCaps  = (undefined != obj.SmallCaps)  ? obj.SmallCaps  : null;
	}
	else
	{
		//    Bold       : false,
		//    Italic     : false,
		//    Underline  : false,
		//    Strikeout  : false,
		//    FontFamily :
		//    {
		//        Name  : "Times New Roman",
		//        Index : -1
		//    },
		//    FontSize   : 12,
		//    Color      :
		//    {
		//        r : 0,
		//        g : 0,
		//        b : 0
		//    },
		//    VertAlign : vertalign_Baseline,
		//    HighLight : highlight_None
		this.Bold       = false;
		this.Italic     = false;
		this.Underline  = false;
		this.Strikeout  = false;
1572
		this.FontFamily = new asc_CTextFontFamily();
1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
		this.FontSize   = 12;
		this.Color      = CreateAscColorCustom(0, 0, 0);
		this.VertAlign  = vertalign_Baseline;
		this.HighLight  = highlight_None;
        this.DStrikeout = false;
        this.Spacing    = 0;
        this.Caps       = false;
        this.SmallCaps  = false;
    }
}
CTextProp.prototype.get_Bold = function ()
{
	return this.Bold;
1586
};
1587 1588 1589
CTextProp.prototype.get_Italic = function ()
{
	return this.Italic;
1590
};
1591 1592 1593
CTextProp.prototype.get_Underline = function ()
{
	return this.Underline;
1594
};
1595 1596 1597
CTextProp.prototype.get_Strikeout = function ()
{
	return this.Strikeout;
1598
};
1599 1600 1601
CTextProp.prototype.get_FontFamily = function ()
{
	return this.FontFamily;
1602
};
1603 1604 1605
CTextProp.prototype.get_FontSize = function ()
{
	return this.FontSize;
1606
};
1607 1608 1609
CTextProp.prototype.get_Color = function ()
{
	return this.Color;
1610
};
1611 1612 1613
CTextProp.prototype.get_VertAlign = function ()
{
	return this.VertAlign;
1614
};
1615 1616 1617
CTextProp.prototype.get_HighLight = function ()
{
	return this.HighLight;
1618
};
1619 1620 1621 1622

CTextProp.prototype.get_Spacing = function ()
{
    return this.Spacing;
1623
};
1624 1625 1626 1627

CTextProp.prototype.get_DStrikeout = function ()
{
    return this.DStrikeout;
1628
};
1629 1630 1631 1632

CTextProp.prototype.get_Caps = function ()
{
    return this.Caps;
1633
};
1634 1635 1636 1637

CTextProp.prototype.get_SmallCaps = function ()
{
    return this.SmallCaps;
1638
};
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649


// paragraph and text properties objects container
function CParagraphAndTextProp (paragraphProp, textProp)
{
	this.ParaPr = (undefined != paragraphProp && null != paragraphProp) ? new CParagraphPropEx (paragraphProp) : null;
	this.TextPr = (undefined != textProp && null != textProp) ? new CTextProp (textProp) : null;
}
CParagraphAndTextProp.prototype.get_ParaPr = function ()
{
	return this.ParaPr;
1650
};
1651 1652 1653
CParagraphAndTextProp.prototype.get_TextPr = function ()
{
	return this.TextPr;
1654
};
1655 1656 1657 1658 1659 1660 1661 1662 1663 1664

//
asc_docs_api.prototype.get_TextProps = function()
{
	var Doc = this.WordControl.m_oLogicDocument;
	var ParaPr = Doc.Get_Paragraph_ParaPr();
	var TextPr = Doc.Get_Paragraph_TextPr();

	// return { ParaPr: ParaPr, TextPr : TextPr };
	return new CParagraphAndTextProp (ParaPr, TextPr);	// uncomment if this method will be used externally. 20/03/2012 uncommented for testers
1665
};
1666 1667 1668 1669 1670

// -------
asc_docs_api.prototype.GetJSONLogicDocument = function()
{
	return JSON.stringify(this.WordControl.m_oLogicDocument);
1671
};
1672 1673 1674 1675

asc_docs_api.prototype.get_ContentCount = function()
{
	return this.WordControl.m_oLogicDocument.Content.length;
1676
};
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699

asc_docs_api.prototype.select_Element = function(Index)
{
	var Document = this.WordControl.m_oLogicDocument;

	if ( true === Document.Selection.Use )
		Document.Selection_Remove();

	Document.DrawingDocument.SelectEnabled(true);
	Document.DrawingDocument.TargetEnd();

	Document.Selection.Use      = true;
	Document.Selection.Start    = false;
	Document.Selection.Flag     = selectionflag_Common;

	Document.Selection.StartPos = Index;
	Document.Selection.EndPos   = Index;

	Document.Content[Index].Selection.Use      = true;
	Document.Content[Index].Selection.StartPos = Document.Content[Index].Internal_GetStartPos();
	Document.Content[Index].Selection.EndPos   = Document.Content[Index].Content.length - 1;

	Document.Selection_Draw();
1700
};
1701 1702 1703 1704 1705

asc_docs_api.prototype.UpdateTextPr = function(TextPr)
{
	if ( "undefined" != typeof(TextPr) )
	{
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
        this.sync_BoldCallBack(TextPr.Bold);
        this.sync_ItalicCallBack(TextPr.Italic);
        this.sync_UnderlineCallBack(TextPr.Underline);
        this.sync_StrikeoutCallBack(TextPr.Strikeout);
        this.sync_TextPrFontSizeCallBack(TextPr.FontSize);
        this.sync_TextPrFontFamilyCallBack(TextPr.FontFamily);
        this.sync_VerticalAlign(TextPr.VertAlign);
        this.sync_TextHighLight(TextPr.HighLight);
        this.sync_TextSpacing(TextPr.Spacing);
        this.sync_TextDStrikeout(TextPr.DStrikeout);
        this.sync_TextCaps(TextPr.Caps);
        this.sync_TextSmallCaps(TextPr.SmallCaps);
        this.sync_TextPosition(TextPr.Position);
        this.sync_TextLangCallBack(TextPr.Lang);
1720
        this.sync_TextColor(TextPr);
1721
	}
1722
};
1723 1724 1725 1726 1727 1728 1729 1730 1731
asc_docs_api.prototype.UpdateParagraphProp = function(ParaPr)
{
    //if ( true === CollaborativeEditing.Get_GlobalLock() )
    //{
    //    ParaPr.Locked      = true;
    //    ParaPr.CanAddTable = false;
    //}

	// var prgrhPr = this.get_TextProps();
1732
	// var prProp = {};
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
	// prProp.Ind = prgrhPr.ParaPr.Ind;
	// prProp.ContextualSpacing = prgrhPr.ParaPr.ContextualSpacing;
	// prProp.Spacing = prgrhPr.ParaPr.Spacing;
	// prProp.PageBreakBefore = prgrhPr.ParaPr.PageBreakBefore;
	// prProp.KeepLines = prgrhPr.ParaPr.KeepLines;

	// {
	//    ContextualSpacing : false,            // Удалять ли интервал между параграфами одинакового стиля
	//
	//    Ind :
	//    {
	//        Left      : 0,                    // Левый отступ
	//        Right     : 0,                    // Правый отступ
	//        FirstLine : 0                     // Первая строка
	//    },
	//    Jc : align_Left,                      // Прилегание параграфа
	//    KeepLines : false,                    // переносить параграф на новую страницу,
	//                                          // если на текущей он целиком не убирается
	//    PageBreakBefore : false,              // начинать параграф с новой страницы
	//
	//    Spacing :
	//    {
	//        Line     : 1.15,                  // Расстояние между строками внутри абзаца
	//        LineRule : linerule_Auto,         // Тип расстрояния между строками
	//        Before   : 0,                     // Дополнительное расстояние до абзаца
	//        After    : 10 * g_dKoef_pt_to_mm  // Дополнительное расстояние после абзаца
	//    }
	//	}

    // TODO: как только разъединят настройки параграфа и текста переделать тут
    var TextPr = editor.WordControl.m_oLogicDocument.Get_Paragraph_TextPr();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1764 1765
    ParaPr.Subscript   = TextPr.VertAlign === vertalign_SubScript;
    ParaPr.Superscript = TextPr.VertAlign === vertalign_SuperScript;
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
    ParaPr.Strikeout   = TextPr.Strikeout;
    ParaPr.DStrikeout  = TextPr.DStrikeout;
    ParaPr.AllCaps     = TextPr.Caps;
    ParaPr.SmallCaps   = TextPr.SmallCaps;
    ParaPr.TextSpacing = TextPr.Spacing;
    ParaPr.Position    = TextPr.Position;
    //-----------------------------------------------------------------------------

    if ( true === ParaPr.Spacing.AfterAutoSpacing )
        ParaPr.Spacing.After = spacing_Auto;
    else if ( undefined === ParaPr.Spacing.AfterAutoSpacing )
        ParaPr.Spacing.After = UnknownValue;

    if ( true === ParaPr.Spacing.BeforeAutoSpacing )
        ParaPr.Spacing.Before = spacing_Auto;
    else if ( undefined === ParaPr.Spacing.BeforeAutoSpacing )
        ParaPr.Spacing.Before = UnknownValue;

    if ( -1 === ParaPr.PStyle )
        ParaPr.StyleName = "";
1786
    else if ( undefined === ParaPr.PStyle || undefined === this.WordControl.m_oLogicDocument.Styles.Style[ParaPr.PStyle] )
1787 1788 1789 1790
        ParaPr.StyleName = this.WordControl.m_oLogicDocument.Styles.Style[this.WordControl.m_oLogicDocument.Styles.Get_Default_Paragraph()].Name;
    else
        ParaPr.StyleName = this.WordControl.m_oLogicDocument.Styles.Style[ParaPr.PStyle].Name;

1791 1792 1793
    var NumType    = -1;
    var NumSubType = -1;
    if ( !(null == ParaPr.NumPr || 0 === ParaPr.NumPr.NumId || "0" === ParaPr.NumPr.NumId) )
1794
    {
1795 1796 1797
        var Numb = this.WordControl.m_oLogicDocument.Numbering.Get_AbstractNum( ParaPr.NumPr.NumId );
        
        if ( undefined !== Numb && undefined !== Numb.Lvl[ParaPr.NumPr.Lvl] )
1798
        {
1799 1800 1801 1802 1803
            var Lvl = Numb.Lvl[ParaPr.NumPr.Lvl];
            var NumFormat = Lvl.Format;
            var NumText   = Lvl.LvlText;
            
            if ( numbering_numfmt_Bullet === NumFormat )
1804
            {
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
                NumType    = 0;
                NumSubType = 0;
                
                var TextLen = NumText.length;
                if ( 1 === TextLen && numbering_lvltext_Text === NumText[0].Type )
                {
                    var NumVal = NumText[0].Value.charCodeAt(0);

                    if ( 0x00B7 === NumVal )
                        NumSubType = 1;
                    else if ( 0x006F === NumVal )
                        NumSubType = 2;
                    else if ( 0x00A7 === NumVal )
                        NumSubType = 3;
                    else if ( 0x0076 === NumVal )
                        NumSubType = 4;
                    else if ( 0x00D8 === NumVal )
                        NumSubType = 5;
                    else if ( 0x00FC === NumVal )
                        NumSubType = 6;
                    else if ( 0x00A8 === NumVal )
                        NumSubType = 7;
                }
1828
            }
1829
            else
1830
            {
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
                NumType    = 1;
                NumSubType = 0;
                
                var TextLen = NumText.length;
                if ( 2 === TextLen && numbering_lvltext_Num === NumText[0].Type && numbering_lvltext_Text === NumText[1].Type )
                {
                    var NumVal2 = NumText[1].Value;
                    
                    if ( numbering_numfmt_Decimal === NumFormat )
                    {
                        if ( "." === NumVal2 )
                            NumSubType = 1;
                        else if ( ")" === NumVal2 )
                            NumSubType = 2;                        
                    }
                    else if ( numbering_numfmt_UpperRoman === NumFormat )
                    {
                        if ( "." === NumVal2 )
                            NumSubType = 3;
                    }
                    else if ( numbering_numfmt_UpperLetter === NumFormat )
                    {
                        if ( "." === NumVal2 )
                            NumSubType = 4;
                    }
                    else if ( numbering_numfmt_LowerLetter === NumFormat )
                    {
                        if ( ")" === NumVal2 )
                            NumSubType = 5;
                        else if ( "." === NumVal2 )
                            NumSubType = 6;
                    }
                    else if ( numbering_numfmt_LowerRoman === NumFormat )
                    {
                        if ( "." === NumVal2 )
                            NumSubType = 7;
                    }
                }
1869 1870 1871
            }
        }
    }
1872 1873

    ParaPr.ListType = { Type : NumType, SubType : NumSubType };
1874 1875 1876 1877 1878 1879 1880 1881
    
    if ( undefined !== ParaPr.FramePr && undefined !== ParaPr.FramePr.Wrap )
    {
        if ( wrap_NotBeside === ParaPr.FramePr.Wrap )
            ParaPr.FramePr.Wrap = false;
        else if ( wrap_Around === ParaPr.FramePr.Wrap )
            ParaPr.FramePr.Wrap = true;
        else
1882
            ParaPr.FramePr.Wrap = undefined;
1883
    }
1884 1885 1886 1887 1888 1889 1890

	this.sync_ParaSpacingLine( ParaPr.Spacing );
	this.Update_ParaInd(ParaPr.Ind);
	this.sync_PrAlignCallBack(ParaPr.Jc);
	this.sync_ParaStyleName(ParaPr.StyleName);
	this.sync_ListType(ParaPr.ListType);
	this.sync_PrPropCallback(ParaPr);
1891
};
1892 1893 1894 1895

/*----------------------------------------------------------------*/
/*functions for working with clipboard, document*/
/*TODO: Print,Undo,Redo,Copy,Cut,Paste,Share,Save,DownloadAs,ReturnToDocuments(вернуться на предыдущую страницу) & callbacks for these functions*/
1896
asc_docs_api.prototype.asc_Print = function(bIsDownloadEvent)
1897
{
Oleg.Korshul's avatar
Oleg.Korshul committed
1898 1899
    if (window["AscDesktopEditor"])
    {
Oleg.Korshul's avatar
Oleg.Korshul committed
1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
        if (null != this.WordControl.m_oDrawingDocument.m_oDocumentRenderer)
        {
            if (window["AscDesktopEditor"]["IsSupportNativePrint"](this.DocumentUrl) === true)
                return;
        }
        else
        {
            window["AscDesktopEditor"]["Print"]();
            return;
        }
Oleg.Korshul's avatar
Oleg.Korshul committed
1910
    }
1911 1912 1913 1914 1915 1916 1917
  var command;
  var options = {isNoData: false, downloadType: bIsDownloadEvent ? 'asc_onPrintUrl' : null};
  if (null == this.WordControl.m_oLogicDocument) {
    command = 'savefromorigin';
    options.isNoData = true;
  } else {
    command = 'save';
1918
  }
1919
  _downloadAs(this, command, c_oAscFileType.PDF, c_oAscAsyncAction.Print, options, null);
1920
};
1921 1922 1923
asc_docs_api.prototype.Undo = function()
{
	this.WordControl.m_oLogicDocument.Document_Undo();
1924
};
1925 1926 1927
asc_docs_api.prototype.Redo = function()
{
	this.WordControl.m_oLogicDocument.Document_Redo();
1928
};
1929 1930
asc_docs_api.prototype.Copy = function()
{
1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
    if (window["AscDesktopEditor"])
    {
        window["AscDesktopEditorButtonMode"] = true;

        var _e = new CKeyboardEvent();
        _e.CtrlKey = true;
        _e.KeyCode = 67;

        this.WordControl.m_oLogicDocument.OnKeyDown(_e);

        window["AscDesktopEditorButtonMode"] = false;

        return;
    }
1945
	return Editor_Copy_Button(this);
1946
};
1947 1948
asc_docs_api.prototype.Update_ParaTab = function(Default_Tab, ParaTabs){
    this.WordControl.m_oDrawingDocument.Update_ParaTab(Default_Tab, ParaTabs);
1949
};
1950 1951
asc_docs_api.prototype.Cut = function()
{
1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965
    if (window["AscDesktopEditor"])
    {
        window["AscDesktopEditorButtonMode"] = true;

        var _e = new CKeyboardEvent();
        _e.CtrlKey = true;
        _e.KeyCode = 88;

        this.WordControl.m_oLogicDocument.OnKeyDown(_e);

        window["AscDesktopEditorButtonMode"] = false;

        return;
    }
1966
	return Editor_Copy_Button(this, true);
1967
};
1968 1969
asc_docs_api.prototype.Paste = function()
{
1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
    if (window["AscDesktopEditor"])
    {
        window["AscDesktopEditorButtonMode"] = true;

        var _e = new CKeyboardEvent();
        _e.CtrlKey = true;
        _e.KeyCode = 86;

        this.WordControl.m_oLogicDocument.OnKeyDown(_e);

        window["AscDesktopEditorButtonMode"] = false;

        return;
    }

1985
    if (false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content))
Oleg.Korshul's avatar
Oleg.Korshul committed
1986
    {
1987
        if (!window.GlobalPasteFlag)
Oleg.Korshul's avatar
Oleg.Korshul committed
1988
        {
1989
            if (!window.USER_AGENT_SAFARI_MACOS)
Oleg.Korshul's avatar
Oleg.Korshul committed
1990 1991 1992 1993
            {
                window.GlobalPasteFlag = true;
                return Editor_Paste_Button(this);
            }
1994 1995 1996 1997 1998 1999 2000 2001 2002
            else
            {
                if (0 === window.GlobalPasteFlagCounter)
                {
                    SafariIntervalFocus();
                    window.GlobalPasteFlag = true;
                    return Editor_Paste_Button(this);
                }
            }
Oleg.Korshul's avatar
Oleg.Korshul committed
2003 2004
        }
    }
2005
};
2006 2007
asc_docs_api.prototype.Share = function(){

2008
};
2009

2010
function OnSave_Callback(e) {
2011 2012 2013 2014 2015 2016
  if (false == e["saveLock"]) {
    if (editor.asc_IsLongAction()) {
      // Мы не можем в этот момент сохранять, т.к. попали в ситуацию, когда мы залочили сохранение и успели нажать вставку до ответа
      // Нужно снять lock с сохранения
      editor.CoAuthoringApi.onUnSaveLock = function() {
        editor.canSave = true;
2017
        editor.IsUserSave = false;
2018 2019 2020 2021 2022
      };
      editor.CoAuthoringApi.unSaveLock();
      return;
    }
    editor.sync_StartAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.Save);
2023

2024 2025 2026
    if (c_oAscCollaborativeMarksShowType.LastChanges === editor.CollaborativeMarksShowType) {
      CollaborativeEditing.Clear_CollaborativeMarks();
    }
2027

2028 2029 2030
    // Принимаем чужие изменения
    var HaveOtherChanges = CollaborativeEditing.Have_OtherChanges();
    CollaborativeEditing.Apply_Changes();
2031

2032 2033
    editor.CoAuthoringApi.onUnSaveLock = function() {
      editor.CoAuthoringApi.onUnSaveLock = null;
2034

2035 2036 2037
      // Выставляем, что документ не модифицирован
      editor.CheckChangedDocument();
      editor.canSave = true;
2038
      editor.IsUserSave = false;
2039
      editor.sync_EndAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.Save);
2040

2041 2042
      // Обновляем состояние возможности сохранения документа
      editor._onUpdateDocumentCanSave();
2043

2044 2045 2046 2047
      if (undefined !== window["AscDesktopEditor"]) {
        window["AscDesktopEditor"]["OnSave"]();
      }
    };
2048

2049 2050 2051 2052
    var CursorInfo = null;
    if (true === CollaborativeEditing.Is_Fast()) {
      CursorInfo = History.Get_DocumentPositionBinary();
    }
2053

2054 2055 2056 2057 2058 2059 2060
    // Пересылаем свои изменения
    CollaborativeEditing.Send_Changes(editor.IsUserSave, {UserId: editor.CoAuthoringApi.getUserConnectionId(), CursorInfo: CursorInfo}, HaveOtherChanges);
  } else {
    var nState = editor.CoAuthoringApi.get_state();
    if (ConnectionState.Close === nState) {
      // Отключаемся от сохранения, соединение потеряно
      editor.canSave = true;
2061
      editor.IsUserSave = false;
2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076
    } else {
      var TimeoutInterval = (true === CollaborativeEditing.Is_Fast() ? 1 : 1000);
      setTimeout(function() {
        editor.CoAuthoringApi.askSaveChanges(OnSave_Callback);
      }, TimeoutInterval);
    }
  }
}

asc_docs_api.prototype.asc_Save = function(isAutoSave) {
  this.IsUserSave = !isAutoSave;
  if (true === this.canSave && !this.asc_IsLongAction()) {
    this.canSave = false;
    this.CoAuthoringApi.askSaveChanges(OnSave_Callback);
  }
2077
};
Oleg.Korshul's avatar
Oleg.Korshul committed
2078

2079
asc_docs_api.prototype.asc_DownloadAs = function(typeFile, bIsDownloadEvent) {//передаем число соответствующее своему формату.
2080
	var actionType = this.mailMergeFileData ? c_oAscAsyncAction.MailMergeLoadFile : c_oAscAsyncAction.DownloadAs;
2081 2082
    var options = {downloadType: bIsDownloadEvent ? 'asc_onDownloadUrl' : null};
	_downloadAs(this, "save", typeFile, actionType, options, null);
2083
};
2084 2085 2086 2087
asc_docs_api.prototype.Resize = function(){
	if (false === this.bInit_word_control)
		return;
	this.WordControl.OnResize(false);
2088
};
2089 2090
asc_docs_api.prototype.AddURL = function(url){

2091
};
2092 2093
asc_docs_api.prototype.Help = function(){

Sergey.Konovalov's avatar
Sergey.Konovalov committed
2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
};
/*
 idOption идентификатор дополнительного параметра, c_oAscAdvancedOptionsID.TXT.
 option - какие свойства применить, пока массив. для TXT объект asc_CTXTAdvancedOptions(codepage)
 exp:	asc_setAdvancedOptions(c_oAscAdvancedOptionsID.TXT, new Asc.asc_CCSVAdvancedOptions(1200) );
 */
asc_docs_api.prototype.asc_setAdvancedOptions = function(idOption, option) {
  var t = this;
  switch (idOption) {
    case c_oAscAdvancedOptionsID.TXT:
      // Проверяем тип состояния в данный момент
      if (this.advancedOptionsAction === c_oAscAdvancedOptionsAction.Open) {
          var rData = {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2107
            "id":this.documentId,
2108
            "userid": this.documentUserId,
2109
            "format": this.documentFormat,
2110
            "vkey": this.documentVKey,
Sergey.Konovalov's avatar
Sergey.Konovalov committed
2111 2112
            "editorid": c_oEditorId.Word,
            "c":"reopen",
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2113
            "url": this.documentUrl,
2114
            "title": this.documentTitle,
Sergey.Konovalov's avatar
Sergey.Konovalov committed
2115 2116 2117 2118 2119
            "codepage": option.asc_getCodePage(),
            "embeddedfonts": t.isUseEmbeddedCutFonts
          };
          sendCommand2(t, null, rData);
      } else if (this.advancedOptionsAction === c_oAscAdvancedOptionsAction.Save) {
2120 2121
          var options = {txtOptions: option};
          _downloadAs(t, "save", c_oAscFileType.TXT, c_oAscAsyncAction.DownloadAs, options, null);
Sergey.Konovalov's avatar
Sergey.Konovalov committed
2122 2123 2124
      }
      break;
  }
2125
};
2126 2127
asc_docs_api.prototype.SetFontRenderingMode = function(mode)
{
2128
    if (c_oAscFontRenderingModeType.noHinting === mode)
2129
        SetHintsProps(false, false);
2130
    else if (c_oAscFontRenderingModeType.hinting === mode)
2131
        SetHintsProps(true, false);
2132
    else if (c_oAscFontRenderingModeType.hintingAndSubpixeling === mode)
2133 2134 2135 2136 2137
        SetHintsProps(true, true);

    this.WordControl.m_oDrawingDocument.ClearCachePages();
    g_fontManager.ClearFontsRasterCache();

Oleg.Korshul's avatar
Oleg.Korshul committed
2138 2139 2140
    if (window.g_fontManager2 !== undefined && window.g_fontManager2 !== null)
        window.g_fontManager2.ClearFontsRasterCache();

2141 2142
    if (this.bInit_word_control)
        this.WordControl.OnScroll();
2143
};
2144
asc_docs_api.prototype.processSavedFile = function(url, downloadType) {
2145
	var t = this;
2146 2147
	if (this.mailMergeFileData) {
		this.mailMergeFileData = null;
2148 2149 2150 2151
		asc_ajax({
			url: url,
			dataType: "text",
			success: function (result) {
2152 2153 2154 2155 2156
				try {
					t.asc_StartMailMergeByList(JSON.parse(result));
				} catch (e) {
					t.asc_fireCallback("asc_onError", c_oAscError.ID.MailMergeLoadFile, c_oAscError.Level.NoCritical);
				}
2157 2158
			},
			error: function () {
2159
				t.asc_fireCallback("asc_onError", c_oAscError.ID.MailMergeLoadFile, c_oAscError.Level.NoCritical);
2160 2161 2162
			}
		});
	} else {
2163 2164
		if (downloadType) {
			this.asc_fireCallback(downloadType, url, function (hasError) {
2165 2166 2167 2168
			});
		} else {
			getFile(url);
		}
2169
	}
2170
};
2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198
asc_docs_api.prototype.startGetDocInfo = function(){
	/*
	Возвращаем объект следующего вида:
	{
		PageCount: 12,
		WordsCount: 2321,
		ParagraphCount: 45,
		SymbolsCount: 232345,
		SymbolsWSCount: 34356
	}
	*/
	this.sync_GetDocInfoStartCallback();

    if (null != this.WordControl.m_oDrawingDocument.m_oDocumentRenderer)
    {
        var _render = this.WordControl.m_oDrawingDocument.m_oDocumentRenderer;

        var obj = { PageCount: _render.PagesCount, WordsCount: _render.CountWords, ParagraphCount: _render.CountParagraphs,
                        SymbolsCount: _render.CountSymbols, SymbolsWSCount: (_render.CountSymbols + _render.CountSpaces) };

        this.asc_fireCallback( "asc_onDocInfo", new CDocInfoProp(obj));

        this.sync_GetDocInfoEndCallback();
    }
    else
    {
        this.WordControl.m_oLogicDocument.Statistics_Start();
    }
2199
};
2200 2201 2202 2203 2204
asc_docs_api.prototype.stopGetDocInfo = function(){
    this.sync_GetDocInfoStopCallback();

    if (null != this.WordControl.m_oLogicDocument)
        this.WordControl.m_oLogicDocument.Statistics_Stop();
2205
};
2206 2207
asc_docs_api.prototype.sync_DocInfoCallback = function(obj){
	this.asc_fireCallback( "asc_onDocInfo", new CDocInfoProp(obj));
2208
};
2209 2210
asc_docs_api.prototype.sync_GetDocInfoStartCallback = function(){
	this.asc_fireCallback("asc_onGetDocInfoStart");
2211
};
2212 2213
asc_docs_api.prototype.sync_GetDocInfoStopCallback = function(){
	this.asc_fireCallback("asc_onGetDocInfoStop");
2214
};
2215 2216
asc_docs_api.prototype.sync_GetDocInfoEndCallback = function(){
	this.asc_fireCallback("asc_onGetDocInfoEnd");
2217
};
2218 2219 2220 2221 2222 2223
asc_docs_api.prototype.sync_CanUndoCallback = function(bCanUndo)
{
    //if ( true === CollaborativeEditing.Get_GlobalLock() )
    //    this.asc_fireCallback("asc_onCanUndo", false);
    //else
        this.asc_fireCallback("asc_onCanUndo", bCanUndo);
2224
};
2225 2226 2227 2228 2229 2230
asc_docs_api.prototype.sync_CanRedoCallback = function(bCanRedo)
{
    //if ( true === CollaborativeEditing.Get_GlobalLock() )
    //    this.asc_fireCallback("asc_onCanRedo", false);
    //else
        this.asc_fireCallback("asc_onCanRedo", bCanRedo);
2231
};
2232

2233 2234 2235 2236 2237
asc_docs_api.prototype.can_CopyCut = function()
{
    return this.WordControl.m_oLogicDocument.Can_CopyCut();
};

2238 2239 2240
asc_docs_api.prototype.sync_CanCopyCutCallback = function(bCanCopyCut)
{
    this.asc_fireCallback("asc_onCanCopyCut", bCanCopyCut);
2241
};
2242

2243
asc_docs_api.prototype.setStartPointHistory = function(){
2244 2245
    this.noCreatePoint = true;
    this.exucuteHistory = true;
2246 2247
    this.asc_IncrementCounterLongAction();
    this.WordControl.m_oLogicDocument.TurnOff_InterfaceEvents();
2248 2249 2250
};
asc_docs_api.prototype.setEndPointHistory   = function(){
    this.noCreatePoint = false;
2251
    this.exucuteHistoryEnd = true;
2252 2253
    this.asc_DecrementCounterLongAction();
    this.WordControl.m_oLogicDocument.TurnOn_InterfaceEvents();
2254
};
2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272

function CDocInfoProp(obj)
{
	if(obj){
		this.PageCount = obj.PageCount;
		this.WordsCount = obj.WordsCount;
		this.ParagraphCount = obj.ParagraphCount;
		this.SymbolsCount = obj.SymbolsCount;
		this.SymbolsWSCount = obj.SymbolsWSCount;
	}
	else {
		this.PageCount = -1;
		this.WordsCount = -1;
		this.ParagraphCount = -1;
		this.SymbolsCount = -1;
		this.SymbolsWSCount = -1;
	}
}
2273 2274 2275 2276 2277 2278 2279 2280 2281 2282
CDocInfoProp.prototype.get_PageCount = function(){ return this.PageCount; };
CDocInfoProp.prototype.put_PageCount = function(v){ this.PageCount = v; };
CDocInfoProp.prototype.get_WordsCount = function(){ return this.WordsCount; };
CDocInfoProp.prototype.put_WordsCount = function(v){ this.WordsCount = v; };
CDocInfoProp.prototype.get_ParagraphCount = function(){ return this.ParagraphCount; };
CDocInfoProp.prototype.put_ParagraphCount = function(v){ this.ParagraphCount = v; };
CDocInfoProp.prototype.get_SymbolsCount = function(){ return this.SymbolsCount; };
CDocInfoProp.prototype.put_SymbolsCount = function(v){ this.SymbolsCount = v; };
CDocInfoProp.prototype.get_SymbolsWSCount = function(){ return this.SymbolsWSCount; };
CDocInfoProp.prototype.put_SymbolsWSCount = function(v){ this.SymbolsWSCount = v; };
2283 2284 2285 2286 2287 2288 2289

/*callbacks*/
/*asc_docs_api.prototype.sync_CursorLockCallBack = function(isLock){
	this.asc_fireCallback("asc_onCursorLock",isLock);
}*/
asc_docs_api.prototype.sync_PrintCallBack = function(){
	this.asc_fireCallback("asc_onPrint");
2290
};
2291 2292
asc_docs_api.prototype.sync_UndoCallBack = function(){
	this.asc_fireCallback("asc_onUndo");
2293
};
2294 2295
asc_docs_api.prototype.sync_RedoCallBack = function(){
	this.asc_fireCallback("asc_onRedo");
2296
};
2297 2298
asc_docs_api.prototype.sync_CopyCallBack = function(){
	this.asc_fireCallback("asc_onCopy");
2299
};
2300 2301
asc_docs_api.prototype.sync_CutCallBack = function(){
	this.asc_fireCallback("asc_onCut");
2302
};
2303 2304
asc_docs_api.prototype.sync_PasteCallBack = function(){
	this.asc_fireCallback("asc_onPaste");
2305
};
2306 2307
asc_docs_api.prototype.sync_ShareCallBack = function(){
	this.asc_fireCallback("asc_onShare");
2308
};
2309 2310
asc_docs_api.prototype.sync_SaveCallBack = function(){
	this.asc_fireCallback("asc_onSave");
2311
};
2312 2313
asc_docs_api.prototype.sync_DownloadAsCallBack = function(){
	this.asc_fireCallback("asc_onDownload");
2314
};
2315 2316 2317
asc_docs_api.prototype.sync_StartAction = function(type, id){
	//this.AsyncAction
	this.asc_fireCallback("asc_onStartAction", type, id);
2318
	//console.log("asc_onStartAction: type = " + type + " id = " + id);
2319 2320

    if (c_oAscAsyncActionType.BlockInteraction == type)
Oleg.Korshul's avatar
Oleg.Korshul committed
2321
        this.asc_IncrementCounterLongAction();
2322
};
2323 2324 2325
asc_docs_api.prototype.sync_EndAction = function(type, id){
	//this.AsyncAction
	this.asc_fireCallback("asc_onEndAction", type, id);
2326
	//console.log("asc_onEndAction: type = " + type + " id = " + id);
2327 2328

    if (c_oAscAsyncActionType.BlockInteraction == type)
Oleg.Korshul's avatar
Oleg.Korshul committed
2329
    {
2330
        this.asc_DecrementCounterLongAction();
Oleg.Korshul's avatar
Oleg.Korshul committed
2331
    }
2332
};
Oleg.Korshul's avatar
Oleg.Korshul committed
2333

2334 2335 2336 2337 2338 2339 2340 2341 2342
asc_docs_api.prototype.asc_IncrementCounterLongAction = function()
{
    this.IsLongActionCurrent++;
};
asc_docs_api.prototype.asc_DecrementCounterLongAction = function()
{
    this.IsLongActionCurrent--;
    if (this.IsLongActionCurrent < 0)
        this.IsLongActionCurrent = 0;
2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353

    if (!this.asc_IsLongAction())
    {
        var _length = this.LongActionCallbacks.length;
        for (var i = 0; i < _length; i++)
        {
            this.LongActionCallbacks[i](this.LongActionCallbacksParams[i]);
        }
        this.LongActionCallbacks.splice(0, _length);
        this.LongActionCallbacksParams.splice(0, _length);
    }
2354 2355
};

Oleg.Korshul's avatar
Oleg.Korshul committed
2356 2357 2358 2359
asc_docs_api.prototype.asc_IsLongAction = function()
{
    return (0 == this.IsLongActionCurrent) ? false : true;
};
Oleg.Korshul's avatar
 
Oleg.Korshul committed
2360
asc_docs_api.prototype.asc_CheckLongActionCallback = function(_callback, _param)
Oleg.Korshul's avatar
Oleg.Korshul committed
2361 2362 2363 2364
{
    if (this.asc_IsLongAction())
    {
        this.LongActionCallbacks[this.LongActionCallbacks.length] = _callback;
Oleg.Korshul's avatar
 
Oleg.Korshul committed
2365
        this.LongActionCallbacksParams[this.LongActionCallbacksParams.length] = _param;
Oleg.Korshul's avatar
Oleg.Korshul committed
2366 2367 2368 2369 2370 2371 2372 2373
        return false;
    }
    else
    {
        return true;
    }
};

2374 2375
asc_docs_api.prototype.sync_AddURLCallback = function(){
	this.asc_fireCallback("asc_onAddURL");
2376
};
2377 2378
asc_docs_api.prototype.sync_ErrorCallback = function(errorID,errorLevel){
	this.asc_fireCallback("asc_onError",errorID,errorLevel);
2379
};
2380 2381
asc_docs_api.prototype.sync_HelpCallback = function(url){
	this.asc_fireCallback("asc_onHelp",url);
2382
};
2383 2384
asc_docs_api.prototype.sync_UpdateZoom = function(zoom){
	this.asc_fireCallback("asc_onZoom", zoom);
2385
};
2386 2387
asc_docs_api.prototype.sync_StatusMessage = function(message){
	this.asc_fireCallback("asc_onMessage", message);
2388
};
2389 2390
asc_docs_api.prototype.ClearPropObjCallback = function(prop){//колбэк предшествующий приходу свойств объекта, prop а всякий случай
	this.asc_fireCallback("asc_onClearPropObj", prop);
2391
};
2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428

/*----------------------------------------------------------------*/
/*functions for working with headers*/
/*
	структура заголовков, предварительно, выглядит так
	{
		headerText: "Header1",//заголовок
		pageNumber: 0, //содержит номер страницы, где находится искомая последовательность
		X: 0,//координаты по OX начала последовательности на данной страницы
		Y: 0,//координаты по OY начала последовательности на данной страницы
		level: 0//уровень заголовка
	}
	заголовки приходят либо в списке, либо последовательно.
*/
// CHeader
function CHeader (obj)
{
	if (obj)
	{
		this.headerText = (undefined != obj.headerText) ? obj.headerText : null;	//заголовок
		this.pageNumber = (undefined != obj.pageNumber) ? obj.pageNumber : null;	//содержит номер страницы, где находится искомая последовательность
		this.X = (undefined != obj.X) ? obj.X : null;								//координаты по OX начала последовательности на данной страницы
		this.Y = (undefined != obj.Y) ? obj.Y : null;								//координаты по OY начала последовательности на данной страницы
		this.level = (undefined != obj.level) ? obj.level : null;					//позиция заголовка
	}
	else
	{
		this.headerText = null;				//заголовок
		this.pageNumber = null;				//содержит номер страницы, где находится искомая последовательность
		this.X = null;						//координаты по OX начала последовательности на данной страницы
		this.Y = null;						//координаты по OY начала последовательности на данной страницы
		this.level = null;					//позиция заголовка
	}
}
CHeader.prototype.get_headerText = function ()
{
	return this.headerText;
2429
};
2430 2431 2432
CHeader.prototype.get_pageNumber = function ()
{
	return this.pageNumber;
2433
};
2434 2435 2436
CHeader.prototype.get_X = function ()
{
	return this.X;
2437
};
2438 2439 2440
CHeader.prototype.get_Y = function ()
{
	return this.Y;
2441
};
2442 2443 2444
CHeader.prototype.get_Level = function ()
{
	return this.level;
2445
};
2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468
var _fakeHeaders = [
	new CHeader ({headerText: "Header1", pageNumber: 0, X: 0, Y: 0, level: 1}),
	new CHeader ({headerText: "Header2", pageNumber: 0, X: 0, Y: 0, level: 1}),
	new CHeader ({headerText: "Header3", pageNumber: 0, X: 0, Y: 0, level: 2}),
	new CHeader ({headerText: "Header4", pageNumber: 0, X: 0, Y: 0, level: 1}),
	new CHeader ({headerText: "Header5", pageNumber: 0, X: 0, Y: 0, level: 1}),
	new CHeader ({headerText: "Header5", pageNumber: 0, X: 0, Y: 0, level: 1}),
	new CHeader ({headerText: "Header5", pageNumber: 0, X: 0, Y: 0, level: 2}),
	new CHeader ({headerText: "Header5", pageNumber: 0, X: 0, Y: 0, level: 3}),
	new CHeader ({headerText: "Header3", pageNumber: 0, X: 0, Y: 0, level: 4}),
	new CHeader ({headerText: "Header3", pageNumber: 0, X: 0, Y: 0, level: 5}),
	new CHeader ({headerText: "Header3", pageNumber: 0, X: 0, Y: 0, level: 6}),
	new CHeader ({headerText: "Header4", pageNumber: 0, X: 0, Y: 0, level: 7}),
	new CHeader ({headerText: "Header5", pageNumber: 0, X: 0, Y: 0, level: 8}),
	new CHeader ({headerText: "Header5", pageNumber: 0, X: 0, Y: 0, level: 1}),
	new CHeader ({headerText: "Header5", pageNumber: 0, X: 0, Y: 0, level: 1}),
	new CHeader ({headerText: "Header5", pageNumber: 0, X: 0, Y: 0, level: 2}),
	new CHeader ({headerText: "Header5", pageNumber: 0, X: 0, Y: 0, level: 3}),
	new CHeader ({headerText: "Header6", pageNumber: 0, X: 0, Y: 0, level: 1}),
	new CHeader ({headerText: "Header5", pageNumber: 0, X: 0, Y: 0, level: 0}),
	new CHeader ({headerText: "Header5", pageNumber: 0, X: 0, Y: 0, level: 1}),
	new CHeader ({headerText: "Header5", pageNumber: 0, X: 0, Y: 0, level: 0}),
	new CHeader ({headerText: "Header5", pageNumber: 0, X: 0, Y: 0, level: 0})
2469
];
2470 2471 2472

asc_docs_api.prototype.CollectHeaders = function(){
	this.sync_ReturnHeadersCallback(_fakeHeaders);
2473
};
2474 2475
asc_docs_api.prototype.GetActiveHeader = function(){

2476
};
2477 2478
asc_docs_api.prototype.gotoHeader = function(page, X, Y){
	this.goToPage(page);
2479
};
2480 2481
asc_docs_api.prototype.sync_ChangeActiveHeaderCallback = function (position, header){
	this.asc_fireCallback("asc_onChangeActiveHeader", position, new CHeader (header));
2482
};
2483
asc_docs_api.prototype.sync_ReturnHeadersCallback = function (headers){
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2484
	var _headers = [];
2485 2486 2487 2488 2489 2490
	for (var i = 0; i < headers.length; i++)
	{
		_headers[i] = new CHeader (headers[i]);
	}

	this.asc_fireCallback("asc_onReturnHeaders", _headers);
2491
};
2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503
/*----------------------------------------------------------------*/
/*functions for working with search*/
/*
	структура поиска, предварительно, выглядит так
	{
		text: "...<b>слово поиска</b>...",
		pageNumber: 0, //содержит номер страницы, где находится искомая последовательность
		X: 0,//координаты по OX начала последовательности на данной страницы
		Y: 0//координаты по OY начала последовательности на данной страницы
	}
*/

2504 2505 2506 2507 2508 2509 2510
asc_docs_api.prototype.asc_searchEnabled = function(bIsEnabled)
{
    if (null != this.WordControl.m_oDrawingDocument.m_oDocumentRenderer)
    {
        this.WordControl.m_oDrawingDocument.m_oDocumentRenderer.SearchResults.IsSearch = false;
        this.WordControl.OnUpdateOverlay();
    }
2511
};
2512

2513
asc_docs_api.prototype.asc_findText = function(text, isNext, isMatchCase)
2514
{
2515 2516 2517 2518 2519 2520
    if (null != this.WordControl.m_oDrawingDocument.m_oDocumentRenderer)
    {
        this.WordControl.m_oDrawingDocument.m_oDocumentRenderer.findText(text, isMatchCase, isNext);
        return this.WordControl.m_oDrawingDocument.m_oDocumentRenderer.SearchResults.Count;
    }

2521
    var SearchEngine = editor.WordControl.m_oLogicDocument.Search( text, { MatchCase : isMatchCase } );
2522

2523 2524 2525 2526 2527
    var Id = this.WordControl.m_oLogicDocument.Search_GetId( isNext );

    if ( null != Id )
        this.WordControl.m_oLogicDocument.Search_Select( Id );

2528
    return SearchEngine.Count;
2529
};
2530

2531
asc_docs_api.prototype.asc_replaceText = function(text, replaceWith, isReplaceAll, isMatchCase)
2532
{
2533 2534 2535 2536
    if (null == this.WordControl.m_oLogicDocument)
        return;

    this.WordControl.m_oLogicDocument.Search( text, { MatchCase : isMatchCase } );
2537

2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556
    if ( true === isReplaceAll )
        this.WordControl.m_oLogicDocument.Search_Replace(replaceWith, true, -1);
    else
    {
        var CurId = this.WordControl.m_oLogicDocument.SearchEngine.CurId;
        var bDirection = this.WordControl.m_oLogicDocument.SearchEngine.Direction;
        if ( -1 != CurId )
            this.WordControl.m_oLogicDocument.Search_Replace(replaceWith, false, CurId);

        var Id = this.WordControl.m_oLogicDocument.Search_GetId( bDirection );

        if ( null != Id )
        {
            this.WordControl.m_oLogicDocument.Search_Select( Id );
            return true;
        }

        return false;
    }
2557
};
2558

2559
asc_docs_api.prototype.asc_selectSearchingResults = function(bShow)
2560
{
2561 2562 2563 2564 2565 2566
    if (null != this.WordControl.m_oDrawingDocument.m_oDocumentRenderer)
    {
        this.WordControl.m_oDrawingDocument.m_oDocumentRenderer.SearchResults.Show = bShow;
        this.WordControl.OnUpdateOverlay();
        return;
    }
2567
    this.WordControl.m_oLogicDocument.Search_Set_Selection(bShow);
2568
};
2569

2570
asc_docs_api.prototype.asc_isSelectSearchingResults = function()
2571
{
2572 2573 2574 2575
    if (null != this.WordControl.m_oDrawingDocument.m_oDocumentRenderer)
    {
        return this.WordControl.m_oDrawingDocument.m_oDocumentRenderer.SearchResults.Show;
    }
2576
    return this.WordControl.m_oLogicDocument.Search_Get_Selection();
2577
};
2578

2579
asc_docs_api.prototype.sync_ReplaceAllCallback = function(ReplaceCount, OverallCount)
2580
{
2581
    this.asc_fireCallback("asc_onReplaceAll", ReplaceCount, OverallCount);
2582
};
2583 2584

asc_docs_api.prototype.sync_SearchEndCallback = function()
2585 2586
{
	this.asc_fireCallback("asc_onSearchEnd");
2587
};
2588 2589 2590 2591 2592 2593
/*----------------------------------------------------------------*/
/*functions for working with font*/
/*setters*/
asc_docs_api.prototype.put_TextPrFontName = function(name)
{
	var loader = window.g_font_loader;
2594
	var fontinfo = g_fontApplication.GetFontInfo(name);
2595 2596 2597 2598 2599
	var isasync = loader.LoadFont(fontinfo);
	if (false === isasync)
    {
        if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
        {
2600
            this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetTextFontName);
2601
            this.WordControl.m_oLogicDocument.Paragraph_Add( new ParaTextPr( { FontFamily : { Name : name , Index : -1 } } ) );
2602 2603
        }
    }
2604
};
2605 2606 2607 2608
asc_docs_api.prototype.put_TextPrFontSize = function(size)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
2609
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetTextFontSize);
2610 2611
        this.WordControl.m_oLogicDocument.Paragraph_Add( new ParaTextPr( { FontSize : Math.min(size, 100) } ) );
    }
2612
};
2613

2614 2615 2616 2617
asc_docs_api.prototype.put_TextPrBold = function(value)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
2618
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetTextBold);
2619 2620
    	this.WordControl.m_oLogicDocument.Paragraph_Add( new ParaTextPr( { Bold : value } ) );
    }
2621
};
2622 2623 2624 2625
asc_docs_api.prototype.put_TextPrItalic = function(value)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
2626
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetTextItalic);
2627 2628
	    this.WordControl.m_oLogicDocument.Paragraph_Add( new ParaTextPr( { Italic : value } ) );
    }
2629
};
2630 2631 2632 2633
asc_docs_api.prototype.put_TextPrUnderline = function(value)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
2634
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetTextUnderline);
2635 2636 2637 2638 2639
        this.WordControl.m_oLogicDocument.Paragraph_Add( new ParaTextPr( { Underline : value } ) );

        if ( true === this.isMarkerFormat )
            this.sync_MarkerFormatCallback( false );
    }
2640
};
2641 2642 2643 2644
asc_docs_api.prototype.put_TextPrStrikeout = function(value)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
2645
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetTextStrikeout);
2646 2647 2648 2649 2650
        this.WordControl.m_oLogicDocument.Paragraph_Add( new ParaTextPr( { Strikeout : value, DStrikeout : false } ) );

        if ( true === this.isMarkerFormat )
            this.sync_MarkerFormatCallback( false );
    }
2651
};
2652 2653 2654 2655
asc_docs_api.prototype.put_TextPrDStrikeout = function(value)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
2656
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetTextDStrikeout);
2657 2658 2659 2660 2661
        this.WordControl.m_oLogicDocument.Paragraph_Add( new ParaTextPr( { DStrikeout : value, Strikeout : false } ) );

        if ( true === this.isMarkerFormat )
            this.sync_MarkerFormatCallback( false );
    }
2662
};
2663 2664 2665 2666
asc_docs_api.prototype.put_TextPrSpacing = function(value)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
2667
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetTextSpacing);
2668 2669 2670 2671 2672
        this.WordControl.m_oLogicDocument.Paragraph_Add( new ParaTextPr( { Spacing : value } ) );

        if ( true === this.isMarkerFormat )
            this.sync_MarkerFormatCallback( false );
    }
2673
};
2674 2675 2676 2677 2678

asc_docs_api.prototype.put_TextPrCaps = function(value)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
2679
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetTextCaps);
2680 2681 2682 2683 2684
        this.WordControl.m_oLogicDocument.Paragraph_Add( new ParaTextPr( { Caps : value, SmallCaps : false } ) );

        if ( true === this.isMarkerFormat )
            this.sync_MarkerFormatCallback( false );
    }
2685
};
2686 2687 2688 2689 2690

asc_docs_api.prototype.put_TextPrSmallCaps = function(value)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
2691
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetTextSmallCaps);
2692 2693 2694 2695 2696
        this.WordControl.m_oLogicDocument.Paragraph_Add( new ParaTextPr( { SmallCaps : value, Caps : false } ) );

        if ( true === this.isMarkerFormat )
            this.sync_MarkerFormatCallback( false );
    }
2697
};
2698 2699 2700 2701 2702 2703


asc_docs_api.prototype.put_TextPrPosition = function(value)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
2704
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetTextPosition);
2705 2706 2707 2708 2709
        this.WordControl.m_oLogicDocument.Paragraph_Add( new ParaTextPr( { Position : value } ) );

        if ( true === this.isMarkerFormat )
            this.sync_MarkerFormatCallback( false );
    }
2710
};
2711

2712 2713 2714 2715
asc_docs_api.prototype.put_TextPrLang = function(value)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
2716
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetTextLang);
2717 2718
        this.WordControl.m_oLogicDocument.Paragraph_Add( new ParaTextPr( { Lang : { Val : value } } ) );

2719 2720
        this.WordControl.m_oLogicDocument.Spelling.Check_CurParas();

2721 2722 2723
        if ( true === this.isMarkerFormat )
            this.sync_MarkerFormatCallback( false );
    }
2724
};
2725 2726


2727 2728 2729 2730
asc_docs_api.prototype.put_PrLineSpacing = function(Type, Value)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Properties) )
    {
2731
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetParagraphLineSpacing);
2732 2733 2734 2735 2736 2737
        this.WordControl.m_oLogicDocument.Set_ParagraphSpacing( { LineRule : Type,  Line : Value } );

        var ParaPr = this.get_TextProps().ParaPr;
        if ( null != ParaPr )
            this.sync_ParaSpacingLine( ParaPr.Spacing );
    }
2738
};
2739 2740 2741 2742
asc_docs_api.prototype.put_LineSpacingBeforeAfter = function(type,value)//"type == 0" means "Before", "type == 1" means "After"
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Properties) )
    {
2743
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetParagraphLineSpacingBeforeAfter);
2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765
        switch (type)
        {
            case 0:
            {
                if ( spacing_Auto === value )
                    this.WordControl.m_oLogicDocument.Set_ParagraphSpacing( { BeforeAutoSpacing : true } );
                else
                    this.WordControl.m_oLogicDocument.Set_ParagraphSpacing( { Before : value, BeforeAutoSpacing : false } );

                break;
            }
            case 1:
            {
                if ( spacing_Auto === value )
                    this.WordControl.m_oLogicDocument.Set_ParagraphSpacing( { AfterAutoSpacing : true } );
                else
                    this.WordControl.m_oLogicDocument.Set_ParagraphSpacing( { After : value, AfterAutoSpacing : false });

                break;
            }
        }
    }
2766
};
2767 2768 2769 2770
asc_docs_api.prototype.FontSizeIn = function()
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
2771
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_IncFontSize);
2772 2773
        this.WordControl.m_oLogicDocument.Paragraph_IncDecFontSize(true);
    }
2774
};
2775 2776 2777 2778
asc_docs_api.prototype.FontSizeOut = function()
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
2779
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_DecFontSize);
2780 2781
        this.WordControl.m_oLogicDocument.Paragraph_IncDecFontSize(false);
    }
2782
};
2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815
// Object:
// {
//    Bottom :
//    {
//        Color : { r : 0, g : 0, b : 0 },
//        Value : border_Single,
//        Size  : 0.5 * g_dKoef_pt_to_mm
//        Space : 0
//    },
//    Left :
//    {
//        ....
//    }
//    Right :
//    {
//        ....
//    }
//    Top :
//    {
//        ....
//    }
//    },
//    Between :
//    {
//        ....
//    }
// }


asc_docs_api.prototype.put_Borders = function(Obj)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Properties) )
    {
2816
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetParagraphBorders);
2817 2818
        this.WordControl.m_oLogicDocument.Set_ParagraphBorders( Obj );
    }
2819
};
2820 2821 2822
/*callbacks*/
asc_docs_api.prototype.sync_BoldCallBack = function(isBold){
	this.asc_fireCallback("asc_onBold",isBold);
2823
};
2824 2825
asc_docs_api.prototype.sync_ItalicCallBack = function(isItalic){
	this.asc_fireCallback("asc_onItalic",isItalic);
2826
};
2827 2828
asc_docs_api.prototype.sync_UnderlineCallBack = function(isUnderline){
	this.asc_fireCallback("asc_onUnderline",isUnderline);
2829
};
2830 2831
asc_docs_api.prototype.sync_StrikeoutCallBack = function(isStrikeout){
	this.asc_fireCallback("asc_onStrikeout",isStrikeout);
2832
};
2833 2834 2835
asc_docs_api.prototype.sync_TextPrFontFamilyCallBack = function(FontFamily)
{
    if ( undefined != FontFamily )
2836
	    this.asc_fireCallback("asc_onFontFamily", new asc_CTextFontFamily( FontFamily ));
2837
    else
2838
        this.asc_fireCallback("asc_onFontFamily", new asc_CTextFontFamily( { Name : "", Index : -1 } ));
2839
};
2840 2841
asc_docs_api.prototype.sync_TextPrFontSizeCallBack = function(FontSize){
	this.asc_fireCallback("asc_onFontSize",FontSize);
2842
};
2843
asc_docs_api.prototype.sync_PrLineSpacingCallBack = function(LineSpacing){
2844
    this.asc_fireCallback("asc_onLineSpacing", new asc_CParagraphInd( LineSpacing ) );
2845
};
2846
asc_docs_api.prototype.sync_InitEditorStyles = function(styles_painter){
2847
    this.asc_fireCallback("asc_onInitEditorStyles", styles_painter);
2848
};
Oleg.Korshul's avatar
Oleg.Korshul committed
2849 2850
asc_docs_api.prototype.sync_InitEditorTableStyles = function(styles, is_retina_enabled){
    this.asc_fireCallback("asc_onInitTableTemplates",styles, is_retina_enabled);
2851
};
2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879


/*----------------------------------------------------------------*/
/*functions for working with paragraph*/
/*setters*/
// Right = 0; Left = 1; Center = 2; Justify = 3; or using enum that written above

/* структура для параграфа
	Ind :
   	{
       	Left      : 0,                    // Левый отступ
       	Right     : 0,                    // Правый отступ
     	FirstLine : 0                     // Первая строка
   	}
   	Spacing :
   	{
       	Line     : 1.15,                  // Расстояние между строками внутри абзаца
       	LineRule : linerule_Auto,         // Тип расстрояния между строками
       	Before   : 0,                     // Дополнительное расстояние до абзаца
       	After    : 10 * g_dKoef_pt_to_mm  // Дополнительное расстояние после абзаца
   	},
   	KeepLines : false,                    // переносить параграф на новую страницу,
                                         // если на текущей он целиком не убирается
   	PageBreakBefore : false
*/

asc_docs_api.prototype.paraApply = function(Props)
{
2880 2881 2882 2883 2884
    var Additional = undefined;
    if ( undefined != Props.DefaultTab )
        Additional = { Type : changestype_2_Element_and_Type, Element : this.WordControl.m_oLogicDocument, CheckType : changestype_Document_SectPr };

    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Properties, Additional) )
2885
    {
2886
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetParagraphPr);
2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900

        // TODO: Сделать так, чтобы пересчет был всего 1 здесь
        if ( "undefined" != typeof(Props.ContextualSpacing) && null != Props.ContextualSpacing )
            this.WordControl.m_oLogicDocument.Set_ParagraphContextualSpacing( Props.ContextualSpacing );

        if ( "undefined" != typeof(Props.Ind) && null != Props.Ind )
            this.WordControl.m_oLogicDocument.Set_ParagraphIndent( Props.Ind );

        if ( "undefined" != typeof(Props.Jc) && null != Props.Jc )
            this.WordControl.m_oLogicDocument.Set_ParagraphAlign( Props.Jc );

        if ( "undefined" != typeof(Props.KeepLines) && null != Props.KeepLines )
            this.WordControl.m_oLogicDocument.Set_ParagraphKeepLines( Props.KeepLines );

2901 2902 2903
        if ( undefined != Props.KeepNext && null != Props.KeepNext )
            this.WordControl.m_oLogicDocument.Set_ParagraphKeepNext( Props.KeepNext );

2904 2905 2906
        if ( undefined != Props.WidowControl && null != Props.WidowControl )
            this.WordControl.m_oLogicDocument.Set_ParagraphWidowControl( Props.WidowControl );

2907 2908 2909 2910 2911 2912 2913
        if ( "undefined" != typeof(Props.PageBreakBefore) && null != Props.PageBreakBefore )
            this.WordControl.m_oLogicDocument.Set_ParagraphPageBreakBefore( Props.PageBreakBefore );

        if ( "undefined" != typeof(Props.Spacing) && null != Props.Spacing )
            this.WordControl.m_oLogicDocument.Set_ParagraphSpacing( Props.Spacing );

        if ( "undefined" != typeof(Props.Shd) && null != Props.Shd )
2914 2915 2916 2917 2918 2919 2920 2921
        {
            var Unifill = new CUniFill();
            Unifill.fill = new CSolidFill();
            Unifill.fill.color = CorrectUniColor(Props.Shd.Color, Unifill.fill.color, 1);
            this.WordControl.m_oLogicDocument.Set_ParagraphShd(
                {
                    Value : Props.Shd.Value,
                    Color: {
2922 2923 2924
                        r : Props.Shd.Color.asc_getR(),
                        g : Props.Shd.Color.asc_getG(),
                        b : Props.Shd.Color.asc_getB()
2925 2926 2927 2928
                    },
                    Unifill: Unifill
                } );
        }
2929 2930

        if ( "undefined" != typeof(Props.Brd) && null != Props.Brd )
Anna.Pavlova's avatar
Anna.Pavlova committed
2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956
        {
            if(Props.Brd.Left && Props.Brd.Left.Color)
            {
                Props.Brd.Left.Unifill = CreateUnifillFromAscColor(Props.Brd.Left.Color);
            }
            if(Props.Brd.Top && Props.Brd.Top.Color)
            {
                Props.Brd.Top.Unifill = CreateUnifillFromAscColor(Props.Brd.Top.Color);
            }
            if(Props.Brd.Right && Props.Brd.Right.Color)
            {
                Props.Brd.Right.Unifill = CreateUnifillFromAscColor(Props.Brd.Right.Color);
            }
            if(Props.Brd.Bottom && Props.Brd.Bottom.Color)
            {
                Props.Brd.Bottom.Unifill = CreateUnifillFromAscColor(Props.Brd.Bottom.Color);
            }
            if(Props.Brd.InsideH && Props.Brd.InsideH.Color)
            {
                Props.Brd.InsideH.Unifill = CreateUnifillFromAscColor(Props.Brd.InsideH.Color);
            }
            if(Props.Brd.InsideV && Props.Brd.InsideV.Color)
            {
                Props.Brd.InsideV.Unifill = CreateUnifillFromAscColor(Props.Brd.InsideV.Color);
            }

2957
            this.WordControl.m_oLogicDocument.Set_ParagraphBorders( Props.Brd );
Anna.Pavlova's avatar
Anna.Pavlova committed
2958
        }
2959

2960 2961 2962 2963 2964 2965 2966 2967 2968
        if ( undefined != Props.Tabs )
        {
            var Tabs = new CParaTabs();
            Tabs.Set_FromObject( Props.Tabs.Tabs );
            this.WordControl.m_oLogicDocument.Set_ParagraphTabs( Tabs );
        }

        if ( undefined != Props.DefaultTab )
        {
2969
            this.WordControl.m_oLogicDocument.Set_DocumentDefaultTab( Props.DefaultTab );
2970 2971
        }

2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017

        // TODO: как только разъединят настройки параграфа и текста переделать тут
        var TextPr = new CTextPr();

        if ( true === Props.Subscript )
            TextPr.VertAlign = vertalign_SubScript;
        else if ( true === Props.Superscript )
            TextPr.VertAlign = vertalign_SuperScript;
        else if ( false === Props.Superscript || false === Props.Subscript )
            TextPr.VertAlign = vertalign_Baseline;

        if ( undefined != Props.Strikeout )
        {
            TextPr.Strikeout  = Props.Strikeout;
            TextPr.DStrikeout = false;
        }

        if ( undefined != Props.DStrikeout )
        {
            TextPr.DStrikeout = Props.DStrikeout;
            if ( true === TextPr.DStrikeout )
                TextPr.Strikeout = false;
        }

        if ( undefined != Props.SmallCaps )
        {
            TextPr.SmallCaps = Props.SmallCaps;
            TextPr.AllCaps   = false;
        }

        if ( undefined != Props.AllCaps )
        {
            TextPr.Caps = Props.AllCaps;
            if ( true === TextPr.AllCaps )
                TextPr.SmallCaps = false;
        }

        if ( undefined != Props.TextSpacing )
            TextPr.Spacing = Props.TextSpacing;

        if ( undefined != Props.Position )
            TextPr.Position = Props.Position;

        this.WordControl.m_oLogicDocument.Paragraph_Add( new ParaTextPr(TextPr) );
        this.WordControl.m_oLogicDocument.Document_UpdateInterfaceState();
    }
3018
};
3019 3020 3021 3022 3023

asc_docs_api.prototype.put_PrAlign = function(value)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Properties) )
    {
3024
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetParagraphAlign);
3025 3026
        this.WordControl.m_oLogicDocument.Set_ParagraphAlign(value);
    }
3027
};
3028 3029 3030 3031 3032
// 0- baseline, 2-subscript, 1-superscript
asc_docs_api.prototype.put_TextPrBaseline = function(value)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
3033
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetTextVertAlign);
3034 3035
    	this.WordControl.m_oLogicDocument.Paragraph_Add( new ParaTextPr( { VertAlign : value } ) );
    }
3036
};
3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079
/*
    Во всех случаях SubType = 0 означает, что нажали просто на кнопку
    c выбором типа списка, без выбора подтипа.

 	Маркированный список Type = 0
		нет          - SubType = -1
		черная точка - SubType = 1
		круг         - SubType = 2
		квадрат      - SubType = 3
		картинка     - SubType = -1
		4 ромба      - SubType = 4
		ч/б стрелка  - SubType = 5
		галка        - SubType = 6
		ромб         - SubType = 7

	Нумерованный список Type = 1
		нет - SubType = -1
		1.  - SubType = 1
		1)  - SubType = 2
		I.  - SubType = 3
		A.  - SubType = 4
		a)  - SubType = 5
		a.  - SubType = 6
		i.  - SubType = 7

	Многоуровневый список Type = 2
		нет           - SubType = -1
		1)a)i)        - SubType = 1
		1.1.1         - SubType = 2
		маркированный - SubType = 3
*/
asc_docs_api.prototype.put_ListType = function(type, subtype)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Properties) )
    {
        var NumberInfo =
        {
            Type    : 0,
            SubType : -1
        };

        NumberInfo.Type = type;
        NumberInfo.SubType = subtype;
3080
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetParagraphNumbering);
3081 3082
        this.WordControl.m_oLogicDocument.Set_ParagraphNumbering( NumberInfo );
    }
3083
};
3084 3085 3086 3087
asc_docs_api.prototype.put_Style = function(name)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Properties) )
    {
3088
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetParagraphStyle);
3089 3090
        this.WordControl.m_oLogicDocument.Set_ParagraphStyle(name);
    }
3091
};
3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117

asc_docs_api.prototype.SetDeviceInputHelperId = function(idKeyboard)
{
    if (window.ID_KEYBOARD_AREA === undefined && this.WordControl.m_oMainView != null)
    {
        window.ID_KEYBOARD_AREA = document.getElementById(idKeyboard);

        window.ID_KEYBOARD_AREA.onkeypress = function(e){
            if (false === editor.WordControl.IsFocus)
            {
                editor.WordControl.IsFocus = true;
                var ret = editor.WordControl.onKeyPress(e);
                editor.WordControl.IsFocus = false;
                return ret;
            }
        }
        window.ID_KEYBOARD_AREA.onkeydown = function(e){
            if (false === editor.WordControl.IsFocus)
            {
                editor.WordControl.IsFocus = true;
                var ret = editor.WordControl.onKeyDown(e);
                editor.WordControl.IsFocus = false;
                return ret;
            }
        }
    }
3118
};
3119

3120 3121 3122
asc_docs_api.prototype.put_ShowSnapLines = function(isShow)
{
    this.ShowSnapLines = isShow;
3123
};
3124 3125 3126
asc_docs_api.prototype.get_ShowSnapLines = function()
{
    return this.ShowSnapLines;
3127
};
3128

3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165
asc_docs_api.prototype.put_ShowParaMarks = function(isShow)
{
    /*
    if (window.IsAddDiv === undefined && this.WordControl.m_oMainView != null)
    {
        window.IsAddDiv = true;

        var _div = this.WordControl.m_oMainView.HtmlElement;

        var test = document.createElement('textarea');
        test.id = "area_id";

        test.setAttribute("style", "font-family:arial;font-size:12pt;position:absolute;resize:none;padding:2px;margin:0px;font-weight:normal;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;z-index:1000");
        test.style.border = "2px solid #4363A4";

        test.style.width = "100px";
        //this.TextBoxInput.style.height = "40px";
        test.rows = 1;

        _div.appendChild(test);

        test.onkeypress = function(e){
            return editor.WordControl.onKeyPress(e);
        }
        test.onkeydown = function(e){
            return editor.WordControl.onKeyDown(e);
        }
    }
    */

	this.ShowParaMarks = isShow;
	this.WordControl.OnRePaintAttack();

    if ( true === this.isMarkerFormat )
        this.sync_MarkerFormatCallback( false );

    return this.ShowParaMarks;
3166
};
3167 3168
asc_docs_api.prototype.get_ShowParaMarks = function(){
    return this.ShowParaMarks;
3169
};
3170 3171 3172 3173 3174 3175 3176 3177 3178
asc_docs_api.prototype.put_ShowTableEmptyLine = function(isShow)
{
    this.isShowTableEmptyLine = isShow;
    this.WordControl.OnRePaintAttack();

    if ( true === this.isMarkerFormat )
        this.sync_MarkerFormatCallback( false );

    return this.isShowTableEmptyLine;
3179
};
3180 3181
asc_docs_api.prototype.get_ShowTableEmptyLine = function(){
    return this.isShowTableEmptyLine;
3182
};
3183 3184 3185 3186 3187
asc_docs_api.prototype.put_PageBreak = function(isBreak)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Properties) )
    {
        this.isPageBreakBefore = isBreak;
3188
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetParagraphPageBreakBefore);
3189 3190 3191
        this.WordControl.m_oLogicDocument.Set_ParagraphPageBreakBefore(isBreak);
        this.sync_PageBreakCallback(isBreak);
    }
3192
};
3193 3194 3195 3196 3197

asc_docs_api.prototype.put_WidowControl = function(bValue)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Properties) )
    {
3198
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetParagraphWidowControl);
3199 3200 3201
        this.WordControl.m_oLogicDocument.Set_ParagraphWidowControl(bValue);
        this.sync_WidowControlCallback(bValue);
    }
3202
};
3203

3204 3205 3206 3207 3208
asc_docs_api.prototype.put_KeepLines = function(isKeepLines)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Properties) )
    {
        this.isKeepLinesTogether = isKeepLines;
3209
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetParagraphKeepLines);
3210 3211 3212
        this.WordControl.m_oLogicDocument.Set_ParagraphKeepLines(isKeepLines);
        this.sync_KeepLinesCallback(isKeepLines);
    }
3213
};
3214 3215 3216 3217 3218

asc_docs_api.prototype.put_KeepNext = function(isKeepNext)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Properties) )
    {
3219
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetParagraphKeepNext);
3220 3221 3222
        this.WordControl.m_oLogicDocument.Set_ParagraphKeepNext(isKeepNext);
        this.sync_KeepNextCallback(isKeepNext);
    }
3223
};
3224

3225 3226 3227 3228 3229
asc_docs_api.prototype.put_AddSpaceBetweenPrg = function(isSpacePrg)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Properties) )
    {
        this.isAddSpaceBetweenPrg = isSpacePrg;
3230
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetParagraphContextualSpacing);
3231 3232
        this.WordControl.m_oLogicDocument.Set_ParagraphContextualSpacing(isSpacePrg);
    }
3233
};
3234 3235 3236 3237 3238 3239
asc_docs_api.prototype.put_LineHighLight = function(is_flag, r, g, b)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
        if (false === is_flag)
        {
3240
            this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetTextHighlightNone);
3241 3242 3243 3244
            this.WordControl.m_oLogicDocument.Paragraph_Add( new ParaTextPr( { HighLight : highlight_None  } ) );
        }
        else
        {
3245
            this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetTextHighlightColor);
3246 3247 3248
            this.WordControl.m_oLogicDocument.Paragraph_Add( new ParaTextPr( { HighLight :  { r : r, g : g, b: b}  } ) );
        }
    }
3249
};
3250 3251 3252 3253
asc_docs_api.prototype.put_TextColor = function(color)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
3254
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetTextColor);
3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266
        
        if ( true === color.Auto )
        {
            this.WordControl.m_oLogicDocument.Paragraph_Add( new ParaTextPr( { Color : { Auto : true, r : 0, g : 0, b : 0 }, Unifill : undefined } ) );   
        }
        else
        {
            var Unifill = new CUniFill();
            Unifill.fill = new CSolidFill();
            Unifill.fill.color = CorrectUniColor(color, Unifill.fill.color, 1);
            this.WordControl.m_oLogicDocument.Paragraph_Add( new ParaTextPr( { Unifill : Unifill} ) );
        }
3267 3268 3269 3270

        if ( true === this.isMarkerFormat )
            this.sync_MarkerFormatCallback( false );
    }
3271
};
3272
asc_docs_api.prototype.put_ParagraphShade = function(is_flag, color, isOnlyPara)
3273 3274 3275
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Properties) )
    {
3276
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetParagraphShd);
3277 3278 3279 3280

        if (true === isOnlyPara)
            this.WordControl.m_oLogicDocument.Set_UseTextShd(false);

3281 3282 3283 3284
        if (false === is_flag)
            this.WordControl.m_oLogicDocument.Set_ParagraphShd( { Value : shd_Nil  }  );
        else
        {
Anna.Pavlova's avatar
Anna.Pavlova committed
3285 3286
            var Unifill = new CUniFill();
            Unifill.fill = new CSolidFill();
3287
            Unifill.fill.color = CorrectUniColor(color, Unifill.fill.color, 1);
3288
            this.WordControl.m_oLogicDocument.Set_ParagraphShd( { Value : shd_Clear, Color : { r : color.asc_getR(), g : color.asc_getG(), b : color.asc_getB() }, Unifill: Unifill } );
3289
        }
3290 3291

        this.WordControl.m_oLogicDocument.Set_UseTextShd(true);
3292
    }
3293
};
3294 3295 3296 3297
asc_docs_api.prototype.put_PrIndent = function(value,levelValue)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Properties) )
    {
3298
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetParagraphIndent);
3299 3300
        this.WordControl.m_oLogicDocument.Set_ParagraphIndent( { Left : value, ChangeLevel: levelValue } );
    }
3301
};
3302 3303 3304 3305
asc_docs_api.prototype.IncreaseIndent = function()
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Properties) )
    {
3306
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_IncParagraphIndent);
3307 3308
        this.WordControl.m_oLogicDocument.Paragraph_IncDecIndent( true );
    }
3309
};
3310 3311 3312 3313
asc_docs_api.prototype.DecreaseIndent = function()
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Properties) )
    {
3314
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_DecParagraphIndent);
3315 3316
        this.WordControl.m_oLogicDocument.Paragraph_IncDecIndent( false );
    }
3317
};
3318 3319 3320 3321
asc_docs_api.prototype.put_PrIndentRight = function(value)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Properties) )
    {
3322
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetParagraphIndentRight);
3323 3324
        this.WordControl.m_oLogicDocument.Set_ParagraphIndent( { Right : value } );
    }
3325
};
3326 3327 3328 3329
asc_docs_api.prototype.put_PrFirstLineIndent = function(value)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Properties) )
    {
3330
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetParagraphIndentFirstLine);
3331 3332
	    this.WordControl.m_oLogicDocument.Set_ParagraphIndent( { FirstLine : value } );
    }
3333
};
3334 3335 3336
asc_docs_api.prototype.put_Margins = function(left, top, right, bottom)
{
	this.WordControl.m_oLogicDocument.Set_DocumentMargin( { Left : left, Top : top, Right : right, Bottom : bottom });
3337
};
3338 3339
asc_docs_api.prototype.getFocusObject = function(){//возвратит тип элемента - параграф c_oAscTypeSelectElement.Paragraph, изображение c_oAscTypeSelectElement.Image, таблица c_oAscTypeSelectElement.Table, колонтитул c_oAscTypeSelectElement.Header.

3340
};
3341 3342 3343 3344

/*callbacks*/
asc_docs_api.prototype.sync_VerticalAlign = function(typeBaseline){
	this.asc_fireCallback("asc_onVerticalAlign",typeBaseline);
3345
};
3346 3347
asc_docs_api.prototype.sync_PrAlignCallBack = function(value){
	this.asc_fireCallback("asc_onPrAlign",value);
3348
};
3349
asc_docs_api.prototype.sync_ListType = function(NumPr){
3350
    this.asc_fireCallback("asc_onListType", new asc_CListType( NumPr ) );
3351
};
3352
asc_docs_api.prototype.sync_TextColor = function(TextPr)
3353
{
3354 3355 3356 3357 3358 3359 3360 3361
    if(TextPr.Unifill && TextPr.Unifill.fill && TextPr.Unifill.fill.type === FILL_TYPE_SOLID && TextPr.Unifill.fill.color)
    {
        this.asc_fireCallback("asc_onTextColor", CreateAscColor(TextPr.Unifill.fill.color));
    }
    else if( undefined != TextPr.Color )
    {
        this.asc_fireCallback("asc_onTextColor", CreateAscColorCustom( TextPr.Color.r, TextPr.Color.g, TextPr.Color.b, TextPr.Color.Auto ));
    }
3362
};
3363 3364 3365 3366
asc_docs_api.prototype.sync_TextHighLight = function(HighLight)
{
    if ( undefined != HighLight )
	    this.asc_fireCallback("asc_onTextHighLight", new CColor( HighLight.r, HighLight.g, HighLight.b ) );
3367
};
3368 3369 3370
asc_docs_api.prototype.sync_TextSpacing = function(Spacing)
{
    this.asc_fireCallback("asc_onTextSpacing", Spacing );
3371
};
3372 3373 3374
asc_docs_api.prototype.sync_TextDStrikeout = function(Value)
{
    this.asc_fireCallback("asc_onTextDStrikeout", Value );
3375
};
3376 3377 3378
asc_docs_api.prototype.sync_TextCaps = function(Value)
{
    this.asc_fireCallback("asc_onTextCaps", Value );
3379
};
3380 3381 3382
asc_docs_api.prototype.sync_TextSmallCaps = function(Value)
{
    this.asc_fireCallback("asc_onTextSmallCaps", Value );
3383
};
3384 3385 3386
asc_docs_api.prototype.sync_TextPosition = function(Value)
{
    this.asc_fireCallback("asc_onTextPosition", Value );
3387
};
Ilya.Kirillov's avatar
Ilya.Kirillov committed
3388 3389 3390
asc_docs_api.prototype.sync_TextLangCallBack = function(Lang)
{
    this.asc_fireCallback("asc_onTextLanguage", Lang.Val );
3391
};
3392 3393
asc_docs_api.prototype.sync_ParaStyleName = function(Name){
	this.asc_fireCallback("asc_onParaStyleName",Name);
3394
};
3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406
asc_docs_api.prototype.sync_ParaSpacingLine = function(SpacingLine)
{
    if ( true === SpacingLine.AfterAutoSpacing )
        SpacingLine.After = spacing_Auto;
    else if ( undefined === SpacingLine.AfterAutoSpacing )
        SpacingLine.After = UnknownValue;

    if ( true === SpacingLine.BeforeAutoSpacing )
        SpacingLine.Before = spacing_Auto;
    else if ( undefined === SpacingLine.BeforeAutoSpacing )
        SpacingLine.Before = UnknownValue;

3407
	this.asc_fireCallback("asc_onParaSpacingLine", new asc_CParagraphSpacing( SpacingLine ));
3408
};
3409 3410
asc_docs_api.prototype.sync_PageBreakCallback = function(isBreak){
	this.asc_fireCallback("asc_onPageBreak",isBreak);
3411
};
3412 3413 3414 3415

asc_docs_api.prototype.sync_WidowControlCallback = function(bValue)
{
    this.asc_fireCallback("asc_onWidowControl",bValue);
3416
};
3417 3418 3419 3420

asc_docs_api.prototype.sync_KeepNextCallback = function(bValue)
{
    this.asc_fireCallback("asc_onKeepNext",bValue);
3421
};
3422

3423 3424
asc_docs_api.prototype.sync_KeepLinesCallback = function(isKeepLines){
	this.asc_fireCallback("asc_onKeepLines",isKeepLines);
3425
};
3426 3427
asc_docs_api.prototype.sync_ShowParaMarksCallback = function(){
	this.asc_fireCallback("asc_onShowParaMarks");
3428
};
3429 3430
asc_docs_api.prototype.sync_SpaceBetweenPrgCallback = function(){
	this.asc_fireCallback("asc_onSpaceBetweenPrg");
3431
};
3432 3433 3434 3435 3436 3437
asc_docs_api.prototype.sync_PrPropCallback = function(prProp){
    var _len = this.SelectedObjectsStack.length;
    if (_len > 0)
    {
        if (this.SelectedObjectsStack[_len - 1].Type == c_oAscTypeSelectElement.Paragraph)
        {
3438
            this.SelectedObjectsStack[_len - 1].Value = new asc_CParagraphProperty( prProp );
3439 3440 3441 3442
            return;
        }
    }

3443
    this.SelectedObjectsStack[this.SelectedObjectsStack.length] = new asc_CSelectedObject( c_oAscTypeSelectElement.Paragraph, new asc_CParagraphProperty( prProp ) );
3444
};
3445

3446 3447
asc_docs_api.prototype.sync_MathPropCallback = function(MathProp)
{
3448
    this.SelectedObjectsStack[this.SelectedObjectsStack.length] = new asc_CSelectedObject(c_oAscTypeSelectElement.Math, new CMathProp(MathProp));
3449
};
3450

3451 3452 3453 3454 3455 3456 3457
asc_docs_api.prototype.sync_EndAddShape = function()
{
    editor.asc_fireCallback("asc_onEndAddShape");
    if (this.WordControl.m_oDrawingDocument.m_sLockedCursorType == "crosshair")
    {
        this.WordControl.m_oDrawingDocument.UnlockCursorType();
    }
3458
};
3459

Oleg.Korshul's avatar
Oleg.Korshul committed
3460 3461 3462
asc_docs_api.prototype.SetDrawingFreeze = function(bIsFreeze)
{
    this.WordControl.DrawingFreeze = bIsFreeze;
Oleg.Korshul's avatar
Oleg.Korshul committed
3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481

    var _elem1 = document.getElementById("id_main");
    if (_elem1)
    {
        var _elem2 = document.getElementById("id_horscrollpanel");
        var _elem3 = document.getElementById("id_panel_right");
        if (bIsFreeze)
        {
            _elem1.style.display = "none";
            _elem2.style.display = "none";
            _elem3.style.display = "none";
        }
        else
        {
            _elem1.style.display = "block";
            _elem2.style.display = "block";
            _elem3.style.display = "block";
        }
    }
Oleg.Korshul's avatar
Oleg.Korshul committed
3482 3483 3484

    if (!bIsFreeze)
        this.WordControl.OnScroll();
3485
};
Oleg.Korshul's avatar
Oleg.Korshul committed
3486

3487 3488 3489 3490 3491 3492 3493
/*----------------------------------------------------------------*/
/*functions for working with page*/
asc_docs_api.prototype.change_PageOrient = function(isPortrait)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Document_SectPr) )
    {
        this.WordControl.m_oDrawingDocument.m_bIsUpdateDocSize = true;
3494
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetPageOrientation);
3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506
        if (isPortrait)
        {
            this.WordControl.m_oLogicDocument.Set_DocumentOrientation(orientation_Portrait);
            this.DocumentOrientation = isPortrait;
        }
        else
        {
            this.WordControl.m_oLogicDocument.Set_DocumentOrientation(orientation_Landscape);
            this.DocumentOrientation = isPortrait;
        }
        this.sync_PageOrientCallback(editor.get_DocumentOrientation());
    }
3507
};
3508 3509 3510
asc_docs_api.prototype.get_DocumentOrientation = function()
{
	return this.DocumentOrientation;
3511
};
3512 3513 3514 3515 3516
asc_docs_api.prototype.change_DocSize = function(width,height)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Document_SectPr) )
    {
        this.WordControl.m_oDrawingDocument.m_bIsUpdateDocSize = true;
3517
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetPageSize);
3518 3519 3520 3521 3522
        if (this.DocumentOrientation)
            this.WordControl.m_oLogicDocument.Set_DocumentPageSize(width, height);
        else
            this.WordControl.m_oLogicDocument.Set_DocumentPageSize(height, width);
    }
3523
};
3524 3525 3526 3527

asc_docs_api.prototype.get_DocumentWidth = function()
{
    return Page_Width;
3528
};
3529 3530 3531 3532

asc_docs_api.prototype.get_DocumentHeight = function()
{
    return Page_Height;
3533
};
3534

3535 3536 3537 3538 3539 3540 3541 3542
asc_docs_api.prototype.put_AddPageBreak = function()
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
        var Document = this.WordControl.m_oLogicDocument;

        if ( null === Document.Hyperlink_Check(false) )
        {
3543
            this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_AddPageBreak);
3544 3545 3546
            this.WordControl.m_oLogicDocument.Paragraph_Add( new ParaNewLine( break_Page ) );
        }
    }
3547
};
3548
asc_docs_api.prototype.Update_ParaInd = function( Ind ){
3549 3550 3551
	var FirstLine = 0,
		Left = 0,
		Right = 0;
3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586
	if ( "undefined" != typeof(Ind) )
	{
		if("undefined" != typeof(Ind.FirstLine))
		{
			FirstLine = Ind.FirstLine;
		}
		if("undefined" != typeof(Ind.Left))
		{
			Left = Ind.Left;
		}
		if("undefined" != typeof(Ind.Right))
		{
			Right = Ind.Right;
		}
	}

    var bIsUpdate = false;
    var _ruler = this.WordControl.m_oHorRuler;
    if (_ruler.m_dIndentLeft != Left)
    {
        _ruler.m_dIndentLeft = Left;
        bIsUpdate = true;
    }
    if (_ruler != (FirstLine + Left))
    {
        _ruler.m_dIndentLeftFirst = (FirstLine + Left);
        bIsUpdate = true;
    }
    if (_ruler.m_dIndentRight != Right)
    {
        _ruler.m_dIndentRight = Right;
        bIsUpdate = true;
    }
    if (bIsUpdate)
        this.WordControl.UpdateHorRuler();
3587
};
3588 3589 3590 3591 3592 3593
asc_docs_api.prototype.Internal_Update_Ind_FirstLine = function(FirstLine,Left){
	if (this.WordControl.m_oHorRuler.m_dIndentLeftFirst != (FirstLine + Left))
    {
        this.WordControl.m_oHorRuler.m_dIndentLeftFirst = (FirstLine + Left);
	    this.WordControl.UpdateHorRuler();
    }
3594
};
3595 3596 3597 3598 3599 3600
asc_docs_api.prototype.Internal_Update_Ind_Left = function(Left){
    if (this.WordControl.m_oHorRuler.m_dIndentLeft != Left)
    {
        this.WordControl.m_oHorRuler.m_dIndentLeft = Left;
        this.WordControl.UpdateHorRuler();
    }
3601
};
3602 3603 3604 3605 3606 3607
asc_docs_api.prototype.Internal_Update_Ind_Right = function(Right){
    if (this.WordControl.m_oHorRuler.m_dIndentRight != Right)
    {
        this.WordControl.m_oHorRuler.m_dIndentRight = Right;
        this.WordControl.UpdateHorRuler();
    }
3608
};
3609 3610 3611 3612 3613 3614 3615 3616

// "where" где нижний или верхний, align выравнивание
asc_docs_api.prototype.put_PageNum = function(where,align)
{
    if ( where >= 0 )
    {
        if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_None, { Type : changestype_2_HdrFtr }) )
        {
3617
            this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_AddPageNumToHdrFtr);
3618 3619 3620 3621 3622 3623 3624
            this.WordControl.m_oLogicDocument.Document_AddPageNum( where, align );
        }
    }
    else
    {
        if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
        {
3625
            this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_AddPageNumToCurrentPos);
3626 3627 3628
            this.WordControl.m_oLogicDocument.Document_AddPageNum( where, align );
        }
    }
3629
};
3630 3631 3632 3633 3634

asc_docs_api.prototype.put_HeadersAndFootersDistance = function(value)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_HdrFtr) )
    {
3635
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetHdrFtrDistance);
3636 3637
        this.WordControl.m_oLogicDocument.Document_SetHdrFtrDistance(value);
    }
3638
};
3639 3640 3641 3642 3643

asc_docs_api.prototype.HeadersAndFooters_DifferentFirstPage = function(isOn)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_HdrFtr) )
    {
3644
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetHdrFtrFirstPage);
3645
        this.WordControl.m_oLogicDocument.Document_SetHdrFtrFirstPage( isOn );
3646
    }
3647
};
Ilya.Kirillov's avatar
Ilya.Kirillov committed
3648

3649 3650 3651 3652
asc_docs_api.prototype.HeadersAndFooters_DifferentOddandEvenPage = function(isOn)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_HdrFtr) )
    {
3653
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetHdrFtrEvenAndOdd);
3654
        this.WordControl.m_oLogicDocument.Document_SetHdrFtrEvenAndOddHeaders( isOn );
3655
    }
3656
};
3657

Ilya.Kirillov's avatar
Ilya.Kirillov committed
3658 3659 3660 3661
asc_docs_api.prototype.HeadersAndFooters_LinkToPrevious = function(isOn)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_HdrFtr) )
    {
3662
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetHdrFtrLink);
Ilya.Kirillov's avatar
Ilya.Kirillov committed
3663 3664
        this.WordControl.m_oLogicDocument.Document_SetHdrFtrLink( isOn );
    }
3665
};
Ilya.Kirillov's avatar
Ilya.Kirillov committed
3666

3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677
/*структура для передачи настроек колонтитулов
	{
		Type : hdrftr_Footer (hdrftr_Header),
		Position : 12.5,
		DifferentFirst : true/false,
		DifferentEvenOdd : true/false,
	}
*/
/*callback*/
asc_docs_api.prototype.sync_DocSizeCallback = function(width,height){
	this.asc_fireCallback("asc_onDocSize",width,height);
3678
};
3679
asc_docs_api.prototype.sync_PageOrientCallback = function(isPortrait){
3680
    this.asc_fireCallback("asc_onPageOrient",isPortrait);
3681
};
3682 3683 3684 3685 3686
asc_docs_api.prototype.sync_HeadersAndFootersPropCallback = function(hafProp)
{
    if ( true === hafProp )
        hafProp.Locked = true;

3687
    this.SelectedObjectsStack[this.SelectedObjectsStack.length] = new asc_CSelectedObject( c_oAscTypeSelectElement.Header, new CHeaderProp( hafProp ) );
3688
};
3689 3690 3691

/*----------------------------------------------------------------*/
/*functions for working with table*/
3692
asc_docs_api.prototype.put_Table = function(col,row)
3693
{
3694
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Document_Content_Add) )
3695
    {
3696
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_AddTable);
3697
        this.WordControl.m_oLogicDocument.Add_InlineTable(col,row);
3698
    }
3699
};
3700 3701 3702 3703
asc_docs_api.prototype.addRowAbove = function(count)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Table_Properties) )
    {
3704
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_TableAddRowAbove);
3705 3706
        this.WordControl.m_oLogicDocument.Table_AddRow(true);
    }
3707
};
3708 3709 3710 3711
asc_docs_api.prototype.addRowBelow = function(count)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Table_Properties) )
    {
3712
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_TableAddRowBelow);
3713 3714
        this.WordControl.m_oLogicDocument.Table_AddRow(false);
    }
3715
};
3716 3717 3718 3719
asc_docs_api.prototype.addColumnLeft = function(count)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Table_Properties) )
    {
3720
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_TableAddColumnLeft);
3721 3722
        this.WordControl.m_oLogicDocument.Table_AddCol(true);
    }
3723
};
3724 3725 3726 3727
asc_docs_api.prototype.addColumnRight = function(count)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Table_Properties) )
    {
3728
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_TableAddColumnRight);
3729 3730
        this.WordControl.m_oLogicDocument.Table_AddCol(false);
    }
3731
};
3732 3733 3734 3735
asc_docs_api.prototype.remRow = function()
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Table_RemoveCells) )
    {
3736
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_TableRemoveRow);
3737 3738
        this.WordControl.m_oLogicDocument.Table_RemoveRow();
    }
3739
};
3740 3741 3742 3743
asc_docs_api.prototype.remColumn = function()
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Table_RemoveCells) )
    {
3744
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_TableRemoveColumn);
3745 3746
        this.WordControl.m_oLogicDocument.Table_RemoveCol();
    }
3747
};
3748 3749 3750 3751
asc_docs_api.prototype.remTable = function()
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Table_RemoveCells) )
    {
3752
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_RemoveTable);
3753 3754
        this.WordControl.m_oLogicDocument.Table_RemoveTable();
    }
3755
};
3756 3757 3758
asc_docs_api.prototype.selectRow = function()
{
    this.WordControl.m_oLogicDocument.Table_Select( c_oAscTableSelectionType.Row );
3759
};
3760 3761 3762
asc_docs_api.prototype.selectColumn = function()
{
    this.WordControl.m_oLogicDocument.Table_Select( c_oAscTableSelectionType.Column );
3763
};
3764 3765 3766
asc_docs_api.prototype.selectCell = function()
{
    this.WordControl.m_oLogicDocument.Table_Select( c_oAscTableSelectionType.Cell );
3767
};
3768 3769 3770
asc_docs_api.prototype.selectTable = function()
{
    this.WordControl.m_oLogicDocument.Table_Select( c_oAscTableSelectionType.Table );
3771
};
3772 3773
asc_docs_api.prototype.setColumnWidth = function(width){

3774
};
3775 3776
asc_docs_api.prototype.setRowHeight = function(height){

3777
};
3778 3779
asc_docs_api.prototype.set_TblDistanceFromText = function(left,top,right,bottom){

3780
};
3781 3782 3783
asc_docs_api.prototype.CheckBeforeMergeCells = function()
{
    return this.WordControl.m_oLogicDocument.Table_CheckMerge();
3784
};
3785 3786 3787
asc_docs_api.prototype.CheckBeforeSplitCells = function()
{
    return this.WordControl.m_oLogicDocument.Table_CheckSplit();
3788
};
3789 3790 3791 3792
asc_docs_api.prototype.MergeCells = function()
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Table_Properties) )
    {
3793
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_MergeTableCells);
3794 3795
        this.WordControl.m_oLogicDocument.Table_MergeCells();
    }
3796
};
3797 3798 3799 3800
asc_docs_api.prototype.SplitCell = function(Cols, Rows)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Table_Properties) )
    {
3801
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SplitTableCells);
3802 3803
        this.WordControl.m_oLogicDocument.Table_SplitCell(Cols, Rows);
    }
3804
};
3805 3806
asc_docs_api.prototype.widthTable = function(width){

3807
};
3808 3809
asc_docs_api.prototype.put_CellsMargin = function(left,top,right,bottom){

3810
};
3811 3812
asc_docs_api.prototype.set_TblWrap = function(type){

3813
};
3814 3815
asc_docs_api.prototype.set_TblIndentLeft = function(spacing){

3816
};
3817 3818
asc_docs_api.prototype.set_Borders = function(typeBorders,size,Color){//если size == 0 то границы нет.

3819
};
3820 3821
asc_docs_api.prototype.set_TableBackground = function(Color){

3822
};
3823 3824 3825 3826 3827 3828 3829
asc_docs_api.prototype.set_AlignCell = function(align){// c_oAscAlignType.RIGHT, c_oAscAlignType.LEFT, c_oAscAlignType.CENTER
	switch(align)
	{
		case c_oAscAlignType.LEFT : break;
		case c_oAscAlignType.CENTER : break;
		case c_oAscAlignType.RIGHT : break;
	}
3830
};
3831 3832 3833 3834 3835 3836 3837
asc_docs_api.prototype.set_TblAlign = function(align){// c_oAscAlignType.RIGHT, c_oAscAlignType.LEFT, c_oAscAlignType.CENTER
	switch(align)
	{
		case c_oAscAlignType.LEFT : break;
		case c_oAscAlignType.CENTER : break;
		case c_oAscAlignType.RIGHT : break;
	}
3838
};
3839 3840 3841 3842
asc_docs_api.prototype.set_SpacingBetweenCells = function(isOn,spacing){// c_oAscAlignType.RIGHT, c_oAscAlignType.LEFT, c_oAscAlignType.CENTER
	if(isOn){

	}
3843
};
3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860

// CBackground
// Value : тип заливки(прозрачная или нет),
// Color : { r : 0, g : 0, b : 0 }
function CBackground (obj)
{
	if (obj)
	{
		this.Color = (undefined != obj.Color && null != obj.Color) ? CreateAscColorCustom(obj.Color.r, obj.Color.g, obj.Color.b) : null;
		this.Value = (undefined != obj.Value) ? obj.Value : null;
	}
	else
	{
		this.Color = CreateAscColorCustom(0, 0, 0);
		this.Value = 1;
	}
}
3861 3862 3863 3864
CBackground.prototype.get_Color = function (){return this.Color;};
CBackground.prototype.put_Color = function (v){this.Color = (v) ? v: null;};
CBackground.prototype.get_Value = function (){return this.Value;};
CBackground.prototype.put_Value = function (v){this.Value = v;};
3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883

function CTablePositionH(obj)
{
    if ( obj )
    {
        this.RelativeFrom = ( undefined === obj.RelativeFrom ) ? c_oAscHAnchor.Margin : obj.RelativeFrom;
        this.UseAlign     = ( undefined === obj.UseAlign     ) ? false                : obj.UseAlign;
        this.Align        = ( undefined === obj.Align        ) ? undefined            : obj.Align;
        this.Value        = ( undefined === obj.Value        ) ? 0                    : obj.Value;
    }
    else
    {
        this.RelativeFrom = c_oAscHAnchor.Column;
        this.UseAlign     = false;
        this.Align        = undefined;
        this.Value        = 0;
    }
}

3884 3885 3886 3887 3888 3889 3890 3891
CTablePositionH.prototype.get_RelativeFrom = function()  { return this.RelativeFrom; };
CTablePositionH.prototype.put_RelativeFrom = function(v) { this.RelativeFrom = v; };
CTablePositionH.prototype.get_UseAlign = function()  { return this.UseAlign; };
CTablePositionH.prototype.put_UseAlign = function(v) { this.UseAlign = v; };
CTablePositionH.prototype.get_Align = function()  { return this.Align; };
CTablePositionH.prototype.put_Align = function(v) { this.Align = v; };
CTablePositionH.prototype.get_Value = function()  { return this.Value; };
CTablePositionH.prototype.put_Value = function(v) { this.Value = v; };
3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910

function CTablePositionV(obj)
{
    if ( obj )
    {
        this.RelativeFrom = ( undefined === obj.RelativeFrom ) ? c_oAscVAnchor.Text : obj.RelativeFrom;
        this.UseAlign     = ( undefined === obj.UseAlign     ) ? false              : obj.UseAlign;
        this.Align        = ( undefined === obj.Align        ) ? undefined          : obj.Align;
        this.Value        = ( undefined === obj.Value        ) ? 0                  : obj.Value;
    }
    else
    {
        this.RelativeFrom = c_oAscVAnchor.Text;
        this.UseAlign     = false;
        this.Align        = undefined;
        this.Value        = 0;
    }
}

3911 3912 3913 3914 3915 3916 3917 3918
CTablePositionV.prototype.get_RelativeFrom = function()  { return this.RelativeFrom; };
CTablePositionV.prototype.put_RelativeFrom = function(v) { this.RelativeFrom = v; };
CTablePositionV.prototype.get_UseAlign = function()  { return this.UseAlign; };
CTablePositionV.prototype.put_UseAlign = function(v) { this.UseAlign = v; };
CTablePositionV.prototype.get_Align = function()  { return this.Align; };
CTablePositionV.prototype.put_Align = function(v) { this.Align = v; };
CTablePositionV.prototype.get_Value = function()  { return this.Value; };
CTablePositionV.prototype.put_Value = function(v) { this.Value = v; };
3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939

function CTablePropLook(obj)
{
    this.FirstCol = false;
    this.FirstRow = false;
    this.LastCol  = false;
    this.LastRow  = false;
    this.BandHor  = false;
    this.BandVer  = false;

    if ( obj )
    {
        this.FirstCol = ( undefined === obj.m_bFirst_Col ? false : obj.m_bFirst_Col );
        this.FirstRow = ( undefined === obj.m_bFirst_Row ? false : obj.m_bFirst_Row );
        this.LastCol  = ( undefined === obj.m_bLast_Col  ? false : obj.m_bLast_Col );
        this.LastRow  = ( undefined === obj.m_bLast_Row  ? false : obj.m_bLast_Row );
        this.BandHor  = ( undefined === obj.m_bBand_Hor  ? false : obj.m_bBand_Hor );
        this.BandVer  = ( undefined === obj.m_bBand_Ver  ? false : obj.m_bBand_Ver );
    }
}

3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951
CTablePropLook.prototype.get_FirstCol = function() {return this.FirstCol;};
CTablePropLook.prototype.put_FirstCol = function(v) {this.FirstCol = v;};
CTablePropLook.prototype.get_FirstRow = function() {return this.FirstRow;};
CTablePropLook.prototype.put_FirstRow = function(v) {this.FirstRow = v;};
CTablePropLook.prototype.get_LastCol = function() {return this.LastCol;};
CTablePropLook.prototype.put_LastCol = function(v) {this.LastCol = v;};
CTablePropLook.prototype.get_LastRow = function() {return this.LastRow;};
CTablePropLook.prototype.put_LastRow = function(v) {this.LastRow = v;};
CTablePropLook.prototype.get_BandHor = function() {return this.BandHor;};
CTablePropLook.prototype.put_BandHor = function(v) {this.BandHor = v;};
CTablePropLook.prototype.get_BandVer = function() {return this.BandVer;};
CTablePropLook.prototype.put_BandVer = function(v) {this.BandVer = v;};
3952 3953 3954 3955 3956 3957 3958 3959 3960 3961

function CTableProp (tblProp)
{
	if (tblProp)
	{
        this.CanBeFlow = (undefined != tblProp.CanBeFlow ? tblProp.CanBeFlow : false );
        this.CellSelect = (undefined != tblProp.CellSelect ? tblProp.CellSelect : false );
        this.CellSelect = (undefined != tblProp.CellSelect) ? tblProp.CellSelect : false;
		this.TableWidth = (undefined != tblProp.TableWidth) ? tblProp.TableWidth : null;
		this.TableSpacing = (undefined != tblProp.TableSpacing) ? tblProp.TableSpacing : null;
3962
		this.TableDefaultMargins = (undefined != tblProp.TableDefaultMargins && null != tblProp.TableDefaultMargins) ? new asc_CPaddings (tblProp.TableDefaultMargins) : null;
3963 3964 3965 3966 3967 3968 3969

		this.CellMargins = (undefined != tblProp.CellMargins && null != tblProp.CellMargins) ? new CMargins (tblProp.CellMargins) : null;

		this.TableAlignment = (undefined != tblProp.TableAlignment) ? tblProp.TableAlignment : null;
		this.TableIndent = (undefined != tblProp.TableIndent) ? tblProp.TableIndent : null;
		this.TableWrappingStyle = (undefined != tblProp.TableWrappingStyle) ? tblProp.TableWrappingStyle : null;

3970
		this.TablePaddings = (undefined != tblProp.TablePaddings && null != tblProp.TablePaddings) ? new asc_CPaddings (tblProp.TablePaddings) : null;
3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986

		this.TableBorders = (undefined != tblProp.TableBorders && null != tblProp.TableBorders) ? new CBorders (tblProp.TableBorders) : null;
		this.CellBorders = (undefined != tblProp.CellBorders && null != tblProp.CellBorders) ? new CBorders (tblProp.CellBorders) : null;
		this.TableBackground = (undefined != tblProp.TableBackground && null != tblProp.TableBackground) ? new CBackground (tblProp.TableBackground) : null;
		this.CellsBackground = (undefined != tblProp.CellsBackground && null != tblProp.CellsBackground) ? new CBackground (tblProp.CellsBackground) : null;
		this.Position = (undefined != tblProp.Position && null != tblProp.Position) ? new CPosition (tblProp.Position) : null;
        this.PositionH = ( undefined != tblProp.PositionH && null != tblProp.PositionH ) ? new CTablePositionH(tblProp.PositionH) : undefined;
        this.PositionV = ( undefined != tblProp.PositionV && null != tblProp.PositionV ) ? new CTablePositionV(tblProp.PositionV) : undefined;
        this.Internal_Position = ( undefined != tblProp.Internal_Position ) ? tblProp.Internal_Position : undefined;

        this.ForSelectedCells = (undefined != tblProp.ForSelectedCells) ? tblProp.ForSelectedCells : true;
        this.TableStyle = (undefined != tblProp.TableStyle) ? tblProp.TableStyle : null;
        this.TableLook = (undefined != tblProp.TableLook) ? new CTablePropLook(tblProp.TableLook) : null;
        this.RowsInHeader = (undefined != tblProp.RowsInHeader) ? tblProp.RowsInHeader : 0;
        this.CellsVAlign = (undefined != tblProp.CellsVAlign) ? tblProp.CellsVAlign :c_oAscVertAlignJc.Top;
        this.AllowOverlap = (undefined != tblProp.AllowOverlap) ? tblProp.AllowOverlap : undefined;
3987
        this.TableLayout  = tblProp.TableLayout;
3988 3989 3990 3991 3992 3993 3994 3995 3996
        this.Locked = (undefined != tblProp.Locked) ? tblProp.Locked : false;
	}
	else
	{
		//Все свойства класса CTableProp должны быть undefined если они не изменялись
        //this.CanBeFlow = false;
        this.CellSelect = false; //обязательное свойство
		/*this.TableWidth = null;
		this.TableSpacing = null;
3997
		this.TableDefaultMargins = new asc_CPaddings ();
3998 3999 4000 4001 4002 4003 4004

		this.CellMargins = new CMargins ();

		this.TableAlignment = 0;
		this.TableIndent = 0;
		this.TableWrappingStyle = c_oAscWrapStyle.Inline;

4005
		this.TablePaddings = new asc_CPaddings ();
4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017

		this.TableBorders = new CBorders ();
		this.CellBorders = new CBorders ();
		this.TableBackground = new CBackground ();
		this.CellsBackground = new CBackground ();;
		this.Position = new CPosition ();
		this.ForSelectedCells = true;*/

        this.Locked = false;
	}
}

4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052
CTableProp.prototype.get_Width = function (){return this.TableWidth;};
CTableProp.prototype.put_Width = function (v){this.TableWidth = v;};
CTableProp.prototype.get_Spacing = function (){return this.TableSpacing;};
CTableProp.prototype.put_Spacing = function (v){this.TableSpacing = v;};
CTableProp.prototype.get_DefaultMargins = function (){return this.TableDefaultMargins;};
CTableProp.prototype.put_DefaultMargins = function (v){this.TableDefaultMargins = v;};
CTableProp.prototype.get_CellMargins = function (){return this.CellMargins;};
CTableProp.prototype.put_CellMargins = function (v){ this.CellMargins = v;};
CTableProp.prototype.get_TableAlignment = function (){return this.TableAlignment;};
CTableProp.prototype.put_TableAlignment = function (v){this.TableAlignment = v;};
CTableProp.prototype.get_TableIndent = function (){return this.TableIndent;};
CTableProp.prototype.put_TableIndent = function (v){this.TableIndent = v;};
CTableProp.prototype.get_TableWrap = function (){return this.TableWrappingStyle;};
CTableProp.prototype.put_TableWrap = function (v){this.TableWrappingStyle = v;};
CTableProp.prototype.get_TablePaddings = function (){return this.TablePaddings;};
CTableProp.prototype.put_TablePaddings = function (v){this.TablePaddings = v;};
CTableProp.prototype.get_TableBorders = function (){return this.TableBorders;};
CTableProp.prototype.put_TableBorders = function (v){this.TableBorders = v;};
CTableProp.prototype.get_CellBorders = function (){return this.CellBorders;};
CTableProp.prototype.put_CellBorders = function (v){this.CellBorders = v;};
CTableProp.prototype.get_TableBackground = function (){return this.TableBackground;};
CTableProp.prototype.put_TableBackground = function (v){this.TableBackground = v;};
CTableProp.prototype.get_CellsBackground = function (){return this.CellsBackground;};
CTableProp.prototype.put_CellsBackground = function (v){this.CellsBackground = v;};
CTableProp.prototype.get_Position = function (){return this.Position;};
CTableProp.prototype.put_Position = function (v){this.Position = v;};
CTableProp.prototype.get_PositionH = function(){return this.PositionH;};
CTableProp.prototype.put_PositionH = function(v){this.PositionH = v;};
CTableProp.prototype.get_PositionV = function(){return this.PositionV;};
CTableProp.prototype.put_PositionV = function(v){this.PositionV = v;};
CTableProp.prototype.get_Value_X = function(RelativeFrom) { if ( undefined != this.Internal_Position ) return this.Internal_Position.Calculate_X_Value(RelativeFrom);  return 0; };
CTableProp.prototype.get_Value_Y = function(RelativeFrom) { if ( undefined != this.Internal_Position ) return this.Internal_Position.Calculate_Y_Value(RelativeFrom);  return 0; };
CTableProp.prototype.get_ForSelectedCells = function (){return this.ForSelectedCells;};
CTableProp.prototype.put_ForSelectedCells = function (v){this.ForSelectedCells = v;};
CTableProp.prototype.put_CellSelect = function(v){this.CellSelect = v;};
4053
CTableProp.prototype.get_CellSelect = function(){return this.CellSelect};
4054
CTableProp.prototype.get_CanBeFlow = function(){return this.CanBeFlow;};
4055 4056
CTableProp.prototype.get_RowsInHeader = function(){return this.RowsInHeader;};
CTableProp.prototype.put_RowsInHeader = function(v){this.RowsInHeader = v;};
4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067
CTableProp.prototype.get_Locked = function() { return this.Locked; };
CTableProp.prototype.get_CellsVAlign = function() { return this.CellsVAlign; };
CTableProp.prototype.put_CellsVAlign = function(v){ this.CellsVAlign = v; };
CTableProp.prototype.get_TableLook = function() {return this.TableLook;};
CTableProp.prototype.put_TableLook = function(v){this.TableLook = v;};
CTableProp.prototype.get_TableStyle = function() {return this.TableStyle;};
CTableProp.prototype.put_TableStyle = function(v){this.TableStyle = v;};
CTableProp.prototype.get_AllowOverlap = function() {return this.AllowOverlap;};
CTableProp.prototype.put_AllowOverlap = function(v){this.AllowOverlap = v;};
CTableProp.prototype.get_TableLayout = function() {return this.TableLayout;};
CTableProp.prototype.put_TableLayout = function(v){this.TableLayout = v;};
4068 4069 4070 4071 4072

function CBorders (obj)
{
	if (obj)
	{
4073 4074 4075 4076 4077 4078
		this.Left = (undefined != obj.Left && null != obj.Left) ? new asc_CTextBorder (obj.Left) : null;
		this.Top = (undefined != obj.Top && null != obj.Top) ? new asc_CTextBorder (obj.Top) : null;
		this.Right = (undefined != obj.Right && null != obj.Right) ? new asc_CTextBorder (obj.Right) : null;
		this.Bottom = (undefined != obj.Bottom && null != obj.Bottom) ? new asc_CTextBorder (obj.Bottom) : null;
		this.InsideH = (undefined != obj.InsideH && null != obj.InsideH) ? new asc_CTextBorder (obj.InsideH) : null;
		this.InsideV = (undefined != obj.InsideV && null != obj.InsideV) ? new asc_CTextBorder (obj.InsideV) : null;
4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090
	}
	//Все свойства класса CBorders должны быть undefined если они не изменялись
	/*else
	{
		this.Left = null;
		this.Top = null;
		this.Right = null;
		this.Bottom = null;
		this.InsideH = null;
		this.InsideV = null;
	}*/
}
4091
CBorders.prototype.get_Left = function(){return this.Left; };
4092
CBorders.prototype.put_Left = function(v){this.Left = (v) ? new asc_CTextBorder (v) : null;};
4093
CBorders.prototype.get_Top = function(){return this.Top; };
4094
CBorders.prototype.put_Top = function(v){this.Top = (v) ? new asc_CTextBorder (v) : null;};
4095
CBorders.prototype.get_Right = function(){return this.Right; };
4096
CBorders.prototype.put_Right = function(v){this.Right = (v) ? new asc_CTextBorder (v) : null;};
4097
CBorders.prototype.get_Bottom = function(){return this.Bottom; };
4098
CBorders.prototype.put_Bottom = function(v){this.Bottom = (v) ? new asc_CTextBorder (v) : null;};
4099
CBorders.prototype.get_InsideH = function(){return this.InsideH; };
4100
CBorders.prototype.put_InsideH = function(v){this.InsideH = (v) ? new asc_CTextBorder (v) : null;};
4101
CBorders.prototype.get_InsideV = function(){return this.InsideV; };
4102
CBorders.prototype.put_InsideV = function(v){this.InsideV = (v) ? new asc_CTextBorder (v) : null;};
4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124


// CMargins
function CMargins (obj)
{
	if (obj)
	{
		this.Left = (undefined != obj.Left) ? obj.Left : null;
		this.Right = (undefined != obj.Right) ? obj.Right : null;
		this.Top = (undefined != obj.Top) ? obj.Top : null;
		this.Bottom = (undefined != obj.Bottom) ? obj.Bottom : null;
		this.Flag = (undefined != obj.Flag) ? obj.Flag : null;
	}
	else
	{
		this.Left = null;
		this.Right = null;
		this.Top = null;
		this.Bottom = null;
		this.Flag = null;
	}
}
4125 4126 4127 4128 4129 4130 4131 4132 4133 4134
CMargins.prototype.get_Left = function(){return this.Left; };
CMargins.prototype.put_Left = function(v){this.Left = v;};
CMargins.prototype.get_Right = function(){return this.Right; };
CMargins.prototype.put_Right = function(v){this.Right = v;};
CMargins.prototype.get_Top = function(){return this.Top; };
CMargins.prototype.put_Top = function(v){this.Top = v;};
CMargins.prototype.get_Bottom = function(){return this.Bottom; };
CMargins.prototype.put_Bottom = function(v){this.Bottom = v;};
CMargins.prototype.get_Flag = function(){return this.Flag; };
CMargins.prototype.put_Flag = function(v){this.Flag = v;};
4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298

/*
	{
	    TableWidth   : null - галочка убрана, либо заданное значение в мм
	    TableSpacing : null - галочка убрана, либо заданное значение в мм

	    TableDefaultMargins :  // маргины для всей таблицы(значение по умолчанию)
	    {
	        Left   : 1.9,
	        Right  : 1.9,
	        Top    : 0,
	        Bottom : 0
	    }

	    CellMargins :
        {
            Left   : 1.9, (null - неопределенное значение)
            Right  : 1.9, (null - неопределенное значение)
            Top    : 0,   (null - неопределенное значение)
            Bottom : 0,   (null - неопределенное значение)
            Flag   : 0 - У всех выделенных ячеек значение берется из TableDefaultMargins
                     1 - У выделенных ячеек есть ячейки с дефолтовыми значениями, и есть со своими собственными
                     2 - У всех ячеек свои собственные значения
        }

        TableAlignment : 0, 1, 2 (слева, по центру, справа)
        TableIndent : значение в мм,
        TableWrappingStyle : 0, 1 (inline, flow)
        TablePaddings:
        {
             Left   : 3.2,
             Right  : 3.2,
             Top    : 0,
             Bottom : 0
        }

        TableBorders : // границы таблицы
        {
            Bottom :
            {
                Color : { r : 0, g : 0, b : 0 },
                Value : border_Single,
                Size  : 0.5 * g_dKoef_pt_to_mm
				Space :
            },

            Left :
            {
                Color : { r : 0, g : 0, b : 0 },
                Value : border_Single,
                Size  : 0.5 * g_dKoef_pt_to_mm
				Space :
            },

            Right :
            {
                Color : { r : 0, g : 0, b : 0 },
                Value : border_Single,
                Size  : 0.5 * g_dKoef_pt_to_mm
				Space :
            },

            Top :
            {
                Color : { r : 0, g : 0, b : 0 },
                Value : border_Single,
                Size  : 0.5 * g_dKoef_pt_to_mm
				Space :
            },

            InsideH :
            {
                Color : { r : 0, g : 0, b : 0 },
                Value : border_Single,
                Size  : 0.5 * g_dKoef_pt_to_mm
				Space :
            },

            InsideV :
            {
                Color : { r : 0, g : 0, b : 0 },
                Value : border_Single,
                Size  : 0.5 * g_dKoef_pt_to_mm
				Space :
            }
        }

        CellBorders : // границы выделенных ячеек
        {
			ForSelectedCells : true,

            Bottom :
            {
                Color : { r : 0, g : 0, b : 0 },
                Value : border_Single,
                Size  : 0.5 * g_dKoef_pt_to_mm
				Space :
            },

            Left :
            {
                Color : { r : 0, g : 0, b : 0 },
                Value : border_Single,
                Size  : 0.5 * g_dKoef_pt_to_mm
				Space :
            },

            Right :
            {
                Color : { r : 0, g : 0, b : 0 },
                Value : border_Single,
                Size  : 0.5 * g_dKoef_pt_to_mm
				Space :
            },

            Top :
            {
                Color : { r : 0, g : 0, b : 0 },
                Value : border_Single,
                Size  : 0.5 * g_dKoef_pt_to_mm
				Space :
            },

            InsideH : // данного элемента может не быть, если у выделенных ячеек
                      // нет горизонтальных внутренних границ
            {
                Color : { r : 0, g : 0, b : 0 },
                 Value : border_Single,
                Size  : 0.5 * g_dKoef_pt_to_mm
				Space :
            },

            InsideV : // данного элемента может не быть, если у выделенных ячеек
                      // нет вертикальных внутренних границ
            {
                Color : { r : 0, g : 0, b : 0 },
                Value : border_Single,
                Size  : 0.5 * g_dKoef_pt_to_mm
				Space :
            }
        }

        TableBackground :
        {
            Value : тип заливки(прозрачная или нет),
            Color : { r : 0, g : 0, b : 0 }
        }
        CellsBackground : null если заливка не определена для выделенных ячеек
        {
            Value : тип заливки(прозрачная или нет),
            Color : { r : 0, g : 0, b : 0 }
        }

		Position:
		{
			X:0,
			Y:0
		}
	}
*/
asc_docs_api.prototype.tblApply = function(obj)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Table_Properties) )
    {
Anna.Pavlova's avatar
Anna.Pavlova committed
4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330
        if(obj.CellBorders)
        {
            if(obj.CellBorders.Left && obj.CellBorders.Left.Color)
            {
                obj.CellBorders.Left.Unifill = CreateUnifillFromAscColor(obj.CellBorders.Left.Color);
            }
            if(obj.CellBorders.Top && obj.CellBorders.Top.Color)
            {
                obj.CellBorders.Top.Unifill = CreateUnifillFromAscColor(obj.CellBorders.Top.Color);
            }
            if(obj.CellBorders.Right && obj.CellBorders.Right.Color)
            {
                obj.CellBorders.Right.Unifill = CreateUnifillFromAscColor(obj.CellBorders.Right.Color);
            }
            if(obj.CellBorders.Bottom && obj.CellBorders.Bottom.Color)
            {
                obj.CellBorders.Bottom.Unifill = CreateUnifillFromAscColor(obj.CellBorders.Bottom.Color);
            }
            if(obj.CellBorders.InsideH && obj.CellBorders.InsideH.Color)
            {
                obj.CellBorders.InsideH.Unifill = CreateUnifillFromAscColor(obj.CellBorders.InsideH.Color);
            }
            if(obj.CellBorders.InsideV && obj.CellBorders.InsideV.Color)
            {
                obj.CellBorders.InsideV.Unifill = CreateUnifillFromAscColor(obj.CellBorders.InsideV.Color);
            }
        }
        if(obj.CellsBackground && obj.CellsBackground.Color)
        {
            obj.CellsBackground.Unifill = CreateUnifillFromAscColor(obj.CellsBackground.Color);
        }

4331
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_ApplyTablePr);
4332 4333
        this.WordControl.m_oLogicDocument.Set_TableProps(obj);
    }
4334
};
4335 4336 4337
/*callbacks*/
asc_docs_api.prototype.sync_AddTableCallback = function(){
	this.asc_fireCallback("asc_onAddTable");
4338
};
4339 4340
asc_docs_api.prototype.sync_AlignCellCallback = function(align){
	this.asc_fireCallback("asc_onAlignCell",align);
4341
};
4342 4343 4344 4345 4346 4347
asc_docs_api.prototype.sync_TblPropCallback = function(tblProp)
{
    //if ( true === CollaborativeEditing.Get_GlobalLock() )
    //    tblProp.Locked = true;

    // TODO: вызвать функцию asc_onInitTableTemplatesв зависимости от TableLook
4348 4349 4350 4351 4352 4353 4354
    if(tblProp.CellsBackground && tblProp.CellsBackground.Unifill)
    {
        var LogicDocument = this.WordControl.m_oLogicDocument;
        tblProp.CellsBackground.Unifill.check(LogicDocument.Get_Theme(), LogicDocument.Get_ColorMap());
        var RGBA = tblProp.CellsBackground.Unifill.getRGBAColor();
        tblProp.CellsBackground.Color = new CDocumentColor(RGBA.R, RGBA.G, RGBA.B, false);
    }
4355
    this.SelectedObjectsStack[this.SelectedObjectsStack.length] = new asc_CSelectedObject( c_oAscTypeSelectElement.Table, new CTableProp( tblProp ));
4356
};
4357 4358
asc_docs_api.prototype.sync_TblWrapStyleChangedCallback = function(style){
	this.asc_fireCallback("asc_onTblWrapStyleChanged",style);
4359
};
4360 4361
asc_docs_api.prototype.sync_TblAlignChangedCallback = function(style){
	this.asc_fireCallback("asc_onTblAlignChanged",style);
4362
};
4363 4364 4365 4366 4367 4368 4369

/*----------------------------------------------------------------*/
/*functions for working with images*/
asc_docs_api.prototype.ChangeImageFromFile = function()
{
    this.isImageChangeUrl = true;
    this.AddImage();
4370
};
4371 4372 4373 4374
asc_docs_api.prototype.ChangeShapeImageFromFile = function()
{
    this.isShapeImageChangeUrl = true;
    this.AddImage();
4375
};
4376 4377

asc_docs_api.prototype.AddImage = function(){
4378
	var t = this;
4379
	ShowImageFileDialog(this.documentId, this.documentUserId, function(error, files){
4380 4381
		t._uploadCallback(error, files);
	}, function (error) {
4382
		if (c_oAscError.ID.No !== error)
4383 4384 4385
			t.asc_fireCallback("asc_onError", error, c_oAscError.Level.NoCritical);
		t.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.UploadImage);
	});
4386
};
4387 4388
asc_docs_api.prototype._uploadCallback = function(error, files){
	var t = this;
4389
	if (c_oAscError.ID.No !== error) {
4390 4391 4392
		t.sync_ErrorCallback(error, c_oAscError.Level.NoCritical);
	} else {
		t.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.UploadImage);
4393
		UploadImageFiles(files, this.documentId, this.documentUserId, function (error, url) {
4394
			if (c_oAscError.ID.No !== error)
4395 4396 4397 4398 4399 4400
				t.sync_ErrorCallback(error, c_oAscError.Level.NoCritical);
			else
				t.AddImageUrl(url);
			t.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.UploadImage);
		});
	}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
4401
};
4402 4403
asc_docs_api.prototype.AddImageUrl2 = function(url)
{
4404
    this.AddImageUrl(getFullImageSrc2(url));
4405
};
4406 4407 4408 4409 4410

asc_docs_api.prototype.AddImageUrl = function(url, imgProp)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
4411
		if(g_oDocumentUrls.getLocal(url))
4412 4413 4414 4415 4416
		{
			this.AddImageUrlAction(url, imgProp);
		}
		else
		{
4417
			var rData = {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
4418
				"id": this.documentId,
4419
				"userid": this.documentUserId,
4420
				"vkey": this.documentVKey,
4421
				"c": "imgurl",
4422
				"saveindex": g_oDocumentUrls.getMaxIndex(),
4423 4424
				"data": url};

4425
			var t = this;
4426
			this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.UploadImage);
4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456
			this.fCurCallback = function(input) {
				if(null != input && "imgurl" == input["type"]){
					if("ok" ==input["status"]) {
						var data = input["data"];
						var urls = {};
						var firstUrl;
						for(var i = 0; i < data.length; ++i){
							var elem = data[i];
							if(elem.url){
								if(!firstUrl){
									firstUrl = elem.url;
								}
								urls[elem.path] = elem.url;
							}
						}
						g_oDocumentUrls.addUrls(urls);
						if(firstUrl) {
							t.AddImageUrlAction(firstUrl, imgProp);
						} else {
							t.asc_fireCallback("asc_onError",c_oAscError.ID.Unknown,c_oAscError.Level.NoCritical);
						}
					} else {
						t.asc_fireCallback("asc_onError", g_fMapAscServerErrorToAscError(parseInt(input["data"])), c_oAscError.Level.NoCritical);
					}
				} else {
					t.asc_fireCallback("asc_onError",c_oAscError.ID.Unknown,c_oAscError.Level.NoCritical);
				}
				t.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.UploadImage);
			};
			sendCommand2(this, null, rData );
4457 4458
		}
    }
4459
};
4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473
asc_docs_api.prototype.AddImageUrlAction = function(url, imgProp)
{
    var _image = this.ImageLoader.LoadImage(url, 1);
    if (null != _image)
    {
        var _w = Math.max(1, Page_Width - (X_Left_Margin + X_Right_Margin));
        var _h = Math.max(1, Page_Height - (Y_Top_Margin + Y_Bottom_Margin));
        if (_image.Image != null)
        {
            var __w = Math.max(parseInt(_image.Image.width * g_dKoef_pix_to_mm), 1);
            var __h = Math.max(parseInt(_image.Image.height * g_dKoef_pix_to_mm), 1);
            _w = Math.max(5, Math.min(_w, __w));
            _h = Math.max(5, Math.min(parseInt(_w * __h / __w)));
        }
4474
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_AddImageUrl);
4475 4476 4477 4478

        var src = _image.src;
        if (this.isShapeImageChangeUrl)
        {
4479 4480
            var AscShapeProp = new asc_CShapeProperty();
            AscShapeProp.fill = new asc_CShapeFill();
4481
            AscShapeProp.fill.type = c_oAscFill.FILL_TYPE_BLIP;
4482 4483 4484
            AscShapeProp.fill.fill = new asc_CFillBlip();
            AscShapeProp.fill.fill.asc_putUrl(src);
            this.ImgApply(new asc_CImgProperty({ShapeProperties:AscShapeProp}));
4485 4486 4487 4488
            this.isShapeImageChangeUrl = false;
        }
        else if (this.isImageChangeUrl)
        {
4489
            var AscImageProp = new asc_CImgProperty();
4490 4491 4492 4493 4494 4495
            AscImageProp.ImageUrl = src;
            this.ImgApply(AscImageProp);
            this.isImageChangeUrl = false;
        }
        else
        {
4496 4497 4498 4499
			var imageLocal = g_oDocumentUrls.getImageLocal(src);
			if(imageLocal){
				src = imageLocal;
			}
4500 4501 4502 4503 4504 4505 4506 4507 4508

            if (undefined === imgProp || undefined === imgProp.WrappingStyle || 0 == imgProp.WrappingStyle)
                this.WordControl.m_oLogicDocument.Add_InlineImage(_w, _h, src);
            else
                this.WordControl.m_oLogicDocument.Add_InlineImage(_w, _h, src, null, true);
        }
    }
    else
    {
Oleg.Korshul's avatar
Oleg.Korshul committed
4509
        this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.LoadImage);
4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520
        this.asyncImageEndLoaded2 = function(_image)
        {
            var _w = Math.max(1, Page_Width - (X_Left_Margin + X_Right_Margin));
            var _h = Math.max(1, Page_Height - (Y_Top_Margin + Y_Bottom_Margin));
            if (_image.Image != null)
            {
                var __w = Math.max(parseInt(_image.Image.width * g_dKoef_pix_to_mm), 1);
                var __h = Math.max(parseInt(_image.Image.height * g_dKoef_pix_to_mm), 1);
                _w = Math.max(5, Math.min(_w, __w));
                _h = Math.max(5, Math.min(parseInt(_w * __h / __w)));
            }
4521
            this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_AddImageUrlLong);
4522 4523 4524 4525
            var src = _image.src;

            if (this.isShapeImageChangeUrl)
            {
4526 4527
                var AscShapeProp = new asc_CShapeProperty();
                AscShapeProp.fill = new asc_CShapeFill();
4528
                AscShapeProp.fill.type = c_oAscFill.FILL_TYPE_BLIP;
4529 4530 4531
                AscShapeProp.fill.fill = new asc_CFillBlip();
                AscShapeProp.fill.fill.asc_putUrl(src);
                this.ImgApply(new asc_CImgProperty({ShapeProperties:AscShapeProp}));
4532 4533 4534 4535
                this.isShapeImageChangeUrl = false;
            }
            else if (this.isImageChangeUrl)
            {
4536
                var AscImageProp = new asc_CImgProperty();
4537 4538 4539 4540 4541 4542
                AscImageProp.ImageUrl = src;
                this.ImgApply(AscImageProp);
                this.isImageChangeUrl = false;
            }
            else
            {
4543 4544 4545 4546
				var imageLocal = g_oDocumentUrls.getImageLocal(src);
				if(imageLocal){
					src = imageLocal;
				}
4547 4548 4549 4550 4551 4552 4553

                if (undefined === imgProp || undefined === imgProp.WrappingStyle || 0 == imgProp.WrappingStyle)
                    this.WordControl.m_oLogicDocument.Add_InlineImage(_w, _h, src);
                else
                    this.WordControl.m_oLogicDocument.Add_InlineImage(_w, _h, src, null, true);
            }

Oleg.Korshul's avatar
Oleg.Korshul committed
4554
            this.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.LoadImage);
4555 4556 4557 4558

            this.asyncImageEndLoaded2 = null;
        }
    }
4559
};
4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585
/*
    Добавляем картинку на заданную страницу. Преполагаем, что картинка уже доступна по ссылке.
 */
asc_docs_api.prototype.AddImageToPage = function(sUrl, nPageIndex, dX, dY, dW, dH)
{
    var LogicDocument = this.WordControl.m_oLogicDocument;

    var oldClickCount = global_mouseEvent.ClickCount;
    global_mouseEvent.Button = 0;
    global_mouseEvent.ClickCount = 1;
    LogicDocument.OnMouseDown(global_mouseEvent, dX, dY, nPageIndex);
    LogicDocument.OnMouseUp  (global_mouseEvent, dX, dY, nPageIndex);
    LogicDocument.OnMouseMove(global_mouseEvent, dX, dY, nPageIndex);
    global_mouseEvent.ClickCount = oldClickCount;

    if (false === LogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content))
    {
        var oPosH = new CImagePositionH();
        oPosH.put_RelativeFrom(c_oAscRelativeFromH.Page);
        oPosH.put_Align(false);
        oPosH.put_Value(dX);
        var oPosV = new CImagePositionV();
        oPosV.put_RelativeFrom(c_oAscRelativeFromV.Page);
        oPosV.put_Align(false);
        oPosV.put_Value(dY);
        var oImageProps = new asc_CImgProperty();
4586 4587 4588
        oImageProps.asc_putWrappingStyle(c_oAscWrapStyle2.Square);
        oImageProps.asc_putPositionH(oPosH);
        oImageProps.asc_putPositionV(oPosV);
4589

4590
        LogicDocument.Create_NewHistoryPoint(historydescription_Document_AddImageToPage);
4591 4592 4593 4594 4595 4596
        LogicDocument.Start_SilentMode();
        LogicDocument.Add_InlineImage(dW, dH, sUrl);
        LogicDocument.Set_ImageProps(oImageProps);
        LogicDocument.End_SilentMode(true);
    }
};
4597 4598
/* В качестве параметра  передается объект класса asc_CImgProperty, он же приходит на OnImgProp
 asc_CImgProperty заменяет пережнюю структуру:
4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610
если параметр не имеет значения то передвать следует null, напримере inline-картинок: в качестве left,top,bottom,right,X,Y,ImageUrl необходимо передавать null.
	{
		Width: 0,
		Height: 0,
		WrappingStyle: 0,
		Paddings: { Left : 0, Top : 0, Bottom: 0, Right: 0 },
		Position : {X : 0, Y : 0},
		ImageUrl : ""
	}
*/
asc_docs_api.prototype.ImgApply = function(obj)
{
4611

4612 4613 4614
    if(!isRealObject(obj))
        return;
    var ImagePr = obj, AdditionalData, LogicDocument = this.WordControl.m_oLogicDocument;
4615

4616 4617
    /*проверка корректности данных для биржевой диаграммы*/
    if(obj.ChartProperties && obj.ChartProperties.type === c_oAscChartTypeSettings.stock)
4618
    {
4619
        if(!CheckStockChart(this.WordControl.m_oLogicDocument.DrawingObjects, this))
4620
        {
4621
            return;
4622 4623
        }
    }
4624 4625 4626

    /*изменение z-индекса*/
    if(isRealNumber(ImagePr.ChangeLevel))
4627
    {
4628
        switch(ImagePr.ChangeLevel)
4629
        {
4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648
            case 0:
            {
                this.WordControl.m_oLogicDocument.DrawingObjects.bringToFront();
                break;
            }
            case 1:
            {
                this.WordControl.m_oLogicDocument.DrawingObjects.bringForward();
                break;
            }
            case 2:
            {
                this.WordControl.m_oLogicDocument.DrawingObjects.sendToBack();
                break;
            }
            case 3:
            {
                this.WordControl.m_oLogicDocument.DrawingObjects.bringBackward();
            }
4649
        }
4650
        return;
4651 4652
    }

4653 4654 4655
    /*параграфы в которых лежат выделенные ParaDrawing*/
    var aParagraphs = [], aSelectedObjects = this.WordControl.m_oLogicDocument.DrawingObjects.selectedObjects, i, j, oParentParagraph;
    for(i = 0; i < aSelectedObjects.length; ++i)
4656
    {
4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667
        oParentParagraph = aSelectedObjects[i].parent.Get_ParentParagraph();
        checkObjectInArray(aParagraphs, oParentParagraph);
    }


    AdditionalData = {Type : changestype_2_ElementsArray_and_Type , Elements : aParagraphs, CheckType : changestype_Paragraph_Content};
    /*группировка и разгруппировка*/
    if(ImagePr.Group === 1 || ImagePr.Group === -1)
    {
        if(false == this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Drawing_Props, AdditionalData))
        {
4668
            History.Create_NewPoint(historydescription_Document_GroupUnGroup);
4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679
            if(ImagePr.Group === 1)
            {
                this.WordControl.m_oLogicDocument.DrawingObjects.groupSelectedObjects();
            }
            else
            {
                this.WordControl.m_oLogicDocument.DrawingObjects.unGroupSelectedObjects();
            }
        }
        return;
    }
Oleg.Korshul's avatar
Oleg.Korshul committed
4680

4681 4682 4683

    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Image_Properties) )
    {
Oleg.Korshul's avatar
Oleg.Korshul committed
4684 4685 4686
        if (ImagePr.ShapeProperties)
            ImagePr.ImageUrl = "";

4687 4688 4689 4690 4691 4692 4693 4694

        var sImageUrl = null, fReplaceCallback = null, bImageUrl = false, sImageToDownLoad = "";
        if(!isNullOrEmptyString(ImagePr.ImageUrl)){
            if(!g_oDocumentUrls.getImageLocal(ImagePr.ImageUrl)){
                sImageUrl = ImagePr.ImageUrl;
                fReplaceCallback = function(sUrl){
                    ImagePr.ImageUrl = sUrl;
                    sImageToDownLoad = sUrl;
4695 4696
                }
            }
4697
            sImageToDownLoad = ImagePr.ImageUrl;
4698
        }
4699 4700 4701 4702 4703 4704 4705 4706
        else if(ImagePr.ShapeProperties && ImagePr.ShapeProperties.fill &&
            ImagePr.ShapeProperties.fill.fill && !isNullOrEmptyString(ImagePr.ShapeProperties.fill.fill.url)){
            if(!g_oDocumentUrls.getImageLocal(ImagePr.ShapeProperties.fill.fill.url)){
                sImageUrl = ImagePr.ShapeProperties.fill.fill.url;
                fReplaceCallback = function(sUrl){
                    ImagePr.ShapeProperties.fill.fill.url = sUrl;
                    sImageToDownLoad = sUrl;
                }
4707
            }
4708 4709 4710 4711 4712 4713 4714 4715 4716 4717
            sImageToDownLoad = ImagePr.ShapeProperties.fill.fill.url;
        }

        var oApi = this;

        if(!isNullOrEmptyString(sImageToDownLoad)){

            var fApplyCallback = function(){
                var _img = oApi.ImageLoader.LoadImage(sImageToDownLoad, 1);
                if (null != _img)
4718
                {
4719 4720
                    oApi.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_ApplyImagePrWithUrl);
                    oApi.WordControl.m_oLogicDocument.Set_ImageProps( ImagePr );
4721
                }
4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733
                else
                {
                    oApi.asyncImageEndLoaded2 = function(_image)
                    {
                        oApi.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_ApplyImagePrWithUrlLong);
                        oApi.WordControl.m_oLogicDocument.Set_ImageProps( ImagePr );
                    }
                }
            };

            if(sImageUrl){
                var rData = {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
4734
                    "id": this.documentId,
4735
                    "userid": this.documentUserId,
4736
                    "vkey": this.documentVKey,
4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775
                    "c": "imgurl",
                    "saveindex": g_oDocumentUrls.getMaxIndex(),
                    "data": sImageToDownLoad};

                this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.UploadImage);
                this.fCurCallback = function(input) {
                    if(null != input && "imgurl" == input["type"]){
                        if("ok" ==input["status"]) {
                            var data = input["data"];
                            var urls = {};
                            var firstUrl;
                            for(var i = 0; i < data.length; ++i){
                                var elem = data[i];
                                if(elem.url){
                                    if(!firstUrl){
                                        firstUrl = elem.url;
                                    }
                                    urls[elem.path] = elem.url;
                                }
                            }
                            g_oDocumentUrls.addUrls(urls);
                            if(firstUrl) {
                                fReplaceCallback(firstUrl);
                                fApplyCallback();
                            } else {
                                oApi.asc_fireCallback("asc_onError",c_oAscError.ID.Unknown,c_oAscError.Level.NoCritical);
                            }
                        } else {
                            oApi.asc_fireCallback("asc_onError", g_fMapAscServerErrorToAscError(parseInt(input["data"])), c_oAscError.Level.NoCritical);
                        }
                    } else {
                        oApi.asc_fireCallback("asc_onError",c_oAscError.ID.Unknown,c_oAscError.Level.NoCritical);
                    }
                    oApi.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.UploadImage);
                };
                sendCommand2(this, null, rData );
            }
            else{
                fApplyCallback();
4776 4777 4778 4779 4780
            }
        }
        else
        {
            ImagePr.ImageUrl = null;
4781 4782 4783 4784
            if(!this.noCreatePoint || this.exucuteHistory)
            {
                if( !this.noCreatePoint && !this.exucuteHistory && this.exucuteHistoryEnd)
                {
4785
                    History.UndoLastPoint(this.nCurPointItemsLength);
4786 4787
                    this.WordControl.m_oLogicDocument.Set_ImageProps( ImagePr );
                    this.exucuteHistoryEnd = false;
4788
                    this.nCurPointItemsLength = 0;
4789 4790 4791
                }
                else
                {
4792
                    this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_ApplyImagePr);
4793 4794 4795 4796 4797
                    this.WordControl.m_oLogicDocument.Set_ImageProps( ImagePr );
                }
                if(this.exucuteHistory)
                {
                    this.exucuteHistory = false;
4798 4799 4800 4801 4802
                    var oPoint = History.Points[History.Index];
                    if(oPoint)
                    {
                        this.nCurPointItemsLength = oPoint.Items.length;
                    }
4803 4804 4805 4806
                }
            }
            else
            {
4807
                //ExecuteNoHistory(function(){
4808
                    History.UndoLastPoint(this.nCurPointItemsLength);
4809
                    this.WordControl.m_oLogicDocument.Set_ImageProps( ImagePr );
4810
                //}, this, []);
4811
            }
4812 4813
        }
    }
4814
};
4815 4816
asc_docs_api.prototype.set_Size = function(width, height){

4817
};
4818 4819 4820 4821 4822 4823 4824
asc_docs_api.prototype.set_ConstProportions = function(isOn){
	if (isOn){

	}
	else{

	}
4825
};
4826 4827
asc_docs_api.prototype.set_WrapStyle = function(type){

4828
};
4829 4830
asc_docs_api.prototype.deleteImage = function(){

4831
};
4832 4833
asc_docs_api.prototype.set_ImgDistanceFromText = function(left,top,right,bottom){

4834
};
4835 4836
asc_docs_api.prototype.set_PositionOnPage = function(X,Y){//расположение от начала страницы

4837
};
4838 4839 4840 4841 4842 4843 4844
asc_docs_api.prototype.get_OriginalSizeImage = function(){
	if (0 == this.SelectedObjectsStack.length)
        return null;
    var obj = this.SelectedObjectsStack[this.SelectedObjectsStack.length - 1];
    if (obj == null)
        return null;
    if (obj.Type == c_oAscTypeSelectElement.Image)
4845
        return obj.Value.asc_getOriginSize(this);
4846
};
4847 4848 4849 4850 4851 4852 4853 4854 4855

asc_docs_api.prototype.ShapeApply = function(shapeProps)
{
    // нужно определить, картинка это или нет
    var image_url = "";
    if (shapeProps.fill != null)
    {
        if (shapeProps.fill.fill != null && shapeProps.fill.type == c_oAscFill.FILL_TYPE_BLIP)
        {
4856
            image_url = shapeProps.fill.fill.asc_getUrl();
4857

4858
            var _tx_id = shapeProps.fill.fill.asc_getTextureId();
4859 4860 4861 4862 4863 4864 4865 4866 4867 4868
            if (null != _tx_id && 0 <= _tx_id && _tx_id < g_oUserTexturePresets.length)
            {
                image_url = g_oUserTexturePresets[_tx_id];
            }
        }
    }
    if (image_url != "")
    {
        var _image = this.ImageLoader.LoadImage(image_url, 1);

4869 4870 4871 4872
		var imageLocal = g_oDocumentUrls.getImageLocal(image_url);
		if(imageLocal){
			shapeProps.fill.fill.asc_putUrl(imageLocal); // erase documentUrl
		}
4873 4874 4875 4876 4877 4878 4879 4880

        if (null != _image)
        {
            this.WordControl.m_oLogicDocument.ShapeApply(shapeProps);
            this.WordControl.m_oDrawingDocument.DrawImageTextureFillShape(image_url);
        }
        else
        {
Oleg.Korshul's avatar
Oleg.Korshul committed
4881
            this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.LoadImage);
4882 4883 4884 4885 4886 4887 4888

            var oProp = shapeProps;
            this.asyncImageEndLoaded2 = function(_image)
            {
                this.WordControl.m_oLogicDocument.ShapeApply(oProp);
                this.WordControl.m_oDrawingDocument.DrawImageTextureFillShape(image_url);

Oleg.Korshul's avatar
Oleg.Korshul committed
4889
                this.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.LoadImage);
4890 4891 4892 4893 4894 4895 4896 4897
                this.asyncImageEndLoaded2 = null;
            }
        }
    }
    else
    {
        this.WordControl.m_oLogicDocument.ShapeApply(shapeProps);
    }
4898
};
4899 4900 4901
/*callbacks*/
asc_docs_api.prototype.sync_AddImageCallback = function(){
	this.asc_fireCallback("asc_onAddImage");
4902
};
4903 4904 4905 4906 4907
asc_docs_api.prototype.sync_ImgPropCallback = function(imgProp)
{
    //if ( true === CollaborativeEditing.Get_GlobalLock() )
    //    imgProp.Locked = true;

4908
    this.SelectedObjectsStack[this.SelectedObjectsStack.length] = new asc_CSelectedObject( c_oAscTypeSelectElement.Image, new asc_CImgProperty( imgProp ) );
4909
};
4910 4911
asc_docs_api.prototype.sync_ImgWrapStyleChangedCallback = function(style){
	this.asc_fireCallback("asc_onImgWrapStyleChanged",style);
4912
};
4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944

//-----------------------------------------------------------------
// События контекстного меню
//-----------------------------------------------------------------

function CContextMenuData( obj )
{
    if( obj )
    {
        this.Type  = ( undefined != obj.Type ) ? obj.Type : c_oAscContextMenuTypes.Common;
        this.X_abs = ( undefined != obj.X_abs ) ? obj.X_abs : 0;
        this.Y_abs = ( undefined != obj.Y_abs ) ? obj.Y_abs : 0;

        switch ( this.Type )
        {
            case c_oAscContextMenuTypes.ChangeHdrFtr :
            {
                this.PageNum = ( undefined != obj.PageNum ) ? obj.PageNum : 0;
                this.Header  = ( undefined != obj.Header  ) ? obj.Header  : true;

                break;
            }
        }
    }
    else
    {
        this.Type  = c_oAscContextMenuTypes.Common;
        this.X_abs = 0;
        this.Y_abs = 0;
    }
}

4945 4946 4947 4948 4949
CContextMenuData.prototype.get_Type  = function()  { return this.Type; };
CContextMenuData.prototype.get_X = function()  { return this.X_abs; };
CContextMenuData.prototype.get_Y = function()  { return this.Y_abs; };
CContextMenuData.prototype.get_PageNum = function()  { return this.PageNum; };
CContextMenuData.prototype.is_Header = function()  { return this.Header; };
4950 4951 4952 4953

asc_docs_api.prototype.sync_ContextMenuCallback = function(Data)
{
    this.asc_fireCallback("asc_onContextMenu", new CContextMenuData( Data ) );
4954
};
4955 4956 4957 4958 4959


asc_docs_api.prototype.sync_MouseMoveStartCallback = function()
{
    this.asc_fireCallback("asc_onMouseMoveStart");
4960
};
4961 4962 4963 4964

asc_docs_api.prototype.sync_MouseMoveEndCallback = function()
{
    this.asc_fireCallback("asc_onMouseMoveEnd");
4965
};
4966 4967 4968 4969

asc_docs_api.prototype.sync_MouseMoveCallback = function(Data)
{
    this.asc_fireCallback("asc_onMouseMove", Data );
4970
};
4971 4972 4973

asc_docs_api.prototype.sync_ShowForeignCursorLabel = function(UserId, X, Y, Color)
{
4974
    this.asc_fireCallback("asc_onShowForeignCursorLabel", UserId, X, Y, new CColor(Color.r, Color.g, Color.b, 255));
4975 4976 4977
};
asc_docs_api.prototype.sync_HideForeignCursorLabel = function(UserId)
{
4978
    this.asc_fireCallback("asc_onHideForeignCursorLabel", UserId);
4979
};
4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993

//-----------------------------------------------------------------
// Функции для работы с гиперссылками
//-----------------------------------------------------------------
asc_docs_api.prototype.can_AddHyperlink = function()
{
    //if ( true === CollaborativeEditing.Get_GlobalLock() )
    //    return false;

    var bCanAdd = this.WordControl.m_oLogicDocument.Hyperlink_CanAdd(true);
    if ( true === bCanAdd )
        return this.WordControl.m_oLogicDocument.Get_SelectedText(true);

    return false;
4994
};
4995 4996 4997 4998 4999 5000

// HyperProps - объект CHyperlinkProperty
asc_docs_api.prototype.add_Hyperlink = function(HyperProps)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
5001
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_AddHyperlink);
5002 5003
        this.WordControl.m_oLogicDocument.Hyperlink_Add( HyperProps );
    }
5004
};
5005 5006 5007 5008 5009 5010

// HyperProps - объект CHyperlinkProperty
asc_docs_api.prototype.change_Hyperlink = function(HyperProps)
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
5011
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_ChangeHyperlink);
5012 5013
        this.WordControl.m_oLogicDocument.Hyperlink_Modify( HyperProps );
    }
5014
};
5015 5016 5017 5018 5019

asc_docs_api.prototype.remove_Hyperlink = function()
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
5020
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_RemoveHyperlink);
5021 5022
        this.WordControl.m_oLogicDocument.Hyperlink_Remove();
    }
5023
};
5024 5025 5026 5027 5028 5029 5030

function CHyperlinkProperty( obj )
{
    if( obj )
    {
        this.Text    = (undefined != obj.Text   ) ? obj.Text    : null;
        this.Value   = (undefined != obj.Value  ) ? obj.Value   : "";
5031
        this.ToolTip = (undefined != obj.ToolTip) ? obj.ToolTip : "";
5032 5033 5034 5035 5036
    }
    else
    {
        this.Text    = null;
        this.Value   = "";
5037
        this.ToolTip = "";
5038 5039 5040
    }
}

5041 5042 5043
CHyperlinkProperty.prototype.get_Value   = function()  { return this.Value; };
CHyperlinkProperty.prototype.put_Value   = function(v) { this.Value = v; };
CHyperlinkProperty.prototype.get_ToolTip = function()  { return this.ToolTip; };
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5044
CHyperlinkProperty.prototype.put_ToolTip = function(v) { this.ToolTip = v ? v.slice(0, c_oAscMaxTooltipLength) : v; };
5045 5046
CHyperlinkProperty.prototype.get_Text    = function()  { return this.Text; };
CHyperlinkProperty.prototype.put_Text    = function(v) { this.Text = v; };
5047 5048 5049

asc_docs_api.prototype.sync_HyperlinkPropCallback = function(hyperProp)
{
5050
    this.SelectedObjectsStack[this.SelectedObjectsStack.length] = new asc_CSelectedObject( c_oAscTypeSelectElement.Hyperlink, new CHyperlinkProperty( hyperProp ) );
5051
};
5052 5053 5054 5055

asc_docs_api.prototype.sync_HyperlinkClickCallback = function(Url)
{
    this.asc_fireCallback("asc_onHyperlinkClick", Url);
5056
};
5057 5058 5059 5060 5061 5062 5063

asc_docs_api.prototype.sync_CanAddHyperlinkCallback = function(bCanAdd)
{
    //if ( true === CollaborativeEditing.Get_GlobalLock() )
    //    this.asc_fireCallback("asc_onCanAddHyperlink", false);
    //else
        this.asc_fireCallback("asc_onCanAddHyperlink", bCanAdd);
5064
};
5065 5066 5067 5068

asc_docs_api.prototype.sync_DialogAddHyperlink = function()
{
    this.asc_fireCallback("asc_onDialogAddHyperlink");
5069
};
5070 5071 5072 5073

asc_docs_api.prototype.sync_DialogAddHyperlink = function()
{
    this.asc_fireCallback("asc_onDialogAddHyperlink");
5074
};
5075 5076 5077 5078

//-----------------------------------------------------------------
// Функции для работы с орфографией
//-----------------------------------------------------------------
5079
function asc_CSpellCheckProperty( Word, Checked, Variants, ParaId, ElemId )
5080 5081 5082 5083
{
    this.Word     = Word;
    this.Checked  = Checked;
    this.Variants = Variants;
5084 5085 5086

    this.ParaId   = ParaId;
    this.ElemId   = ElemId;
5087 5088
}

5089 5090 5091
asc_CSpellCheckProperty.prototype.get_Word     = function()  { return this.Word; };
asc_CSpellCheckProperty.prototype.get_Checked  = function()  { return this.Checked; };
asc_CSpellCheckProperty.prototype.get_Variants = function()  { return this.Variants; };
5092

5093
asc_docs_api.prototype.sync_SpellCheckCallback = function(Word, Checked, Variants, ParaId, ElemId)
5094
{
5095
    this.SelectedObjectsStack[this.SelectedObjectsStack.length] = new asc_CSelectedObject( c_oAscTypeSelectElement.SpellCheck, new asc_CSpellCheckProperty( Word, Checked, Variants, ParaId, ElemId ) );
5096
};
5097 5098 5099 5100

asc_docs_api.prototype.sync_SpellCheckVariantsFound = function()
{
    this.asc_fireCallback("asc_onSpellCheckVariantsFound");
5101
};
5102 5103 5104 5105 5106 5107 5108 5109 5110

asc_docs_api.prototype.asc_replaceMisspelledWord = function(Word, SpellCheckProperty)
{
    var ParaId = SpellCheckProperty.ParaId;
    var ElemId = SpellCheckProperty.ElemId;

    var Paragraph = g_oTableId.Get_ById(ParaId);
    if ( null != Paragraph && false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_None, { Type : changestype_2_Element_and_Type, Element : Paragraph, CheckType : changestype_Paragraph_Content } ) )
    {
5111
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_ReplaceMisspelledWord);
5112 5113
        Paragraph.Replace_MisspelledWord( Word, ElemId );
        this.WordControl.m_oLogicDocument.Recalculate();
5114
        Paragraph.Document_SetThisElementCurrent(true);
5115
    }
5116
};
5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137

asc_docs_api.prototype.asc_ignoreMisspelledWord = function(SpellCheckProperty, bAll)
{
    if ( false === bAll )
    {
        var ParaId = SpellCheckProperty.ParaId;
        var ElemId = SpellCheckProperty.ElemId;

        var Paragraph = g_oTableId.Get_ById(ParaId);
        if ( null != Paragraph )
        {
            Paragraph.Ignore_MisspelledWord( ElemId );
        }
    }
    else
    {
        var LogicDocument = editor.WordControl.m_oLogicDocument;
        LogicDocument.Spelling.Add_Word( SpellCheckProperty.Word );
        LogicDocument.DrawingDocument.ClearCachePages();
        LogicDocument.DrawingDocument.FirePaint();
    }
5138
};
Ilya.Kirillov's avatar
Ilya.Kirillov committed
5139 5140 5141

asc_docs_api.prototype.asc_setDefaultLanguage = function(Lang)
{
5142 5143
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Document_SectPr) )
    {
5144
        History.Create_NewPoint(historydescription_Document_SetDefaultLanguage);
Oleg.Korshul's avatar
Oleg.Korshul committed
5145
        editor.WordControl.m_oLogicDocument.Set_DefaultLanguage(Lang);
5146
    }
5147
};
Ilya.Kirillov's avatar
Ilya.Kirillov committed
5148 5149 5150

asc_docs_api.prototype.asc_getDefaultLanguage = function()
{
5151
    return editor.WordControl.m_oLogicDocument.Get_DefaultLanguage();
5152
};
5153

5154 5155
asc_docs_api.prototype.asc_getKeyboardLanguage = function()
{
5156 5157
    if (undefined !== window["asc_current_keyboard_layout"])
        return window["asc_current_keyboard_layout"];
5158 5159 5160
    return -1;
};

5161 5162
asc_docs_api.prototype.asc_setSpellCheck = function(isOn)
{
5163 5164 5165 5166 5167 5168
    if (editor.WordControl.m_oLogicDocument)
    {
        editor.WordControl.m_oLogicDocument.Spelling.Use = isOn;
        editor.WordControl.m_oDrawingDocument.ClearCachePages();
        editor.WordControl.m_oDrawingDocument.FirePaint();
    }
5169
};
5170 5171 5172
//-----------------------------------------------------------------
// Функции для работы с комментариями
//-----------------------------------------------------------------
5173
function asc_CCommentDataWord( obj )
5174 5175 5176 5177 5178 5179 5180 5181 5182
{
    if( obj )
    {
        this.m_sText      = (undefined != obj.m_sText     ) ? obj.m_sText      : "";
        this.m_sTime      = (undefined != obj.m_sTime     ) ? obj.m_sTime      : "";
        this.m_sUserId    = (undefined != obj.m_sUserId   ) ? obj.m_sUserId    : "";
        this.m_sQuoteText = (undefined != obj.m_sQuoteText) ? obj.m_sQuoteText : null;
        this.m_bSolved    = (undefined != obj.m_bSolved   ) ? obj.m_bSolved    : false;
        this.m_sUserName  = (undefined != obj.m_sUserName ) ? obj.m_sUserName  : "";
5183
        this.m_aReplies   = [];
5184 5185 5186 5187 5188
        if ( undefined != obj.m_aReplies )
        {
            var Count = obj.m_aReplies.length;
            for ( var Index = 0; Index < Count; Index++ )
            {
5189
                var Reply = new asc_CCommentDataWord( obj.m_aReplies[Index] );
5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201
                this.m_aReplies.push( Reply );
            }
        }
    }
    else
    {
        this.m_sText      = "";
        this.m_sTime      = "";
        this.m_sUserId    = "";
        this.m_sQuoteText = null;
        this.m_bSolved    = false;
        this.m_sUserName  = "";
5202
        this.m_aReplies   = [];
5203 5204 5205
    }
}

5206
asc_CCommentDataWord.prototype.asc_getText         = function()  { return this.m_sText; };
5207
asc_CCommentDataWord.prototype.asc_putText         = function(v) { this.m_sText = v ? v.slice(0, c_oAscMaxCellOrCommentLength) : v; };
5208 5209 5210 5211 5212 5213
asc_CCommentDataWord.prototype.asc_getTime         = function()  { return this.m_sTime; };
asc_CCommentDataWord.prototype.asc_putTime         = function(v) { this.m_sTime = v; };
asc_CCommentDataWord.prototype.asc_getUserId       = function()  { return this.m_sUserId; };
asc_CCommentDataWord.prototype.asc_putUserId       = function(v) { this.m_sUserId = v; };
asc_CCommentDataWord.prototype.asc_getUserName     = function()  { return this.m_sUserName; };
asc_CCommentDataWord.prototype.asc_putUserName     = function(v) { this.m_sUserName = v; };
5214 5215 5216 5217
asc_CCommentDataWord.prototype.asc_getQuoteText    = function()  { return this.m_sQuoteText; };
asc_CCommentDataWord.prototype.asc_putQuoteText    = function(v) { this.m_sQuoteText = v; };
asc_CCommentDataWord.prototype.asc_getSolved       = function()  { return this.m_bSolved; };
asc_CCommentDataWord.prototype.asc_putSolved       = function(v) { this.m_bSolved = v; };
5218 5219 5220
asc_CCommentDataWord.prototype.asc_getReply        = function(i) { return this.m_aReplies[i]; };
asc_CCommentDataWord.prototype.asc_addReply        = function(v) { this.m_aReplies.push( v ); };
asc_CCommentDataWord.prototype.asc_getRepliesCount = function(v) { return this.m_aReplies.length; };
5221 5222 5223 5224 5225 5226 5227 5228


asc_docs_api.prototype.asc_showComments = function()
{
    if (null == this.WordControl.m_oLogicDocument)
        return;

    this.WordControl.m_oLogicDocument.Show_Comments();
5229
};
5230 5231 5232 5233 5234 5235 5236 5237

asc_docs_api.prototype.asc_hideComments = function()
{
    if (null == this.WordControl.m_oLogicDocument)
        return;

    this.WordControl.m_oLogicDocument.Hide_Comments();
    editor.sync_HideComment();
5238
};
5239 5240 5241

asc_docs_api.prototype.asc_addComment = function(AscCommentData)
{
5242
};
5243 5244 5245 5246 5247 5248 5249 5250

asc_docs_api.prototype.asc_removeComment = function(Id)
{
    if (null == this.WordControl.m_oLogicDocument)
        return;

    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_None, { Type : changestype_2_Comment, Id : Id } ) )
    {
5251
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_RemoveComment);
5252
        this.WordControl.m_oLogicDocument.Remove_Comment( Id, true, true );
5253
    }
5254
};
5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265

asc_docs_api.prototype.asc_changeComment = function(Id, AscCommentData)
{
    if (null == this.WordControl.m_oLogicDocument)
        return;

    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_None, { Type : changestype_2_Comment, Id : Id } ) )
    {
        var CommentData = new CCommentData();
        CommentData.Read_FromAscCommentData(AscCommentData);

5266
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_ChangeComment);
5267 5268 5269 5270
        this.WordControl.m_oLogicDocument.Change_Comment( Id, CommentData );

        this.sync_ChangeCommentData( Id, CommentData );
    }
5271
};
5272 5273 5274 5275 5276 5277

asc_docs_api.prototype.asc_selectComment = function(Id)
{
    if (null == this.WordControl.m_oLogicDocument)
        return;

5278
    this.WordControl.m_oLogicDocument.Select_Comment(Id, true);
5279
};
5280 5281 5282 5283

asc_docs_api.prototype.asc_showComment = function(Id)
{
    this.WordControl.m_oLogicDocument.Show_Comment(Id);
5284
};
5285 5286 5287 5288 5289 5290 5291

asc_docs_api.prototype.can_AddQuotedComment = function()
{
    //if ( true === CollaborativeEditing.Get_GlobalLock() )
    //    return false;

    return this.WordControl.m_oLogicDocument.CanAdd_Comment();
5292
};
5293 5294 5295 5296

asc_docs_api.prototype.sync_RemoveComment = function(Id)
{
    this.asc_fireCallback("asc_onRemoveComment", Id);
5297
};
5298 5299 5300

asc_docs_api.prototype.sync_AddComment = function(Id, CommentData)
{
5301
    var AscCommentData = new asc_CCommentDataWord(CommentData);
5302
    this.asc_fireCallback("asc_onAddComment", Id, AscCommentData);
5303
};
5304 5305 5306 5307 5308

asc_docs_api.prototype.sync_ShowComment = function(Id, X, Y)
{
    // TODO: Переделать на нормальный массив
    this.asc_fireCallback("asc_onShowComment", [ Id ], X, Y);
5309
};
5310 5311 5312 5313

asc_docs_api.prototype.sync_HideComment = function()
{
    this.asc_fireCallback("asc_onHideComment");
5314
};
5315 5316 5317 5318 5319

asc_docs_api.prototype.sync_UpdateCommentPosition = function(Id, X, Y)
{
    // TODO: Переделать на нормальный массив
    this.asc_fireCallback("asc_onUpdateCommentPosition", [ Id ], X, Y);
5320
};
5321 5322 5323

asc_docs_api.prototype.sync_ChangeCommentData = function(Id, CommentData)
{
5324
    var AscCommentData = new asc_CCommentDataWord(CommentData);
5325
    this.asc_fireCallback("asc_onChangeCommentData", Id, AscCommentData);
5326
};
5327 5328 5329 5330

asc_docs_api.prototype.sync_LockComment = function(Id, UserId)
{
    this.asc_fireCallback("asc_onLockComment", Id, UserId);
5331
};
5332 5333 5334 5335

asc_docs_api.prototype.sync_UnLockComment = function(Id)
{
    this.asc_fireCallback("asc_onUnLockComment", Id);
5336
};
5337 5338 5339

asc_docs_api.prototype.asc_getComments = function()
{
5340
    var ResComments = [];
5341 5342 5343 5344 5345 5346
    var LogicDocument = this.WordControl.m_oLogicDocument;
    if ( undefined != LogicDocument )
    {
        var DocComments = LogicDocument.Comments;
        for ( var Id in DocComments.m_aComments )
        {
5347
            var AscCommentData = new asc_CCommentDataWord(DocComments.m_aComments[Id].Data);
5348 5349 5350 5351 5352
            ResComments.push( { "Id" : Id, "Comment" : AscCommentData } );
        }
    }

    return ResComments;
5353
};
5354 5355 5356 5357
//-----------------------------------------------------------------
asc_docs_api.prototype.sync_LockHeaderFooters = function()
{
    this.asc_fireCallback("asc_onLockHeaderFooters");
5358
};
5359 5360 5361 5362

asc_docs_api.prototype.sync_LockDocumentProps = function()
{
    this.asc_fireCallback("asc_onLockDocumentProps");
5363
};
5364 5365 5366 5367

asc_docs_api.prototype.sync_UnLockHeaderFooters = function()
{
    this.asc_fireCallback("asc_onUnLockHeaderFooters");
5368
};
5369 5370 5371 5372

asc_docs_api.prototype.sync_UnLockDocumentProps = function()
{
    this.asc_fireCallback("asc_onUnLockDocumentProps");
5373
};
5374 5375 5376

asc_docs_api.prototype.sync_CollaborativeChanges = function()
{
5377 5378
    if (true !== CollaborativeEditing.Is_Fast())
        this.asc_fireCallback("asc_onCollaborativeChanges");
5379
};
5380 5381 5382 5383

asc_docs_api.prototype.sync_LockDocumentSchema = function()
{
    this.asc_fireCallback("asc_onLockDocumentSchema");
5384
};
5385 5386 5387 5388

asc_docs_api.prototype.sync_UnLockDocumentSchema = function()
{
    this.asc_fireCallback("asc_onUnLockDocumentSchema");
5389
};
5390 5391 5392 5393 5394 5395


/*----------------------------------------------------------------*/
/*functions for working with zoom & navigation*/
asc_docs_api.prototype.zoomIn = function(){
    this.WordControl.zoom_In();
5396
};
5397 5398
asc_docs_api.prototype.zoomOut = function(){
    this.WordControl.zoom_Out();
5399
};
5400 5401
asc_docs_api.prototype.zoomFitToPage = function(){
    this.WordControl.zoom_FitToPage();
5402
};
5403 5404
asc_docs_api.prototype.zoomFitToWidth = function(){
    this.WordControl.zoom_FitToWidth();
5405
};
5406 5407 5408
asc_docs_api.prototype.zoomCustomMode = function(){
    this.WordControl.m_nZoomType = 0;
    this.WordControl.zoom_Fire(0, this.WordControl.m_nZoomValue);
5409
};
5410 5411
asc_docs_api.prototype.zoom100 = function(){
	this.zoom(100);
5412
};
5413 5414 5415 5416 5417
asc_docs_api.prototype.zoom = function(percent){
    var _old_val = this.WordControl.m_nZoomValue;
    this.WordControl.m_nZoomValue = percent;
    this.WordControl.m_nZoomType = 0;
    this.WordControl.zoom_Fire(0, _old_val);
5418
};
5419 5420
asc_docs_api.prototype.goToPage = function(number){
	this.WordControl.GoToPage(number);
5421
};
5422 5423
asc_docs_api.prototype.getCountPages = function(){
	return this.WordControl.m_oDrawingDocument.m_lPagesCount;
5424
};
5425 5426
asc_docs_api.prototype.getCurrentPage = function(){
	return this.WordControl.m_oDrawingDocument.m_lCurrentPage;
5427
};
5428 5429 5430
/*callbacks*/
asc_docs_api.prototype.sync_zoomChangeCallback = function(percent,type){	//c_oAscZoomType.Current, c_oAscZoomType.FitWidth, c_oAscZoomType.FitPage
	this.asc_fireCallback("asc_onZoomChange",percent,type);
5431
};
5432 5433
asc_docs_api.prototype.sync_countPagesCallback = function(count){
	this.asc_fireCallback("asc_onCountPages",count);
5434
};
5435 5436
asc_docs_api.prototype.sync_currentPageCallback = function(number){
	this.asc_fireCallback("asc_onCurrentPage",number);
5437
};
5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448

/*----------------------------------------------------------------*/
asc_docs_api.prototype.asc_enableKeyEvents = function(value){
	if (this.WordControl.IsFocus != value) {
		this.WordControl.IsFocus = value;

        if (this.WordControl.IsFocus && null != this.WordControl.TextBoxInput)
            this.WordControl.TextBoxInput.focus();

		this.asc_fireCallback("asc_onEnableKeyEventsChanged", value);
	}
5449
};
5450 5451 5452 5453 5454 5455

asc_docs_api.prototype.asyncServerIdEndLoaded = function()
{
    this.ServerIdWaitComplete = true;
    if (true == this.ServerImagesWaitComplete)
        this.OpenDocumentEndCallback();
5456
};
5457 5458 5459 5460 5461 5462 5463

// работа с шрифтами
asc_docs_api.prototype.asyncFontsDocumentStartLoaded = function()
{
	// здесь прокинуть евент о заморозке меню
	// и нужно вывести информацию в статус бар
    if (this.isPasteFonts_Images)
Oleg.Korshul's avatar
Oleg.Korshul committed
5464
        this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.LoadFont);
5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480
    else if (this.isSaveFonts_Images)
        this.sync_StartAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.LoadFont);
    else
    {
        this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.LoadDocumentFonts);

        // заполним прогресс
        var _progress = this.OpenDocumentProgress;
        _progress.Type = c_oAscAsyncAction.LoadDocumentFonts;
        _progress.FontsCount = this.FontLoader.fonts_loading.length;
        _progress.CurrentFont = 0;

        var _loader_object = this.WordControl.m_oLogicDocument;
        var _count = 0;
        if (_loader_object !== undefined && _loader_object != null)
        {
5481
            for (var i in _loader_object.ImageMap) {
Sergey.Konovalov's avatar
Sergey.Konovalov committed
5482 5483
				if(this.DocInfo.get_OfflineApp()) {
					var localUrl = _loader_object.ImageMap[i];
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5484
					g_oDocumentUrls.addImageUrl(localUrl, this.documentUrl + 'media/' + localUrl);
Sergey.Konovalov's avatar
Sergey.Konovalov committed
5485
				}
5486
                ++_count;
5487
			}
5488 5489 5490 5491 5492
        }

        _progress.ImagesCount = _count;
        _progress.CurrentImage = 0;
    }
5493
};
5494 5495
asc_docs_api.prototype.GenerateStyles = function()
{
5496 5497 5498 5499 5500 5501
    if (window["NATIVE_EDITOR_ENJINE"] === true)
    {
        if (!this.asc_checkNeedCallback("asc_onInitEditorStyles"))
            return;
    }

5502
    var StylesPainter = new CStylesPainter();
5503 5504
    var LogicDocument = this.WordControl.m_oLogicDocument;
    if (LogicDocument)
5505
    {
5506 5507 5508 5509 5510
        var isTrackRevision = LogicDocument.Is_TrackRevisions();

        if (true === isTrackRevision)
            LogicDocument.Set_TrackRevisions(false);

Oleg.Korshul's avatar
Oleg.Korshul committed
5511
        StylesPainter.GenerateStyles(this, (null == this.LoadedObject) ? this.WordControl.m_oLogicDocument.Get_Styles().Style : this.LoadedObjectDS);
5512 5513 5514

        if (true === isTrackRevision)
            LogicDocument.Set_TrackRevisions(true);
5515
    }
5516
};
5517 5518 5519 5520
asc_docs_api.prototype.asyncFontsDocumentEndLoaded = function()
{
    // все, шрифты загружены. Теперь нужно подгрузить картинки
    if (this.isPasteFonts_Images)
Oleg.Korshul's avatar
Oleg.Korshul committed
5521
        this.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.LoadFont);
5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536
    else if (this.isSaveFonts_Images)
        this.sync_EndAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.LoadFont);
    else
        this.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.LoadDocumentFonts);

    this.EndActionLoadImages = 0;
    if (this.isPasteFonts_Images)
    {
        var _count = 0;
        for (var i in this.pasteImageMap)
            ++_count;

        if (_count > 0)
        {
            this.EndActionLoadImages = 2;
Oleg.Korshul's avatar
Oleg.Korshul committed
5537
            this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.LoadImage);
5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588
        }

        var _oldAsyncLoadImages = this.ImageLoader.bIsAsyncLoadDocumentImages;
        this.ImageLoader.bIsAsyncLoadDocumentImages = false;
        this.ImageLoader.LoadDocumentImages(this.pasteImageMap, false);
        this.ImageLoader.bIsAsyncLoadDocumentImages = true;
        return;
    }
    else if (this.isSaveFonts_Images)
    {
        var _count = 0;
        for (var i in this.saveImageMap)
            ++_count;

        if (_count > 0)
        {
            this.EndActionLoadImages = 2;
            this.sync_StartAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.LoadImage);
        }

        this.ImageLoader.LoadDocumentImages(this.saveImageMap, false);
        return;
    }

    if (!this.FontLoader.embedded_cut_manager.bIsCutFontsUse)
        this.GenerateStyles();

    if (null != this.WordControl.m_oLogicDocument)
    {
        this.WordControl.m_oDrawingDocument.CheckGuiControlColors();
        this.WordControl.m_oDrawingDocument.SendThemeColorScheme();
		this.asc_fireCallback("asc_onUpdateChartStyles");
    }

    if (this.isLoadNoCutFonts)
    {
        this.isLoadNoCutFonts = false;
        this.SetViewMode(false);
        return;
    }

    // открытие после загрузки документа

	var _loader_object = this.WordControl.m_oLogicDocument;
	if (null == _loader_object)
		_loader_object = this.WordControl.m_oDrawingDocument.m_oDocumentRenderer;

    var _count = 0;
	for (var i in _loader_object.ImageMap)
        ++_count;

Oleg.Korshul's avatar
Oleg.Korshul committed
5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600
    if (!this.isOnlyReaderMode)
    {
        // add const textures
        var _st_count = g_oUserTexturePresets.length;
        for (var i = 0; i < _st_count; i++)
            _loader_object.ImageMap[_count + i] = g_oUserTexturePresets[i];

        if (this.OpenDocumentProgress && !this.ImageLoader.bIsAsyncLoadDocumentImages)
        {
            this.OpenDocumentProgress.ImagesCount += _st_count;
        }
    }
5601 5602 5603 5604 5605 5606 5607 5608 5609

    if (_count > 0)
    {
        this.EndActionLoadImages = 1;
        this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.LoadDocumentImages);
    }

    this.ImageLoader.bIsLoadDocumentFirst = true;
	this.ImageLoader.LoadDocumentImages(_loader_object.ImageMap, true);
5610
};
5611 5612 5613 5614 5615 5616 5617 5618 5619

asc_docs_api.prototype.CreateFontsCharMap = function()
{
    var _info = new CFontsCharMap();
    _info.StartWork();

    this.WordControl.m_oLogicDocument.Document_CreateFontCharMap(_info);

    return _info.EndWork();
5620
};
5621 5622 5623 5624

asc_docs_api.prototype.sync_SendThemeColors = function(colors,standart_colors)
{
    this._gui_control_colors = { Colors : colors, StandartColors : standart_colors };
Oleg.Korshul's avatar
Oleg.Korshul committed
5625
    this.asc_fireCallback("asc_onSendThemeColors",colors,standart_colors);
5626
};
5627 5628 5629
asc_docs_api.prototype.sync_SendThemeColorSchemes = function(param)
{
    this._gui_color_schemes = param;
5630
};
5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646

asc_docs_api.prototype.ChangeColorScheme = function(index_scheme)
{
    if (null == this.WordControl.m_oLogicDocument)
        return;

    var _changer = this.WordControl.m_oLogicDocument.DrawingObjects;
    if (null == _changer)
        return;

    var theme = this.WordControl.m_oLogicDocument.theme;

    var _count_defaults = g_oUserColorScheme.length;

    if(this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_ColorScheme) === false)
    {
5647
        History.Create_NewPoint(historydescription_Document_ChangeColorScheme);
5648 5649 5650 5651 5652 5653
        var data = {Type: historyitem_ChangeColorScheme, oldScheme:theme.themeElements.clrScheme};

        if (index_scheme < _count_defaults)
        {
            var _obj = g_oUserColorScheme[index_scheme];
            var scheme = new ClrScheme();
5654
			scheme.name = _obj["name"];
5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717
            var _c = null;

            _c = _obj["dk1"];
            scheme.colors[8] = CreateUniColorRGB(_c["R"], _c["G"], _c["B"]);

            _c = _obj["lt1"];
            scheme.colors[12] = CreateUniColorRGB(_c["R"], _c["G"], _c["B"]);

            _c = _obj["dk2"];
            scheme.colors[9] = CreateUniColorRGB(_c["R"], _c["G"], _c["B"]);

            _c = _obj["lt2"];
            scheme.colors[13] = CreateUniColorRGB(_c["R"], _c["G"], _c["B"]);

            _c = _obj["accent1"];
            scheme.colors[0] = CreateUniColorRGB(_c["R"], _c["G"], _c["B"]);

            _c = _obj["accent2"];
            scheme.colors[1] = CreateUniColorRGB(_c["R"], _c["G"], _c["B"]);

            _c = _obj["accent3"];
            scheme.colors[2] = CreateUniColorRGB(_c["R"], _c["G"], _c["B"]);

            _c = _obj["accent4"];
            scheme.colors[3] = CreateUniColorRGB(_c["R"], _c["G"], _c["B"]);

            _c = _obj["accent5"];
            scheme.colors[4] = CreateUniColorRGB(_c["R"], _c["G"], _c["B"]);

            _c = _obj["accent6"];
            scheme.colors[5] = CreateUniColorRGB(_c["R"], _c["G"], _c["B"]);

            _c = _obj["hlink"];
            scheme.colors[11] = CreateUniColorRGB(_c["R"], _c["G"], _c["B"]);

            _c = _obj["folHlink"];
            scheme.colors[10] = CreateUniColorRGB(_c["R"], _c["G"], _c["B"]);

            theme.themeElements.clrScheme = scheme;
            /*_changer.calculateAfterChangeTheme();

             // TODO:
             this.WordControl.m_oDrawingDocument.ClearCachePages();
             this.WordControl.OnScroll();*/
        }
        else
        {
            index_scheme -= _count_defaults;

            if (index_scheme < 0 || index_scheme >= theme.extraClrSchemeLst.length)
                return;

            theme.themeElements.clrScheme = theme.extraClrSchemeLst[index_scheme].clrScheme.createDuplicate();
            /*_changer.calculateAfterChangeTheme();

             // TODO:
             this.WordControl.m_oDrawingDocument.ClearCachePages();
             this.WordControl.OnScroll();*/
        }

        data.newScheme = theme.themeElements.clrScheme;
        History.Add(this.WordControl.m_oLogicDocument.DrawingObjects, data);
        this.WordControl.m_oDrawingDocument.CheckGuiControlColors();
5718
        this.chartPreviewManager.clearPreviews();
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
5719
        this.textArtPreviewManager.clear();
5720
        this.asc_fireCallback("asc_onUpdateChartStyles");
Anna.Pavlova's avatar
Anna.Pavlova committed
5721
        this.WordControl.m_oLogicDocument.Recalculate();
5722

5723

5724 5725 5726
        // TODO:
        this.WordControl.m_oDrawingDocument.ClearCachePages();
        this.WordControl.OnScroll();
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
5727 5728

        this.WordControl.m_oDrawingDocument.CheckGuiControlColors();
5729
        this.WordControl.m_oLogicDocument.Document_UpdateInterfaceState();
5730 5731
    }

5732
};
5733 5734 5735 5736 5737

asc_docs_api.prototype.asyncImagesDocumentStartLoaded = function()
{
	// евент о заморозке не нужен... оно и так заморожено
	// просто нужно вывести информацию в статус бар (что началась загрузка картинок)
5738
};
5739 5740 5741
asc_docs_api.prototype.asyncImagesDocumentEndLoaded = function()
{
    this.ImageLoader.bIsLoadDocumentFirst = false;
Oleg.Korshul's avatar
 
Oleg.Korshul committed
5742
    var _bIsOldPaste = this.isPasteFonts_Images;
5743 5744 5745

    if (null != this.WordControl.m_oDrawingDocument.m_oDocumentRenderer)
    {
Oleg.Korshul's avatar
Oleg.Korshul committed
5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758
        if (this.EndActionLoadImages == 1)
        {
            this.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.LoadDocumentImages);
        }
        else if (this.EndActionLoadImages == 2)
        {
            if (this.isPasteFonts_Images)
                this.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.LoadImage);
            else
                this.sync_EndAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.LoadImage);
        }
        this.EndActionLoadImages = 0;

5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770
        this.WordControl.m_oDrawingDocument.OpenDocument();

        this.LoadedObject = null;

        this.bInit_word_control = true;

        if (false === this.isPasteFonts_Images)
            this.asc_fireCallback("asc_onDocumentContentReady");

        this.WordControl.InitControl();

        if (this.isViewMode)
5771
            this.SetViewMode(true);
5772 5773 5774
        return;
    }

5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788
    // на методе OpenDocumentEndCallback может поменяться this.EndActionLoadImages
    if (this.EndActionLoadImages == 1)
    {
        this.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.LoadDocumentImages);
    }
    else if (this.EndActionLoadImages == 2)
    {
        if (_bIsOldPaste)
            this.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.LoadImage);
        else
            this.sync_EndAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.LoadImage);
    }
    this.EndActionLoadImages = 0;

5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801
	// размораживаем меню... и начинаем считать документ
    if (false === this.isPasteFonts_Images && false === this.isSaveFonts_Images && false === this.isLoadImagesCustom)
    {
        this.ServerImagesWaitComplete = true;
        if (true == this.ServerIdWaitComplete)
            this.OpenDocumentEndCallback();
    }
    else
    {
        if (this.isPasteFonts_Images)
        {
            this.isPasteFonts_Images = false;
            this.pasteImageMap = null;
5802
            this.asc_DecrementCounterLongAction();
5803
            this.pasteCallback();
Oleg.Korshul's avatar
Oleg.Korshul committed
5804
            window.GlobalPasteFlag = false;
Oleg.Korshul's avatar
Oleg.Korshul committed
5805
            window.GlobalPasteFlagCounter = 0;
5806 5807 5808 5809 5810 5811 5812
            this.pasteCallback = null;
        }
        else if (this.isSaveFonts_Images)
        {
            this.isSaveFonts_Images = false;
            this.saveImageMap = null;
            this.pre_SaveCallback();
5813 5814 5815 5816 5817 5818

            if (this.bInit_word_control === false)
            {
                this.bInit_word_control = true;
                this.asc_fireCallback("asc_onDocumentContentReady");
            }
5819 5820 5821 5822 5823
        }
        else if (this.isLoadImagesCustom)
        {
            this.isLoadImagesCustom = false;
            this.loadCustomImageMap = null;
Oleg.Korshul's avatar
Oleg.Korshul committed
5824 5825 5826

            if (!this.ImageLoader.bIsAsyncLoadDocumentImages)
                this.SyncLoadImages_callback();
5827 5828
        }
    }
5829
};
5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855

asc_docs_api.prototype.OpenDocumentEndCallback = function()
{
    if (null == this.WordControl.m_oLogicDocument)
        return;

    if (0 == this.DocumentType)
        this.WordControl.m_oLogicDocument.LoadEmptyDocument();
    else if (1 == this.DocumentType)
    {
        this.WordControl.m_oLogicDocument.LoadTestDocument();
    }
    else
    {
        if(this.LoadedObject)
        {
            if(1 != this.LoadedObject)
            {
                this.WordControl.m_oLogicDocument.fromJfdoc(this.LoadedObject);
                this.WordControl.m_oDrawingDocument.TargetStart();
                this.WordControl.m_oLogicDocument.Document_UpdateInterfaceState();
            }
            else
            {
                var Document = this.WordControl.m_oLogicDocument;

5856 5857 5858
                if (this.isApplyChangesOnOpenEnabled)
                {
                    this.isApplyChangesOnOpenEnabled = false;
5859 5860 5861
                    this.isApplyChangesOnOpen = true;
                    CollaborativeEditing.Apply_Changes();
                    CollaborativeEditing.Release_Locks();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5862 5863 5864 5865 5866 5867

                  // Применяем все lock-и (ToDo возможно стоит пересмотреть вообще Lock-и)
                  for (var i = 0; i < this.arrPreOpenLocksObjects.length; ++i) {
                    this.arrPreOpenLocksObjects[i]();
                  }
                  this.arrPreOpenLocksObjects = [];
5868
                }
5869

5870
//                History.RecalcData_Add( { Type : historyrecalctype_Inline, Data : { Pos : 0, PageNum : 0 } } );
5871 5872 5873

                //Recalculate для Document
                Document.CurPos.ContentPos = 0;
5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886
//                History.RecalcData_Add({Type: historyrecalctype_Drawing, All: true});

                var RecalculateData =
                {
                    Inline : { Pos : 0, PageNum : 0 },
                    Flow   : [],
                    HdrFtr : [],
                    Drawings: {
                        All: true,
                        Map:{}
                    }
                };

Oleg.Korshul's avatar
Oleg.Korshul committed
5887 5888
                if (!this.isOnlyReaderMode)
                {
5889
                    if (false === this.isSaveFonts_Images)
5890
                        Document.Recalculate(false, false, RecalculateData);
5891

Oleg.Korshul's avatar
Oleg.Korshul committed
5892 5893 5894 5895
                    this.WordControl.m_oDrawingDocument.TargetStart();
                }
                else
                {
Ilya.Kirillov's avatar
Ilya.Kirillov committed
5896
                    Document.Recalculate_AllTables();
5897 5898 5899
                    var data = {All:true};
                    Document.DrawingObjects.recalculate_(data);
                    Document.DrawingObjects.recalculateText_(data);
5900 5901 5902 5903 5904

                    if (!this.WordControl.IsReaderMode())
                        this.ChangeReaderMode();
                    else
                        this.WordControl.UpdateReaderContent();
Oleg.Korshul's avatar
Oleg.Korshul committed
5905
                }
5906 5907 5908 5909 5910 5911 5912 5913 5914
            }
        }
    }

    this.WordControl.m_oLogicDocument.Document_UpdateInterfaceState();
    //this.WordControl.m_oLogicDocument.Document_UpdateRulersState();
    this.WordControl.m_oLogicDocument.Document_UpdateSelectionState();
    this.LoadedObject = null;

5915 5916 5917 5918 5919
    if (false === this.isSaveFonts_Images)
    {
        this.bInit_word_control = true;
        this.asc_fireCallback("asc_onDocumentContentReady");
    }
5920 5921

    this.WordControl.InitControl();
Oleg.Korshul's avatar
Oleg.Korshul committed
5922 5923 5924

    if (!this.isViewMode)
        this.WordControl.m_oDrawingDocument.SendMathToMenu();
5925 5926

    if (this.isViewMode)
5927
        this.SetViewMode(true);
5928 5929 5930

	// Меняем тип состояния (на никакое)
	this.advancedOptionsAction = c_oAscAdvancedOptionsAction.None;
5931
};
5932 5933 5934 5935 5936 5937 5938

asc_docs_api.prototype.UpdateInterfaceState = function()
{
    if (this.WordControl.m_oLogicDocument != null)
    {
        this.WordControl.m_oLogicDocument.Document_UpdateInterfaceState();
    }
5939
};
5940 5941 5942 5943 5944

asc_docs_api.prototype.asyncFontStartLoaded = function()
{
	// здесь прокинуть евент о заморозке меню
    this.sync_StartAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.LoadFont);
5945
};
5946 5947 5948
asc_docs_api.prototype.asyncFontEndLoaded = function(fontinfo)
{
    this.sync_EndAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.LoadFont);
Oleg.Korshul's avatar
Oleg.Korshul committed
5949

5950 5951
    var _fontSelections = g_fontApplication.g_fontSelections;
    if (_fontSelections.CurrentLoadedObj != null)
Oleg.Korshul's avatar
Oleg.Korshul committed
5952
    {
5953 5954
        var _rfonts = _fontSelections.getSetupRFonts(_fontSelections.CurrentLoadedObj);
        this.WordControl.m_oLogicDocument.TextBox_Put(_fontSelections.CurrentLoadedObj.text, _rfonts);
Oleg.Korshul's avatar
Oleg.Korshul committed
5955 5956
        this.WordControl.ReinitTB();

5957
        _fontSelections.CurrentLoadedObj = null;
Oleg.Korshul's avatar
Oleg.Korshul committed
5958 5959 5960 5961
        this.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.LoadFont);
        return;
    }

Oleg.Korshul's avatar
Oleg.Korshul committed
5962 5963 5964 5965 5966 5967 5968 5969
    if (this.FontAsyncLoadType == 1)
    {
        this.FontAsyncLoadType = 0;
        this.asc_AddMath2(this.FontAsyncLoadParam);
        this.FontAsyncLoadParam = null;
        return;
    }

5970 5971
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
5972
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_SetTextFontNameLong);
5973 5974 5975 5976
        this.WordControl.m_oLogicDocument.Paragraph_Add( new ParaTextPr( { FontFamily : { Name : fontinfo.Name , Index : -1 } } ) );
        this.WordControl.m_oLogicDocument.Document_UpdateInterfaceState();
    }
	// отжать заморозку меню
5977
};
5978 5979 5980 5981

asc_docs_api.prototype.asyncImageStartLoaded = function()
{
    // здесь прокинуть евент о заморозке меню
5982
};
5983 5984 5985 5986 5987 5988 5989
asc_docs_api.prototype.asyncImageEndLoaded = function(_image)
{
    // отжать заморозку меню
	if (this.asyncImageEndLoaded2)
		this.asyncImageEndLoaded2(_image);
	else
    {
5990
        if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
5991
        {
5992
            this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_AddImage);
5993
            this.WordControl.m_oLogicDocument.Add_InlineImage(50, 50, _image.src);
5994 5995
        }
	}
5996
};
5997 5998 5999 6000

asc_docs_api.prototype.asyncImageEndLoadedBackground = function(_image)
{
    this.WordControl.m_oDrawingDocument.CheckRasterImageOnScreen(_image.src);
6001
};
6002 6003 6004
asc_docs_api.prototype.IsAsyncOpenDocumentImages = function()
{
    return true;
6005
};
6006 6007 6008

asc_docs_api.prototype.pre_Paste = function(_fonts, _images, callback)
{
Oleg.Korshul's avatar
Oleg.Korshul committed
6009 6010 6011 6012 6013 6014 6015 6016
	if (undefined !== window["Native"] && undefined !== window["Native"]["GetImageUrl"])
	{
		callback();
		window.GlobalPasteFlag = false;
		window.GlobalPasteFlagCounter = 0;
		return;
	}

6017 6018
    this.pasteCallback = callback;
    this.pasteImageMap = _images;
Oleg.Korshul's avatar
Oleg.Korshul committed
6019 6020 6021 6022 6023 6024 6025 6026

    var _count = 0;
    for (var i in this.pasteImageMap)
        ++_count;
    if (0 == _count && false === this.FontLoader.CheckFontsNeedLoading(_fonts))
    {
        // никаких евентов. ничего грузить не нужно. сделано для сафари под макОс.
        // там при LongActions теряется фокус и вставляются пробелы
6027
        this.asc_DecrementCounterLongAction();
Oleg.Korshul's avatar
Oleg.Korshul committed
6028
        this.pasteCallback();
Oleg.Korshul's avatar
Oleg.Korshul committed
6029
        window.GlobalPasteFlag = false;
Oleg.Korshul's avatar
Oleg.Korshul committed
6030
        window.GlobalPasteFlagCounter = 0;
Oleg.Korshul's avatar
Oleg.Korshul committed
6031
        this.pasteCallback = null;
6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052
        
		if (-1 != window.PasteEndTimerId)
        {
            clearTimeout(window.PasteEndTimerId);
            window.PasteEndTimerId = -1;

            document.body.style.MozUserSelect = "none";
            document.body.style["-khtml-user-select"] = "none";
            document.body.style["-o-user-select"] = "none";
            document.body.style["user-select"] = "none";
            document.body.style["-webkit-user-select"] = "none";

            var pastebin = Editor_Paste_GetElem(this, true);

            if (!window.USER_AGENT_SAFARI_MACOS)
                pastebin.onpaste = null;

            pastebin.style.display  = ELEMENT_DISPAY_STYLE;
        }
		
		return;
Oleg.Korshul's avatar
Oleg.Korshul committed
6053 6054
    }

Oleg.Korshul's avatar
Oleg.Korshul committed
6055
    this.isPasteFonts_Images = true;
6056
    this.FontLoader.LoadDocumentFonts2(_fonts);
6057
};
6058 6059 6060 6061 6062 6063 6064

asc_docs_api.prototype.pre_Save = function(_images)
{
    this.isSaveFonts_Images = true;
    this.saveImageMap = _images;
    this.WordControl.m_oDrawingDocument.CheckFontNeeds();
    this.FontLoader.LoadDocumentFonts2(this.WordControl.m_oLogicDocument.Fonts);
6065
};
6066 6067 6068 6069 6070 6071 6072

asc_docs_api.prototype.SyncLoadImages = function(_images)
{
    this.isLoadImagesCustom = true;
    this.loadCustomImageMap = _images;

    var _count = 0;
Oleg.Korshul's avatar
Oleg.Korshul committed
6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084
    var _loaded = this.ImageLoader.map_image_index;

    var _new_len = this.loadCustomImageMap.length;
    for (var i = 0; i < _new_len; i++)
    {
        if (undefined !== _loaded[this.loadCustomImageMap[i]])
        {
            this.loadCustomImageMap.splice(i, 1);
            i--;
            _new_len--;
            continue;
        }
6085
        ++_count;
Oleg.Korshul's avatar
Oleg.Korshul committed
6086
    }
6087 6088 6089 6090 6091 6092 6093 6094

    if (_count > 0)
    {
        this.EndActionLoadImages = 2;
        this.sync_StartAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.LoadImage);
    }

    this.ImageLoader.LoadDocumentImages(this.loadCustomImageMap, false);
6095
};
6096 6097 6098
asc_docs_api.prototype.SyncLoadImages_callback = function()
{
    this.WordControl.OnRePaintAttack();
6099
};
6100 6101 6102 6103

asc_docs_api.prototype.pre_SaveCallback = function()
{
    CollaborativeEditing.OnEnd_Load_Objects();
6104 6105 6106 6107 6108 6109

    if (this.isApplyChangesOnOpen)
    {
        this.isApplyChangesOnOpen = false;
        this.OpenDocumentEndCallback();
    }
6110
};
6111 6112 6113 6114

asc_docs_api.prototype.initEvents2MobileAdvances = function()
{
    //this.WordControl.initEvents2MobileAdvances();
6115
};
6116 6117 6118
asc_docs_api.prototype.ViewScrollToX = function(x)
{
    this.WordControl.m_oScrollHorApi.scrollToX(x);
6119
};
6120 6121 6122
asc_docs_api.prototype.ViewScrollToY = function(y)
{
    this.WordControl.m_oScrollVerApi.scrollToY(y);
6123
};
6124 6125 6126
asc_docs_api.prototype.GetDocWidthPx = function()
{
    return this.WordControl.m_dDocumentWidth;
6127
};
6128 6129 6130
asc_docs_api.prototype.GetDocHeightPx = function()
{
    return this.WordControl.m_dDocumentHeight;
6131
};
6132 6133 6134
asc_docs_api.prototype.ClearSearch = function()
{
    return this.WordControl.m_oDrawingDocument.EndSearch(true);
6135
};
6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153
asc_docs_api.prototype.GetCurrentVisiblePage = function()
{
    var lPage1 = this.WordControl.m_oDrawingDocument.m_lDrawingFirst;
    var lPage2 = lPage1 + 1;

    if (lPage2 > this.WordControl.m_oDrawingDocument.m_lDrawingEnd)
        return lPage1;

    var lWindHeight = this.WordControl.m_oEditor.HtmlElement.height;
    var arPages = this.WordControl.m_oDrawingDocument.m_arrPages;

    var dist1 = arPages[lPage1].drawingPage.bottom;
    var dist2 = lWindHeight - arPages[lPage2].drawingPage.top;

    if (dist1 > dist2)
        return lPage1;

    return lPage2;
6154 6155
};

Anna.Pavlova's avatar
Anna.Pavlova committed
6156 6157 6158 6159
asc_docs_api.prototype.asc_SetDocumentPlaceChangedEnabled = function(bEnabled)
{
    if (this.WordControl)
        this.WordControl.m_bDocumentPlaceChangedEnabled = bEnabled;
6160
};
Anna.Pavlova's avatar
Anna.Pavlova committed
6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172

asc_docs_api.prototype.asc_SetViewRulers = function(bRulers)
{
    //if (false === this.bInit_word_control || true === this.isViewMode)
    //    return;

    if (this.WordControl.m_bIsRuler != bRulers)
    {
        this.WordControl.m_bIsRuler = bRulers;
        this.WordControl.checkNeedRules();
        this.WordControl.OnResize(true);
    }
6173
};
Anna.Pavlova's avatar
Anna.Pavlova committed
6174 6175 6176 6177 6178 6179 6180 6181 6182
asc_docs_api.prototype.asc_SetViewRulersChange = function()
{
    //if (false === this.bInit_word_control || true === this.isViewMode)
    //    return;

    this.WordControl.m_bIsRuler = !this.WordControl.m_bIsRuler;
    this.WordControl.checkNeedRules();
    this.WordControl.OnResize(true);
    return this.WordControl.m_bIsRuler;
6183
};
Anna.Pavlova's avatar
Anna.Pavlova committed
6184 6185 6186
asc_docs_api.prototype.asc_GetViewRulers = function()
{
    return this.WordControl.m_bIsRuler;
6187
};
Anna.Pavlova's avatar
Anna.Pavlova committed
6188

6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200
asc_docs_api.prototype.SetMobileVersion = function(val)
{
    this.isMobileVersion = val;
    if (this.isMobileVersion)
    {
        this.WordControl.bIsRetinaSupport = false; // ipad имеет проблемы с большими картинками
        this.WordControl.bIsRetinaNoSupportAttack = true;
        this.WordControl.m_bIsRuler = false;
		this.ShowParaMarks = false;

        this.SetFontRenderingMode(1);
    }
6201
};
6202 6203 6204 6205 6206 6207

asc_docs_api.prototype.GoToHeader = function(pageNumber)
{
    if (this.WordControl.m_oDrawingDocument.IsFreezePage(pageNumber))
        return;

6208 6209 6210 6211 6212 6213 6214 6215
    var bForceRedraw = false;
    var LogicDocument = this.WordControl.m_oLogicDocument;
    if (docpostype_HdrFtr !== LogicDocument.CurPos.Type)
    {
        LogicDocument.CurPos.Type = docpostype_HdrFtr;
        bForceRedraw = true;
    }

6216 6217
    var oldClickCount = global_mouseEvent.ClickCount;
    global_mouseEvent.Button = 0;
6218
    global_mouseEvent.ClickCount = 1;
6219

6220 6221 6222 6223 6224
    LogicDocument.OnMouseDown(global_mouseEvent, 0, 0, pageNumber);
    LogicDocument.OnMouseUp(global_mouseEvent, 0, 0, pageNumber);
    LogicDocument.OnMouseMove(global_mouseEvent, 0, 0, pageNumber);
    LogicDocument.Cursor_MoveLeft();
    LogicDocument.Document_UpdateInterfaceState();
6225 6226

    global_mouseEvent.ClickCount = oldClickCount;
6227 6228 6229 6230 6231 6232

    if (true === bForceRedraw)
    {
        this.WordControl.m_oDrawingDocument.ClearCachePages();
        this.WordControl.m_oDrawingDocument.FirePaint();
    }
6233
};
6234 6235 6236 6237 6238 6239

asc_docs_api.prototype.GoToFooter = function(pageNumber)
{
    if (this.WordControl.m_oDrawingDocument.IsFreezePage(pageNumber))
        return;

6240 6241 6242 6243 6244 6245 6246 6247
    var bForceRedraw = false;
    var LogicDocument = this.WordControl.m_oLogicDocument;
    if (docpostype_HdrFtr !== LogicDocument.CurPos.Type)
    {
        LogicDocument.CurPos.Type = docpostype_HdrFtr;
        bForceRedraw = true;
    }

6248 6249
    var oldClickCount = global_mouseEvent.ClickCount;
    global_mouseEvent.Button = 0;
6250
    global_mouseEvent.ClickCount = 1;
6251

6252 6253 6254 6255 6256
    LogicDocument.OnMouseDown(global_mouseEvent, 0, Page_Height, pageNumber);
    LogicDocument.OnMouseUp(global_mouseEvent, 0, Page_Height, pageNumber);
    LogicDocument.OnMouseMove(global_mouseEvent, 0, 0, pageNumber);
    LogicDocument.Cursor_MoveLeft();
    LogicDocument.Document_UpdateInterfaceState();
6257 6258

    global_mouseEvent.ClickCount = oldClickCount;
6259 6260 6261 6262 6263 6264

    if (true === bForceRedraw)
    {
        this.WordControl.m_oDrawingDocument.ClearCachePages();
        this.WordControl.m_oDrawingDocument.FirePaint();
    }
6265
};
6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279

asc_docs_api.prototype.ExitHeader_Footer = function(pageNumber)
{
    if (this.WordControl.m_oDrawingDocument.IsFreezePage(pageNumber))
        return;

    var oldClickCount = global_mouseEvent.ClickCount;
    global_mouseEvent.ClickCount = 2;
    this.WordControl.m_oLogicDocument.OnMouseDown(global_mouseEvent, 0, Page_Height / 2, pageNumber);
    this.WordControl.m_oLogicDocument.OnMouseUp(global_mouseEvent, 0, Page_Height / 2, pageNumber);

    this.WordControl.m_oLogicDocument.Document_UpdateInterfaceState();

    global_mouseEvent.ClickCount = oldClickCount;
6280
};
6281 6282 6283 6284

asc_docs_api.prototype.GetCurrentPixOffsetY = function()
{
    return this.WordControl.m_dScrollY;
6285
};
6286

6287
asc_docs_api.prototype.SetPaintFormat = function(_value)
6288
{
6289 6290
    var value = ( true === _value ? c_oAscFormatPainterState.kOn : ( false === _value ? c_oAscFormatPainterState.kOff : _value ) );
    
6291
    this.isPaintFormat = value;
6292 6293 6294

    if (c_oAscFormatPainterState.kOff !== value)
        this.WordControl.m_oLogicDocument.Document_Format_Copy();
6295
};
6296 6297 6298

asc_docs_api.prototype.ChangeShapeType = function(value)
{
6299
    this.ImgApply(new asc_CImgProperty({ShapeProperties:{type:value}}));
6300
};
6301

6302
asc_docs_api.prototype.sync_PaintFormatCallback = function(_value)
6303
{
6304 6305
    var value = ( true === _value ? c_oAscFormatPainterState.kOn : ( false === _value ? c_oAscFormatPainterState.kOff : _value ) );
    
6306 6307
    this.isPaintFormat = value;
    return this.asc_fireCallback("asc_onPaintFormatChanged", value);
6308
};
6309 6310 6311 6312 6313 6314 6315 6316 6317
asc_docs_api.prototype.SetMarkerFormat = function(value, is_flag, r, g, b)
{
    this.isMarkerFormat = value;

    if (this.isMarkerFormat)
    {
        this.WordControl.m_oLogicDocument.Paragraph_SetHighlight(is_flag, r, g, b);
        this.WordControl.m_oLogicDocument.Document_Format_Copy();
    }
6318
};
6319 6320 6321 6322 6323

asc_docs_api.prototype.sync_MarkerFormatCallback = function(value)
{
    this.isMarkerFormat = value;
    return this.asc_fireCallback("asc_onMarkerFormatChanged", value);
6324
};
6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338

asc_docs_api.prototype.StartAddShape = function(sPreset, is_apply)
{
    this.isStartAddShape = true;
    this.addShapePreset = sPreset;
    if (is_apply)
    {
        this.WordControl.m_oDrawingDocument.LockCursorType("crosshair");
    }
    else
    {
        editor.sync_EndAddShape();
        editor.sync_StartAddShapeCallback(false);
    }
6339
};
6340

6341 6342 6343 6344 6345 6346 6347
asc_docs_api.prototype.AddTextArt = function(nStyle)
{
    if(false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content))
    {
        History.Create_NewPoint(historydescription_Document_AddTextArt);
        this.WordControl.m_oLogicDocument.Add_TextArt(nStyle);
    }
6348
};
6349 6350


6351 6352 6353 6354
asc_docs_api.prototype.sync_StartAddShapeCallback = function(value)
{
    this.isStartAddShape = value;
    return this.asc_fireCallback("asc_onStartAddShapeChanged", value);
6355
};
6356 6357 6358 6359

asc_docs_api.prototype.CanGroup = function()
{
    return this.WordControl.m_oLogicDocument.CanGroup();
6360
};
6361 6362 6363 6364

asc_docs_api.prototype.CanUnGroup = function()
{
    return this.WordControl.m_oLogicDocument.CanUnGroup();
6365
};
6366 6367 6368 6369

asc_docs_api.prototype.CanChangeWrapPolygon = function()
{
    return this.WordControl.m_oLogicDocument.CanChangeWrapPolygon();
6370
};
6371 6372 6373 6374

asc_docs_api.prototype.StartChangeWrapPolygon = function()
{
    return this.WordControl.m_oLogicDocument.StartChangeWrapPolygon();
6375
};
6376 6377 6378 6379 6380 6381


asc_docs_api.prototype.ClearFormating = function()
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
6382
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_ClearFormatting);
6383 6384
        this.WordControl.m_oLogicDocument.Paragraph_ClearFormatting();
    }
6385
};
6386 6387 6388 6389

asc_docs_api.prototype.GetSectionInfo = function()
{
    var obj = new CAscSection();
6390 6391 6392 6393
        
    // TODO: Переделать данную функцию, если она вообще нужна
    obj.PageWidth    = 297;
    obj.PageHeight   = 210;
6394

6395 6396 6397 6398
    obj.MarginLeft   = 30;
    obj.MarginRight  = 15;
    obj.MarginTop    = 20;
    obj.MarginBottom = 20;
6399 6400

    return obj;
6401
};
6402

6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416
asc_docs_api.prototype.add_SectionBreak = function(_Type)
{
    var Type = section_type_Continuous;
    switch(_Type)
    {
        case c_oAscSectionBreakType.NextPage   : Type = section_type_NextPage; break;
        case c_oAscSectionBreakType.OddPage    : Type = section_type_OddPage; break;
        case c_oAscSectionBreakType.EvenPage   : Type = section_type_EvenPage; break;
        case c_oAscSectionBreakType.Continuous : Type = section_type_Continuous; break;
        case c_oAscSectionBreakType.Column     : Type = section_type_Column; break;
    }

    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
6417
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_AddSectionBreak);
6418 6419
        this.WordControl.m_oLogicDocument.Add_SectionBreak(Type);
    }
6420
};
6421

6422 6423 6424
asc_docs_api.prototype.SetViewMode = function(isViewMode) {
  if (isViewMode) {
    this.asc_SpellCheckDisconnect();
6425

6426 6427 6428 6429 6430
    this.isViewMode = true;
    this.ShowParaMarks = false;
    CollaborativeEditing.m_bGlobalLock = true;
    //this.isShowTableEmptyLine = false;
    //this.WordControl.m_bIsRuler = true;
Oleg.Korshul's avatar
Oleg.Korshul committed
6431

6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444
    if (null == this.WordControl.m_oDrawingDocument.m_oDocumentRenderer) {
      this.WordControl.m_oDrawingDocument.ClearCachePages();
      this.WordControl.HideRulers();
    } else {
      this.WordControl.HideRulers();
      this.WordControl.OnScroll();
    }
  } else {
    if (this.bInit_word_control === true && this.FontLoader.embedded_cut_manager.bIsCutFontsUse) {
      this.isLoadNoCutFonts = true;
      this.FontLoader.embedded_cut_manager.bIsCutFontsUse = false;
      this.FontLoader.LoadDocumentFonts(this.WordControl.m_oLogicDocument.Fonts, true);
      return;
6445
    }
6446

6447 6448 6449 6450 6451 6452 6453 6454
    // быстрого перехода больше нет
    /*
     if ( this.bInit_word_control === true )
     {
     CollaborativeEditing.Apply_Changes();
     CollaborativeEditing.Release_Locks();
     }
     */
6455

6456
    this.isUseEmbeddedCutFonts = false;
6457

6458 6459 6460 6461 6462 6463
    this.isViewMode = false;
    //this.WordControl.m_bIsRuler = true;
    this.WordControl.checkNeedRules();
    this.WordControl.m_oDrawingDocument.ClearCachePages();
    this.WordControl.OnResize(true);
  }
6464
};
6465 6466 6467 6468

asc_docs_api.prototype.SetUseEmbeddedCutFonts = function(bUse)
{
    this.isUseEmbeddedCutFonts = bUse;
6469
};
6470 6471 6472 6473 6474 6475

asc_docs_api.prototype.IsNeedDefaultFonts = function()
{
    if (this.WordControl.m_oLogicDocument != null)
        return true;
    return false;
6476
};
6477 6478 6479 6480

asc_docs_api.prototype.OnMouseUp = function(x, y)
{
    this.WordControl.onMouseUpExternal(x, y);
6481
};
Oleg.Korshul's avatar
Oleg.Korshul committed
6482

6483 6484
asc_docs_api.prototype.asyncImageEndLoaded2 = null;

6485 6486
asc_docs_api.prototype._OfflineAppDocumentStartLoad = function() {
  var t = this, scriptElem = document.createElement('script');
6487

6488 6489 6490
  scriptElem.onload = scriptElem.onerror = function() {
    t._OfflineAppDocumentEndLoad();
  };
6491

Alexander.Trofimov's avatar
Alexander.Trofimov committed
6492
  scriptElem.setAttribute('src', this.documentUrl + "editor.js");
6493 6494
  scriptElem.setAttribute('type', 'text/javascript');
  document.getElementsByTagName('head')[0].appendChild(scriptElem);
6495
};
6496 6497 6498 6499 6500 6501 6502 6503
asc_docs_api.prototype._OfflineAppDocumentEndLoad = function() {
  var bIsViewer = false;
  var sData = window["editor_bin"];
  if (undefined == sData)
    return;
  if (c_oSerFormat.Signature !== sData.substring(0, c_oSerFormat.Signature.length)) {
    bIsViewer = true;
  }
6504

6505
  if (bIsViewer) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
6506
    this.OpenDocument(this.documentUrl, sData);
6507
  } else {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
6508
    this.OpenDocument2(this.documentUrl, sData);
6509
  }
6510
};
6511 6512 6513 6514 6515

asc_docs_api.prototype.SetDrawImagePlaceParagraph = function(element_id, props)
{
    this.WordControl.m_oDrawingDocument.InitGuiCanvasTextProps(element_id);
    this.WordControl.m_oDrawingDocument.DrawGuiCanvasTextProps(props);
6516
};
6517

6518 6519 6520
asc_docs_api.prototype.asc_getMasterCommentId = function()
{
    return -1;
6521
};
6522 6523 6524

asc_docs_api.prototype.asc_getAnchorPosition = function()
{
Ilya.Kirillov's avatar
Ilya.Kirillov committed
6525 6526
    var AnchorPos = this.WordControl.m_oLogicDocument.Get_SelectionAnchorPos();    
    return new asc_CRect(AnchorPos.X0, AnchorPos.Y, AnchorPos.X1 - AnchorPos.X0, 0);
6527
};
6528

6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539
function spellCheck (editor, rdata) {
  //console.log("start - " + rdata);
  // ToDo проверка на подключение
  switch (rdata.type) {
    case "spell":
    case "suggest":
      editor.SpellCheckApi.spellCheck(JSON.stringify(rdata));
      break;
  }
}

6540 6541
window["asc_nativeOnSpellCheck"] = function (response)
{
Oleg.Korshul's avatar
Oleg.Korshul committed
6542 6543
    if (editor.SpellCheckApi)
        editor.SpellCheckApi.onSpellCheck(response);
6544 6545
};

6546
function _onOpenCommand(fCallback, incomeObject) {
6547
	g_fOpenFileCommand(incomeObject["data"], editor.documentUrlChanges, c_oSerFormat.Signature, function (error, result) {
6548
		if (error) {
6549
			editor.asc_fireCallback("asc_onError",c_oAscError.ID.Unknown,c_oAscError.Level.Critical);
6550 6551
			if(fCallback) fCallback();
			return;
6552
		}
6553

6554
		if (result.changes && editor.VersionHistory) {
6555 6556
			editor.VersionHistory.changes = result.changes;
			editor.VersionHistory.applyChanges(editor);
6557 6558
		}

6559 6560 6561 6562 6563
		if (result.bSerFormat)
			editor.OpenDocument2(result.url, result.data);
		else
			editor.OpenDocument(result.url, result.data);
		if(fCallback) fCallback();
6564 6565
	});
}
6566 6567 6568 6569 6570 6571 6572 6573 6574 6575
function _downloadAs(editor, command, filetype, actionType, options, fCallbackRequest) {
    if (!options) {
      options = {};
    }
    if (actionType) {
        editor.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, actionType);
    }
    // Меняем тип состояния (на сохранение)
    editor.advancedOptionsAction = c_oAscAdvancedOptionsAction.Save;
    
6576
	var dataContainer = {data: null, part: null, index: 0, count: 0};
6577
	var oAdditionalData = {};
6578
    oAdditionalData["c"] = command;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
6579
    oAdditionalData["id"] = editor.documentId;
6580
    oAdditionalData["userid"] = editor.documentUserId;
6581
    oAdditionalData["vkey"] = editor.documentVKey;
Sergey.Luzyanin's avatar
 
Sergey.Luzyanin committed
6582
    oAdditionalData["outputformat"] = filetype;
6583
    oAdditionalData["title"] = changeFileExtention(editor.documentTitle, getExtentionByFormat(filetype));
6584
	oAdditionalData["savetype"] = c_oAscSaveTypes.CompleteAll;
6585 6586 6587
	if (options.isNoData) {
		;//nothing
	} else if (null == options.oDocumentMailMerge &&  c_oAscFileType.PDF === filetype) {
6588
		var dd = editor.WordControl.m_oDrawingDocument;
6589
		dataContainer.data = dd.ToRendererPart();
6590
        //console.log(oAdditionalData["data"]);
6591
	} else if (c_oAscFileType.JSON === filetype) {
6592 6593 6594
		oAdditionalData['url'] = editor.mailMergeFileData['url'];
		oAdditionalData['format'] = editor.mailMergeFileData['fileType'];
		// ToDo select csv params
6595 6596
		oAdditionalData['codepage'] = c_oAscCodePageUtf8;
		oAdditionalData['delimiter'] = c_oAscCsvDelimiter.Comma
6597
	} else if (c_oAscFileType.TXT === filetype && !options.txtOptions && null == options.oDocumentMailMerge && null == options.oMailMergeSendData) {
6598
		// Мы открывали команду, надо ее закрыть.
6599 6600 6601
		if (actionType) {
			editor.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, actionType);
		}
6602
		var cp = {'codepage': c_oAscCodePageUtf8, 'encodings': getEncodingParams()};
Sergey.Konovalov's avatar
Sergey.Konovalov committed
6603
		editor.asc_fireCallback("asc_onAdvancedOptions", new asc.asc_CAdvancedOptions(c_oAscAdvancedOptionsID.TXT, cp), editor.advancedOptionsAction);
6604
		return;
6605
	} else if (c_oAscFileType.HTML === filetype && null == options.oDocumentMailMerge && null == options.oMailMergeSendData) {
6606 6607 6608 6609 6610 6611
		//в asc_nativeGetHtml будет вызван select all, чтобы выделился документ должны выйти из колонтитулов и автофигур
		var _e = new CKeyboardEvent();
		_e.CtrlKey = false;
		_e.KeyCode = 27;
		editor.WordControl.m_oLogicDocument.OnKeyDown(_e);
		//сделано через сервер, потому что нет простого механизма сохранения на клиенте
Sergey.Konovalov's avatar
Sergey.Konovalov committed
6612
		dataContainer.data = '\ufeff' + window["asc_docs_api"].prototype["asc_nativeGetHtml"].call(editor);
6613
	} else {
6614 6615
		if (options.txtOptions instanceof asc.asc_CTXTAdvancedOptions) {
			oAdditionalData["codepage"] = options.txtOptions.asc_getCodePage();
Sergey.Konovalov's avatar
Sergey.Konovalov committed
6616
		}
6617
		var oLogicDocument;
6618 6619
		if(null != options.oDocumentMailMerge)
			oLogicDocument = options.oDocumentMailMerge;
6620 6621
		else
			oLogicDocument = editor.WordControl.m_oLogicDocument;
6622
		var oBinaryFileWriter;
6623
		if(null != options.oMailMergeSendData && c_oAscFileType.HTML == options.oMailMergeSendData.get_MailFormat())
6624 6625
			oBinaryFileWriter = new BinaryFileWriter(oLogicDocument, false, true);
		else
6626
			oBinaryFileWriter = new BinaryFileWriter(oLogicDocument);
6627
		dataContainer.data = oBinaryFileWriter.Write();
6628
	}
6629 6630
	if(null != options.oMailMergeSendData){
		oAdditionalData["mailmergesend"] = options.oMailMergeSendData;
6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647
		var MailMergeMap = editor.WordControl.m_oLogicDocument.MailMergeMap;
		var aJsonOut = [];
		if(MailMergeMap.length > 0){
			var oFirstRow = MailMergeMap[0];
			var aRowOut = [];
			for(var i in oFirstRow)
				aRowOut.push(i);
			aJsonOut.push(aRowOut);
		}
		//todo может надо запоминать порядок for in в первом столбце, если for in будет по-разному обходить строки
		for(var i = 0; i < MailMergeMap.length; ++i){
			var oRow = MailMergeMap[i];
			var aRowOut = [];
			for(var j in oRow)
				aRowOut.push(oRow[j]);
			aJsonOut.push(aRowOut);
		}
6648
		dataContainer.data = dataContainer.data.length + ';' + dataContainer.data + JSON.stringify(aJsonOut);
6649
	}
6650
    var fCallback = null;
6651
    if (!options.isNoCallback) {
6652 6653
        fCallback = function (input) {
          var error = c_oAscError.ID.Unknown;
6654 6655
          //input = {'type': command, 'status': 'err', 'data': -80};
          if (null != input && command == input['type']) {
6656 6657 6658
            if ('ok' == input['status']){
              if (options.isNoUrl) {
                error = c_oAscError.ID.No;
6659 6660
              } else {
                var url = input['data'];
6661
                if (url) {
6662 6663
                  error = c_oAscError.ID.No;
                  editor.processSavedFile(url, options.downloadType);
6664
                }
6665
              }
6666
            } else {
6667 6668
              error = g_fMapAscServerErrorToAscError(parseInt(input["data"]));
            }
6669 6670 6671
          }
          if (c_oAscError.ID.No != error) {
            editor.asc_fireCallback('asc_onError', options.errorDirect || error, c_oAscError.Level.NoCritical);
6672 6673
          }
          // Меняем тип состояния (на никакое)
6674
          editor.advancedOptionsAction = c_oAscAdvancedOptionsAction.None;
6675
          if (actionType) {
6676
            editor.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, actionType);
6677
          }
6678 6679
        };
    }
6680 6681
	editor.fCurCallback = fCallback;
	g_fSaveWithParts(function(fCallback1, oAdditionalData1, dataContainer1){sendCommand2(editor, fCallback1, oAdditionalData1, dataContainer1);}, fCallback, fCallbackRequest, oAdditionalData, dataContainer);
6682
}
6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707

function _addImageUrl2 (url)
{
	editor.AddImageUrl2 (url);
}
function _isDocumentModified2 ()
{
	return editor.isDocumentModified();
}
function  _asc_scrollTo (x,y)
{
	editor.WordControl.m_oScrollHorApi.scrollToX(x);
	editor.WordControl.m_oScrollVerApi.scrollToY(y);
}

function CErrorData()
{
    this.Value = 0;
}

CErrorData.prototype.put_Value = function(v){ this.Value = v; };
CErrorData.prototype.get_Value = function() { return this.Value; };
//test

// Вставка диаграмм
6708
asc_docs_api.prototype.asc_getChartObject = function(type)
6709
{	
Dmitry.Vikulov's avatar
Dmitry.Vikulov committed
6710
	this.isChartEditor = true;		// Для совместного редактирования
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
6711

Anna.Pavlova's avatar
Anna.Pavlova committed
6712

6713
    return this.WordControl.m_oLogicDocument.Get_ChartObject(type);
6714
};
6715

Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
6716
asc_docs_api.prototype.asc_addChartDrawingObject = function(options)
6717
{
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
6718 6719
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
6720
        History.Create_NewPoint(historydescription_Document_AddChart);
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
6721 6722
        this.WordControl.m_oLogicDocument.Add_InlineImage( null, null, null, options );
    }
6723
};
6724 6725
asc_docs_api.prototype.asc_doubleClickOnChart = function(obj)
{
6726
	this.WordControl.onMouseUpMainSimple();
6727 6728
    this.asc_fireCallback("asc_doubleClickOnChart", obj);
};
6729

Dmitry.Vikulov's avatar
Dmitry.Vikulov committed
6730
asc_docs_api.prototype.asc_editChartDrawingObject = function(chartBinary)
6731
{
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
6732
    /**/
Dmitry.Vikulov's avatar
Dmitry.Vikulov committed
6733 6734
	
	// Находим выделенную диаграмму и накатываем бинарник
Dmitry.Vikulov's avatar
Dmitry.Vikulov committed
6735 6736 6737
	if ( isObject(chartBinary) )
	{
		var binary = chartBinary["binary"];
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
6738 6739
        if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
        {
6740
            History.Create_NewPoint(historydescription_Document_EditChart);
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
6741 6742
            this.WordControl.m_oLogicDocument.Edit_Chart(binary);
        }
Dmitry.Vikulov's avatar
Dmitry.Vikulov committed
6743
	}
6744
};
6745 6746 6747 6748

asc_docs_api.prototype.sync_closeChartEditor = function()
{
    this.asc_fireCallback("asc_onCloseChartEditor");
6749
};
6750 6751 6752 6753 6754 6755

asc_docs_api.prototype.asc_setDrawCollaborationMarks = function (bDraw)
{
    if ( bDraw !== this.isCoMarksDraw )
    {
        this.isCoMarksDraw = bDraw;
6756 6757
        this.WordControl.m_oDrawingDocument.ClearCachePages();
        this.WordControl.m_oDrawingDocument.FirePaint();
6758
    }
6759
};
6760 6761

asc_docs_api.prototype.asc_AddMath = function(Type)
Oleg.Korshul's avatar
Oleg.Korshul committed
6762 6763
{
    var loader = window.g_font_loader;
6764
    var fontinfo = g_fontApplication.GetFontInfo("Cambria Math");
Oleg.Korshul's avatar
Oleg.Korshul committed
6765 6766 6767 6768 6769 6770 6771 6772 6773 6774
    var isasync = loader.LoadFont(fontinfo);
    if (false === isasync)
    {
        return this.asc_AddMath2(Type);
    }
    else
    {
        this.FontAsyncLoadType = 1;
        this.FontAsyncLoadParam = Type;
    }
6775
};
Oleg.Korshul's avatar
Oleg.Korshul committed
6776 6777

asc_docs_api.prototype.asc_AddMath2 = function(Type)
6778 6779 6780
{
    if ( false === this.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_Paragraph_Content) )
    {
6781
        this.WordControl.m_oLogicDocument.Create_NewHistoryPoint(historydescription_Document_AddMath);
6782
		var MathElement = new MathMenu (Type);
6783 6784
        this.WordControl.m_oLogicDocument.Paragraph_Add( MathElement );
    }
6785
};
6786

6787 6788 6789
//----------------------------------------------------------------------------------------------------------------------
// Функции для работы с MailMerge
//----------------------------------------------------------------------------------------------------------------------
6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805
asc_docs_api.prototype.asc_StartMailMerge = function(oData){};
asc_docs_api.prototype.asc_StartMailMergeByList = function(aList){};
asc_docs_api.prototype.asc_GetReceptionsCount = function(){};
asc_docs_api.prototype.asc_GetMailMergeFieldsNameList = function(){};
asc_docs_api.prototype.asc_AddMailMergeField = function(Name){};
asc_docs_api.prototype.asc_SetHighlightMailMergeFields = function(Value){};
asc_docs_api.prototype.asc_PreviewMailMergeResult = function(Index){};
asc_docs_api.prototype.asc_EndPreviewMailMergeResult = function(){};
asc_docs_api.prototype.sync_StartMailMerge = function(){};
asc_docs_api.prototype.sync_PreviewMailMergeResult = function(Index){};
asc_docs_api.prototype.sync_EndPreviewMailMergeResult = function(){};
asc_docs_api.prototype.sync_HighlightMailMergeFields = function(Value){};
asc_docs_api.prototype.asc_getMailMergeData = function(){};
asc_docs_api.prototype.asc_setMailMergeData = function(aList){};
asc_docs_api.prototype.asc_sendMailMergeData = function(oData){};
asc_docs_api.prototype.asc_GetMailMergeFiledValue = function(nIndex, sName){};
6806 6807 6808
//----------------------------------------------------------------------------------------------------------------------
// Работаем со стилями
//----------------------------------------------------------------------------------------------------------------------
6809 6810 6811 6812 6813 6814
asc_docs_api.prototype.asc_GetStyleFromFormatting = function(){return null;};
asc_docs_api.prototype.asc_AddNewStyle = function(oStyle){};
asc_docs_api.prototype.asc_RemoveStyle = function(sName){};
asc_docs_api.prototype.asc_RemoveAllCustomStyles = function(){};
asc_docs_api.prototype.asc_IsStyleDefault = function(sName){return true;};
asc_docs_api.prototype.asc_IsDefaultStyleChanged = function(sName){return false;};
6815 6816 6817
//----------------------------------------------------------------------------------------------------------------------
// Работаем с рецензированием
//----------------------------------------------------------------------------------------------------------------------
6818
asc_docs_api.prototype.asc_SetTrackRevisions = function(bTrack){};
6819
asc_docs_api.prototype.asc_IsTrackRevisions = function(){return false;};
6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831
asc_docs_api.prototype.sync_BeginCatchRevisionsChanges = function(){};
asc_docs_api.prototype.sync_EndCatchRevisionsChanges = function(){};
asc_docs_api.prototype.sync_AddRevisionsChange = function(Change){};
asc_docs_api.prototype.asc_AcceptChanges = function(Change){};
asc_docs_api.prototype.asc_RejectChanges = function(Change){};
asc_docs_api.prototype.asc_HaveRevisionsChanges = function(){return false};
asc_docs_api.prototype.asc_HaveNewRevisionsChanges = function(){return false};
asc_docs_api.prototype.asc_GetNextRevisionsChange = function(){};
asc_docs_api.prototype.asc_GetPrevRevisionsChange = function(){};
asc_docs_api.prototype.sync_UpdateRevisionsChangesPosition = function(X, Y){};
asc_docs_api.prototype.asc_AcceptAllChanges = function(){};
asc_docs_api.prototype.asc_RejectAllChanges = function(){};
6832

6833 6834
function CRevisionsChange()
{
6835 6836 6837 6838 6839 6840
    this.Type      = c_oAscRevisionsChangeType.Unknown;
    this.X         = 0;
    this.Y         = 0;
    this.Value     = "";

    this.UserName  = "";
6841 6842
    this.UserId    = "";
    this.DateTime  = "";
6843 6844 6845 6846

    this.Paragraph = null;
    this.StartPos  = null;
    this.EndPos    = null;
6847 6848 6849 6850 6851

    this._X       = 0;
    this._Y       = 0;
    this._PageNum = 0;
    this._PosChanged = false;
6852
}
6853 6854 6855 6856 6857 6858 6859 6860 6861 6862
CRevisionsChange.prototype.get_UserId = function(){return this.UserId;};
CRevisionsChange.prototype.put_UserId = function(UserId){this.UserId = UserId;};
CRevisionsChange.prototype.get_UserName = function(){return this.UserName;};
CRevisionsChange.prototype.put_UserName = function(UserName){this.UserName = UserName;};
CRevisionsChange.prototype.get_DateTime = function(){return this.DateTime};
CRevisionsChange.prototype.put_DateTime = function(DateTime){this.DateTime = DateTime};
CRevisionsChange.prototype.get_StartPos = function(){return this.StartPos};
CRevisionsChange.prototype.put_StartPos = function(StartPos){this.StartPos = StartPos;};
CRevisionsChange.prototype.get_EndPos = function(){return this.EndPos};
CRevisionsChange.prototype.put_EndPos = function(EndPos){this.EndPos = EndPos;};
6863 6864 6865 6866 6867 6868 6869
CRevisionsChange.prototype.get_Type  = function(){return this.Type;};
CRevisionsChange.prototype.get_X     = function(){return this.X;};
CRevisionsChange.prototype.get_Y     = function(){return this.Y;};
CRevisionsChange.prototype.get_Value = function(){return this.Value;};
CRevisionsChange.prototype.put_Type  = function(Type){this.Type = Type;};
CRevisionsChange.prototype.put_XY    = function(X, Y){this.X = X; this.Y = Y;};
CRevisionsChange.prototype.put_Value = function(Value){this.Value = Value;};
6870 6871 6872 6873
CRevisionsChange.prototype.put_Paragraph = function(Para)
{
    this.Paragraph = Para;
};
6874
CRevisionsChange.prototype.get_Paragraph = function(){return this.Paragraph;};
6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887
CRevisionsChange.prototype.get_LockUserId = function()
{
    if (this.Paragraph)
    {
        var Lock = this.Paragraph.Get_Lock();
        var LockType = Lock.Get_Type();

        if (locktype_Mine !== LockType && locktype_None !== LockType)
            return Lock.Get_UserId();
    }

    return null;
};
6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919
CRevisionsChange.prototype.put_InternalPos = function(x, y, pageNum)
{
    if (this._PageNum !== pageNum
        || Math.abs(this._X - x) > 0.001
        || Math.abs(this._Y - y) > 0.001)
    {
        this._X = x;
        this._Y = y;
        this._PageNum = pageNum;
        this._PosChanged = true;
    }
    else
    {
        this._PosChanged = false;
    }
};
CRevisionsChange.prototype.get_InternalPosX = function()
{
    return this._X;
};
CRevisionsChange.prototype.get_InternalPosY = function()
{
    return this._Y;
};
CRevisionsChange.prototype.get_InternalPosPageNum = function()
{
    return this._PageNum;
};
CRevisionsChange.prototype.ComparePrevPosition = function()
{
    if (true === this._PosChanged)
        return false;
6920

6921 6922
    return true;
};
6923

6924
asc_docs_api.prototype.asc_stopSaving = function () {
6925
	this.asc_IncrementCounterLongAction();
6926 6927
};
asc_docs_api.prototype.asc_continueSaving = function () {
6928
	this.asc_DecrementCounterLongAction();
6929
};
6930

6931 6932 6933
asc_docs_api.prototype.asc_undoAllChanges = function ()
{
    this.WordControl.m_oLogicDocument.Document_Undo({All : true});
6934
};
6935
asc_docs_api.prototype.asc_CloseFile = function()
6936 6937
{
    History.Clear();
6938
	g_oIdCounter.Clear();
6939
    g_oTableId.Clear();
6940
    CollaborativeEditing.Clear();
6941
	this.isApplyChangesOnOpenEnabled = true;
6942

6943 6944 6945 6946
	var oLogicDocument = this.WordControl.m_oLogicDocument;
	oLogicDocument.Stop_Recalculate();
	oLogicDocument.Stop_CheckSpelling();
	window.global_pptx_content_loader.ImageMapChecker = {};
6947 6948

    this.WordControl.m_oDrawingDocument.CloseFile();
6949
};
6950 6951 6952 6953 6954
asc_docs_api.prototype.asc_SetFastCollaborative = function(isOn)
{
    if (CollaborativeEditing)
        CollaborativeEditing.Set_Fast(isOn);
};
6955

Oleg.Korshul's avatar
Oleg.Korshul committed
6956
window["asc_docs_api"] = asc_docs_api;
6957
window["asc_docs_api"].prototype["asc_nativeOpenFile"] = function(base64File, version)
Oleg.Korshul's avatar
Oleg.Korshul committed
6958
{
6959
	this.SpellCheckUrl = '';
6960 6961

	this.User = new Asc.asc_CUser();
Oleg.Korshul's avatar
Oleg.Korshul committed
6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976
	this.User.asc_setId("TM");
	this.User.asc_setUserName("native");
	
	this.WordControl.m_bIsRuler = false;
	this.WordControl.Init();
	
	this.InitEditor();
	this.DocumentType = 2;
	this.LoadedObjectDS = Common_CopyObj(this.WordControl.m_oLogicDocument.Get_Styles().Style);
	
	g_oIdCounter.Set_Load(true);

	var openParams = {checkFileSize: this.isMobileVersion, charCount: 0, parCount: 0};
	var oBinaryFileReader = new BinaryFileReader(this.WordControl.m_oLogicDocument, openParams);

6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001
    if (undefined === version)
    {
        if (oBinaryFileReader.Read(base64File))
        {
            g_oIdCounter.Set_Load(false);
            this.LoadedObject = 1;

            this.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.Open);
        }
        else
            this.asc_fireCallback("asc_onError", c_oAscError.ID.MobileUnexpectedCharCount, c_oAscError.Level.Critical);
    }
    else
    {
        g_nCurFileVersion = version;		
        if(oBinaryFileReader.ReadData(base64File))
        {
            g_oIdCounter.Set_Load(false);
            this.LoadedObject = 1;

            this.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.Open);
        }
        else
            this.asc_fireCallback("asc_onError",c_oAscError.ID.MobileUnexpectedCharCount,c_oAscError.Level.Critical);
    }
Oleg.Korshul's avatar
Oleg.Korshul committed
7002 7003 7004

    if (undefined != window["Native"])
        return;
Oleg.Korshul's avatar
Oleg.Korshul committed
7005 7006 7007 7008 7009 7010 7011 7012 7013 7014
		
	//callback
	this.DocumentOrientation = (null == editor.WordControl.m_oLogicDocument) ? true : !editor.WordControl.m_oLogicDocument.Orientation;
	var sizeMM;
	if(this.DocumentOrientation)
		sizeMM = DocumentPageSize.getSize(Page_Width, Page_Height);
	else
		sizeMM = DocumentPageSize.getSize(Page_Height, Page_Width);
	this.sync_DocSizeCallback(sizeMM.w_mm, sizeMM.h_mm);
	this.sync_PageOrientCallback(editor.get_DocumentOrientation());
Oleg.Korshul's avatar
Oleg.Korshul committed
7015 7016 7017 7018

    if (this.GenerateNativeStyles !== undefined)
    {
        this.GenerateNativeStyles();
Oleg.Korshul's avatar
Oleg.Korshul committed
7019 7020 7021

        if (this.WordControl.m_oDrawingDocument.CheckTableStylesOne !== undefined)
            this.WordControl.m_oDrawingDocument.CheckTableStylesOne();
Oleg.Korshul's avatar
Oleg.Korshul committed
7022
    }
7023
};
Oleg.Korshul's avatar
Oleg.Korshul committed
7024 7025 7026 7027 7028 7029 7030
window["asc_docs_api"].prototype["asc_nativeCalculateFile"] = function()
{
    if (null == this.WordControl.m_oLogicDocument)
        return;

    var Document = this.WordControl.m_oLogicDocument;

7031
    if ((window["NATIVE_EDITOR_ENJINE"] === undefined) && this.isApplyChangesOnOpenEnabled)
Oleg.Korshul's avatar
Oleg.Korshul committed
7032 7033
    {
        this.isApplyChangesOnOpenEnabled = false;
7034
        if (1 === CollaborativeEditing.m_nUseType)
Oleg.Korshul's avatar
Oleg.Korshul committed
7035 7036 7037 7038 7039 7040
        {
            this.isApplyChangesOnOpen = true;
            CollaborativeEditing.Apply_Changes();
            CollaborativeEditing.Release_Locks();
            return;
        }
7041
    }
Oleg.Korshul's avatar
Oleg.Korshul committed
7042 7043 7044

    Document.CurPos.ContentPos = 0;

7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057
    var RecalculateData =
    {
        Inline : { Pos : 0, PageNum : 0 },
        Flow   : [],
        HdrFtr : [],
        Drawings: {
            All: true,
            Map:{}
        }
    };

    Document.Recalculate(false, false, RecalculateData);

7058 7059 7060 7061
    Document.Document_UpdateInterfaceState();
    //Document.Document_UpdateRulersState();
    Document.Document_UpdateSelectionState();

Oleg.Korshul's avatar
Oleg.Korshul committed
7062
    this.ShowParaMarks = false;
7063
};
Oleg.Korshul's avatar
Oleg.Korshul committed
7064 7065 7066

window["asc_docs_api"].prototype["asc_nativeApplyChanges"] = function(changes)
{
Oleg.Korshul's avatar
Oleg.Korshul committed
7067
    this._coAuthoringSetChanges(changes, new CDocumentColor( 191, 255, 199 ));
Oleg.Korshul's avatar
Oleg.Korshul committed
7068
	CollaborativeEditing.Apply_OtherChanges();
7069
};
Oleg.Korshul's avatar
Oleg.Korshul committed
7070

Oleg.Korshul's avatar
Oleg.Korshul committed
7071
window["asc_docs_api"].prototype["asc_nativeApplyChanges2"] = function(data, isFull)
Oleg.Korshul's avatar
Oleg.Korshul committed
7072 7073 7074 7075 7076 7077
{
    // Чтобы заново созданные параграфы не отображались залоченными
    g_oIdCounter.Set_Load( true );
	
    var stream = new FT_Stream2(data, data.length);
    stream.obj = null;
7078
    var Loader = { Reader : stream, Reader2 : null };
Oleg.Korshul's avatar
Oleg.Korshul committed
7079 7080 7081 7082
    var _color = new CDocumentColor( 191, 255, 199 );

    // Применяем изменения, пока они есть
    var _count = Loader.Reader.GetLong();
7083

Oleg.Korshul's avatar
Oleg.Korshul committed
7084 7085 7086 7087 7088 7089 7090 7091
    var _pos = 4;
    for (var i = 0; i < _count; i++)
    {
        if (window["NATIVE_EDITOR_ENJINE"] === true && window["native"]["CheckNextChange"])
        {
            if (!window["native"]["CheckNextChange"]())
                break;
        }
7092

Oleg.Korshul's avatar
Oleg.Korshul committed
7093
        var _len = Loader.Reader.GetLong();
7094 7095 7096 7097 7098
        _pos += 4;
        stream.size = _pos + _len;

        var _id  = Loader.Reader.GetString2();
        var _read_pos = Loader.Reader.GetCurPos();
Oleg.Korshul's avatar
Oleg.Korshul committed
7099 7100 7101 7102 7103 7104 7105 7106 7107

        var Type = Loader.Reader.GetLong();
        var Class = null;

        if ( historyitem_type_HdrFtr === Type )
        {
            Class = editor.WordControl.m_oLogicDocument.HdrFtr;
        }
        else
7108
            Class = g_oTableId.Get_ById( _id );
Oleg.Korshul's avatar
Oleg.Korshul committed
7109

7110 7111
        stream.Seek(_read_pos);
        stream.Seek2(_read_pos);
Oleg.Korshul's avatar
Oleg.Korshul committed
7112 7113 7114 7115 7116 7117 7118 7119 7120

        if ( null != Class )
            Class.Load_Changes( Loader.Reader, Loader.Reader2, _color );

        _pos += _len;
		stream.Seek2(_pos);
		stream.size = data.length;
    }

Oleg.Korshul's avatar
Oleg.Korshul committed
7121 7122 7123
    if (isFull)
    {
        CollaborativeEditing.m_aChanges = [];
Oleg.Korshul's avatar
Oleg.Korshul committed
7124

Oleg.Korshul's avatar
Oleg.Korshul committed
7125 7126
        // У новых элементов выставляем указатели на другие классы
        CollaborativeEditing.Apply_LinkData();
Oleg.Korshul's avatar
Oleg.Korshul committed
7127

Oleg.Korshul's avatar
Oleg.Korshul committed
7128 7129
        // Делаем проверки корректности новых изменений
        CollaborativeEditing.Check_MergeData();
Oleg.Korshul's avatar
Oleg.Korshul committed
7130

Oleg.Korshul's avatar
Oleg.Korshul committed
7131
        CollaborativeEditing.OnEnd_ReadForeignChanges();
7132

Oleg.Korshul's avatar
Oleg.Korshul committed
7133 7134 7135 7136 7137 7138 7139 7140
        if (window["NATIVE_EDITOR_ENJINE"] === true && window["native"]["AddImageInChanges"])
        {
            var _new_images = CollaborativeEditing.m_aNewImages;
            var _new_images_len = _new_images.length;

            for (var nImage = 0; nImage < _new_images_len; nImage++)
                window["native"]["AddImageInChanges"](_new_images[nImage]);
        }
Oleg.Korshul's avatar
Oleg.Korshul committed
7141
    }
Oleg.Korshul's avatar
Oleg.Korshul committed
7142 7143 7144 7145

    g_oIdCounter.Set_Load( false );
};

Oleg.Korshul's avatar
Oleg.Korshul committed
7146 7147 7148 7149
window["asc_docs_api"].prototype["asc_nativeGetFile"] = function()
{
	var oBinaryFileWriter = new BinaryFileWriter(this.WordControl.m_oLogicDocument);
    return oBinaryFileWriter.Write();
7150
};
Oleg.Korshul's avatar
Oleg.Korshul committed
7151

Oleg.Korshul's avatar
Oleg.Korshul committed
7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164
window["asc_docs_api"].prototype["asc_nativeGetFileData"] = function()
{
    var oBinaryFileWriter = new BinaryFileWriter(this.WordControl.m_oLogicDocument);
    var _memory = oBinaryFileWriter.memory;

    oBinaryFileWriter.Write2();

	var _header = c_oSerFormat.Signature + ";v" + c_oSerFormat.Version + ";" + _memory.GetCurPosition() + ";";
	window["native"]["Save_End"](_header, _memory.GetCurPosition());
	
	return _memory.ImData.data;
};

7165 7166
window["asc_docs_api"].prototype["asc_nativeGetHtml"] = function()
{
Oleg.Korshul's avatar
Oleg.Korshul committed
7167 7168
    var _old = copyPasteUseBinary;
    copyPasteUseBinary = false;
7169
    this.WordControl.m_oLogicDocument.Select_All();
Oleg.Korshul's avatar
Oleg.Korshul committed
7170
    var oCopyProcessor = new CopyProcessor(this);
7171
    oCopyProcessor.Start();
7172
    var _ret = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body>" + oCopyProcessor.getInnerHtml() + "</body></html>";
7173
    this.WordControl.m_oLogicDocument.Selection_Remove();
Oleg.Korshul's avatar
Oleg.Korshul committed
7174
    copyPasteUseBinary = _old;
7175 7176 7177
    return _ret;
};

Oleg.Korshul's avatar
Oleg.Korshul committed
7178 7179 7180 7181 7182 7183 7184 7185 7186 7187
window["asc_docs_api"].prototype["asc_AddHtml"] = function(_iframeId)
{
    var ifr = document.getElementById(_iframeId);

    var frameWindow = window.frames[_iframeId];
    if (frameWindow)
    {
        if(null != frameWindow.document && null != frameWindow.document.body)
        {
            ifr.style.display  = "block";
7188
            this.WordControl.m_oLogicDocument.TurnOffHistory();
Oleg.Korshul's avatar
Oleg.Korshul committed
7189
            Editor_Paste_Exec(this, frameWindow.document.body, ifr);
7190
            this.WordControl.m_oLogicDocument.TurnOnHistory();
Oleg.Korshul's avatar
Oleg.Korshul committed
7191 7192 7193 7194 7195 7196 7197
        }
    }

    if (ifr)
        document.body.removeChild(ifr);
};

Oleg.Korshul's avatar
Oleg.Korshul committed
7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226
window["asc_docs_api"].prototype["asc_nativeCheckPdfRenderer"] = function(_memory1, _memory2)
{
	if (true)
	{
		// pos не должен минимизироваться!!!

		_memory1.Copy           = _memory1["Copy"];
		_memory1.ClearNoAttack  = _memory1["ClearNoAttack"];
		_memory1.WriteByte      = _memory1["WriteByte"];
		_memory1.WriteBool      = _memory1["WriteBool"];
		_memory1.WriteLong      = _memory1["WriteLong"];
		_memory1.WriteDouble    = _memory1["WriteDouble"];
		_memory1.WriteString    = _memory1["WriteString"];
		_memory1.WriteString2   = _memory1["WriteString2"];
		
		_memory2.Copy           = _memory1["Copy"];
		_memory2.ClearNoAttack  = _memory1["ClearNoAttack"];
		_memory2.WriteByte      = _memory1["WriteByte"];
		_memory2.WriteBool      = _memory1["WriteBool"];
		_memory2.WriteLong      = _memory1["WriteLong"];
		_memory2.WriteDouble    = _memory1["WriteDouble"];
		_memory2.WriteString    = _memory1["WriteString"];
		_memory2.WriteString2   = _memory1["WriteString2"];
	}
	
	var _printer = new CDocumentRenderer();
	_printer.Memory				    = _memory1;
	_printer.VectorMemoryForPrint	= _memory2;
	return _printer;
7227
};
Oleg.Korshul's avatar
Oleg.Korshul committed
7228 7229 7230

window["asc_docs_api"].prototype["asc_nativeCalculate"] = function()
{
7231
};
Oleg.Korshul's avatar
Oleg.Korshul committed
7232 7233 7234

window["asc_docs_api"].prototype["asc_nativePrint"] = function(_printer, _page)
{
7235 7236 7237 7238 7239 7240 7241
    if (undefined === _printer && _page === undefined)
    {
        if (undefined !== window["AscDesktopEditor"])
        {
            var _drawing_document = this.WordControl.m_oDrawingDocument;
            var pagescount = Math.min(_drawing_document.m_lPagesCount, _drawing_document.m_lCountCalculatePages);

Oleg.Korshul's avatar
Oleg.Korshul committed
7242
            window["AscDesktopEditor"]["Print_Start"](this.DocumentUrl, pagescount, "", this.getCurrentPage());
7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258

            var oDocRenderer = new CDocumentRenderer();
            oDocRenderer.VectorMemoryForPrint = new CMemory();
            var bOldShowMarks = this.ShowParaMarks;
            this.ShowParaMarks = false;

            for (var i = 0; i < pagescount; i++)
            {
                oDocRenderer.Memory.Seek(0);
                oDocRenderer.VectorMemoryForPrint.ClearNoAttack();

                var page = _drawing_document.m_arrPages[i];
                oDocRenderer.BeginPage(page.width_mm, page.height_mm);
                this.WordControl.m_oLogicDocument.DrawPage(i, oDocRenderer);
                oDocRenderer.EndPage();

7259
                window["AscDesktopEditor"]["Print_Page"](oDocRenderer.Memory.GetBase64Memory(), page.width_mm, page.height_mm);
7260 7261 7262 7263 7264 7265 7266 7267 7268
            }

            this.ShowParaMarks = bOldShowMarks;

            window["AscDesktopEditor"]["Print_End"]();
        }
        return;
    }

Oleg.Korshul's avatar
Oleg.Korshul committed
7269 7270 7271 7272
	var page = this.WordControl.m_oDrawingDocument.m_arrPages[_page];
    _printer.BeginPage(page.width_mm, page.height_mm);
    this.WordControl.m_oLogicDocument.DrawPage(_page, _printer);
    _printer.EndPage();
7273
};
Oleg.Korshul's avatar
Oleg.Korshul committed
7274 7275 7276 7277

window["asc_docs_api"].prototype["asc_nativePrintPagesCount"] = function()
{
	return this.WordControl.m_oDrawingDocument.m_lPagesCount;
Oleg.Korshul's avatar
Oleg.Korshul committed
7278 7279
};

7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300
window["asc_docs_api"].prototype["asc_nativeGetPDF"] = function()
{
    var pagescount = this["asc_nativePrintPagesCount"]();

    var _renderer = new CDocumentRenderer();
    _renderer.VectorMemoryForPrint = new CMemory();
    var _bOldShowMarks = this.ShowParaMarks;
    this.ShowParaMarks = false;

    for (var i = 0; i < pagescount; i++)
    {
        this["asc_nativePrint"](_renderer, i);
    }

    this.ShowParaMarks = _bOldShowMarks;

    window["native"]["Save_End"]("", _renderer.Memory.GetCurPosition());

    return _renderer.Memory.data;
};

Oleg.Korshul's avatar
Oleg.Korshul committed
7301
// cool api (autotests)
7302
window["asc_docs_api"].prototype["Add_Text"] = function(_text)
Oleg.Korshul's avatar
Oleg.Korshul committed
7303 7304 7305
{
    this.WordControl.m_oLogicDocument.TextBox_Put(_text);
};
7306
window["asc_docs_api"].prototype["Add_NewParagraph"] = function()
Oleg.Korshul's avatar
Oleg.Korshul committed
7307
{
7308 7309 7310 7311 7312 7313
    var LogicDocument = this.WordControl.m_oLogicDocument;
    if (false === LogicDocument.Document_Is_SelectionLocked(changestype_Document_Content_Add))
    {
        LogicDocument.Create_NewHistoryPoint(historydescription_Document_EnterButton);
        LogicDocument.Add_NewParagraph(true);
    }
Oleg.Korshul's avatar
Oleg.Korshul committed
7314
};
7315
window["asc_docs_api"].prototype["Cursor_MoveLeft"] = function()
Oleg.Korshul's avatar
Oleg.Korshul committed
7316 7317 7318
{
    this.WordControl.m_oLogicDocument.Cursor_MoveLeft();
};
7319
window["asc_docs_api"].prototype["Cursor_MoveRight"] = function()
Oleg.Korshul's avatar
Oleg.Korshul committed
7320 7321 7322
{
    this.WordControl.m_oLogicDocument.Cursor_MoveRight();
};
7323
window["asc_docs_api"].prototype["Cursor_MoveUp"] = function()
Oleg.Korshul's avatar
Oleg.Korshul committed
7324 7325 7326
{
    this.WordControl.m_oLogicDocument.Cursor_MoveUp();
};
7327
window["asc_docs_api"].prototype["Cursor_MoveDown"] = function()
Oleg.Korshul's avatar
Oleg.Korshul committed
7328 7329 7330
{
    this.WordControl.m_oLogicDocument.Cursor_MoveDown();
};
Oleg.Korshul's avatar
 
Oleg.Korshul committed
7331
window["asc_docs_api"].prototype["Get_DocumentRecalcId"] = function()
7332 7333 7334
{
    return this.WordControl.m_oLogicDocument.RecalcId;
};
7335
window["asc_docs_api"].prototype["asc_IsSpellCheckCurrentWord"] = function()
Oleg.Korshul's avatar
Oleg.Korshul committed
7336 7337 7338
{
	return this.IsSpellCheckCurrentWord;
};
7339
window["asc_docs_api"].prototype["asc_putSpellCheckCurrentWord"] = function(value)
Oleg.Korshul's avatar
Oleg.Korshul committed
7340 7341
{
	this.IsSpellCheckCurrentWord = value;
Oleg.Korshul's avatar
Oleg.Korshul committed
7342 7343
};

Oleg.Korshul's avatar
Oleg.Korshul committed
7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364
// desktop editor spellcheck
function CSpellCheckApi_desktop()
{
    this.docId  = undefined;

    this.init = function(docid)
    {
        this.docId = docid;
    };

    this.set_url = function(url) {};

    this.spellCheck = function(spellData)
    {
        window["AscDesktopEditor"]["SpellCheck"](spellData);
    };

    this.onSpellCheck = function(spellData)
    {
        SpellCheck_CallBack(spellData);
    };
Oleg.Korshul's avatar
Oleg.Korshul committed
7365 7366 7367 7368 7369

    this.disconnect = function()
    {
        // none
    };
7370 7371 7372 7373
}

window["AscDesktopEditor_Save"] = function()
{
7374
    return editor.asc_Save(false);
7375
};