Back to index

scribus-ng  1.3.4.dfsg+svn20071115
scribusdoc.cpp
Go to the documentation of this file.
00001 /*
00002 For general Scribus (>=1.3.2) copyright and licensing information please refer
00003 to the COPYING file provided with the program. Following this notice may exist
00004 a copyright and/or license notice that predates the release of Scribus 1.3.2
00005 for which a new license (GPL+exception) is in place.
00006 */
00007 /***************************************************************************
00008                           scribusdoc.cpp  -  description
00009                              -------------------
00010     begin                : Fre Apr  6 21:47:55 CEST 2001
00011     copyright            : (C) 2001 by Franz Schmid
00012     email                : Franz.Schmid@altmuehlnet.de
00013  ***************************************************************************/
00014 
00015 /***************************************************************************
00016  *                                                                         *
00017  *   This program is free software; you can redistribute it and/or modify  *
00018  *   it under the terms of the GNU General Public License as published by  *
00019  *   the Free Software Foundation; either version 2 of the License, or     *
00020  *   (at your option) any later version.                                   *
00021  *                                                                         *
00022  ***************************************************************************/
00023 #include "scribusdoc.moc"
00024 #include "scribus.h"
00025 #include "scribuscore.h"
00026 #include "scribusdoc.h"
00027 #include "scribusview.h"
00028 #include "scribuswin.h"
00029 #include "guidemanager.h"
00030 #include "seiten.h"
00031 
00032 #include <utility>
00033 #include <qeventloop.h>
00034 
00035 #include <qfile.h>
00036 #include <qpainter.h>
00037 #include <qprogressbar.h>
00038 
00039 #include "fileloader.h"
00040 #include "filewatcher.h"
00041 //CBVTD
00042 #include "hruler.h"
00043 #include "hyphenator.h"
00044 #include "layers.h"
00045 #include "page.h"
00046 #include "pageitem.h"
00047 #include "pageitem_imageframe.h"
00048 #include "pageitem_line.h"
00049 #include "pageitem_pathtext.h"
00050 #include "pageitem_polygon.h"
00051 #include "pageitem_polyline.h"
00052 #include "pageitem_textframe.h"
00053 #include "pagestructs.h"
00054 #include "prefsfile.h"
00055 #include "prefsmanager.h"
00056 #include "resourcecollection.h"
00057 #include "scmessagebox.h"
00058 #include "scpainter.h"
00059 #include "scraction.h"
00060 #include "scribusXml.h"
00061 #include "selection.h"
00062 #include "story.h"
00063 // #include "tree.h"
00064 #include "undomanager.h"
00065 #include "undostate.h"
00066 #include "units.h"
00067 #include "util.h"
00068 #include "commonstrings.h"
00069 #include "sccolorengine.h"
00070 
00071 #include "text/nlsconfig.h"
00072 
00073 #include "cmsutil.h"
00074 #include "cmserrorhandling.h"
00075 
00076 extern QPixmap loadIcon(QString nam);
00077 
00078 static const bool FRAMESELECTION_EDITS_DEFAULTSTYLE = false;
00079 
00080 ScribusDoc::ScribusDoc() : UndoObject( tr("Document")),
00081        m_hasGUI(false),
00082        prefsData(PrefsManager::instance()->appPrefs),
00083        undoManager(UndoManager::instance()),
00084        loading(false),
00085        modified(false),
00086        ActiveLayer(0),
00087        docUnitIndex(prefsData.docUnitIndex),
00088        docUnitRatio(unitGetRatioFromIndex(docUnitIndex)),
00089        automaticTextFrames(0),
00090        m_masterPageMode(false),
00091        m_ScMW(0),
00092        m_View(0),
00093        m_guardedObject(this),
00094        is12doc(false),
00095        NrItems(0),
00096        First(1), Last(0),
00097        viewCount(0), viewID(0),
00098        SnapGuides(false), GuideLock(false),
00099        scratch(prefsData.scratch),
00100 //     ScratchLeft(prefsData.ScratchLeft),
00101 //     ScratchRight(prefsData.ScratchRight),
00102 //     ScratchTop(prefsData.ScratchTop),
00103 //     ScratchBottom(prefsData.ScratchBottom),
00104        minCanvasCoordinate(FPoint(0, 0)),
00105        maxCanvasCoordinate(FPoint(scratch.Left + scratch.Right, scratch.Top + scratch.Bottom)),
00106        rulerXoffset(0.0), rulerYoffset(0.0),
00107        Pages(0), MasterPages(), DocPages(),
00108        MasterNames(),
00109        Items(0), MasterItems(), DocItems(), FrameItems(),
00110        m_Selection(new Selection(this, true)),
00111        pageWidth(0), pageHeight(0),
00112        pageSets(prefsData.pageSets),
00113        PageSp(1), PageSpa(0),
00114        currentPageLayout(0),
00115        PageOri(0), m_pageSize(0),
00116        FirstPnum(1),
00117        useRaster(false),
00118        PageColors(this, true),
00119        appMode(modeNormal),
00120        SubMode(-1),
00121        ShapeValues(0),
00122        ValCount(0),
00123        DocName( tr("Document")+"-"),
00124        UsedFonts(),
00125        AllFonts(&prefsData.AvailFonts),
00126        AObjects(),
00127        papColor(prefsData.DpapColor),
00128        CurrentSel(-1),
00129        EditClip(false),
00130        EditClipMode(0),
00131        typographicSettings(prefsData.typographicSettings),
00132        guidesSettings(prefsData.guidesSettings),
00133        toolSettings(prefsData.toolSettings),
00134        checkerProfiles(prefsData.checkerProfiles),
00135        curCheckProfile(prefsData.curCheckProfile),
00136        LastAuto(0), FirstAuto(0),
00137        DraggedElem(0),
00138        ElemToLink(0),
00139        DragElements(),
00140        docParagraphStyles(),
00141        docCharStyles(),
00142        Layers(),
00143        marginColored(prefsData.marginColored),
00144        GroupCounter(1),
00145        JavaScripts(),
00146        TotalItems(0),
00147        MinWordLen(prefsData.MinWordLen),
00148        HyCount(prefsData.HyCount),
00149        Language(prefsData.Language),
00150        Automatic(prefsData.Automatic),
00151        AutoCheck(prefsData.AutoCheck),
00152        PDF_Options(prefsData.PDF_Options),
00153        RePos(false),
00154        BookMarks(),
00155        OldBM(false),
00156        hasName(false),
00157        RotMode(0),
00158        AutoSave(prefsData.AutoSave),
00159        AutoSaveTime(prefsData.AutoSaveTime),
00160        autoSaveTimer(new QTimer(this)),
00161        MLineStyles(),
00162        arrowStyles(prefsData.arrowStyles),
00163        WinHan(0),
00164        DoDrawing(true),
00165        OpenNodes(),
00166        CurTimer(0),
00167        docLayerErrors(),
00168        docItemErrors(),
00169        masterItemErrors(),
00170        docItemAttributes(prefsData.defaultItemAttributes),
00171        docToCSetups(prefsData.defaultToCSetups),
00172        // sections
00173        symReturn(), symNewLine(), symTab(), symNonBreak(), symNewCol(), symNewFrame(),
00174        docHyphenator(0),
00175        _itemCreationTransactionStarted(false)
00176 {
00177        init();
00178        bleeds = prefsData.bleeds;
00179        PDF_Options.bleeds = bleeds;
00180        Print_Options.firstUse = true;
00181 }
00182 
00183 ScribusDoc::ScribusDoc(const QString& docName, int unitindex, const PageSize& pagesize, const MarginStruct& margins, const DocPagesSetup& pagesSetup) : UndoObject( tr("Document")),
00184        m_hasGUI(false),
00185        prefsData(PrefsManager::instance()->appPrefs),
00186        undoManager(UndoManager::instance()),
00187        loading(false),
00188        modified(false),
00189        ActiveLayer(0),
00190        docUnitIndex(unitindex),
00191        docUnitRatio(unitGetRatioFromIndex(docUnitIndex)),
00192        automaticTextFrames(pagesSetup.autoTextFrames),
00193        m_masterPageMode(false),
00194        m_ScMW(0),
00195        m_View(0),
00196        m_guardedObject(this),
00197        is12doc(false),
00198        NrItems(0),
00199        First(1), Last(0),
00200        viewCount(0), viewID(0),
00201        SnapGuides(false), GuideLock(false),
00202        scratch(prefsData.scratch),
00203 //     ScratchLeft(prefsData.ScratchLeft),
00204 //     ScratchRight(prefsData.ScratchRight),
00205 //     ScratchTop(prefsData.ScratchTop),
00206 //     ScratchBottom(prefsData.ScratchBottom),
00207        minCanvasCoordinate(FPoint(0, 0)),
00208        maxCanvasCoordinate(FPoint(scratch.Left + scratch.Right, scratch.Top + scratch.Bottom)),
00209        rulerXoffset(0.0), rulerYoffset(0.0),
00210        Pages(0), MasterPages(), DocPages(),
00211        MasterNames(),
00212        Items(0), MasterItems(), DocItems(), FrameItems(),
00213        m_Selection(new Selection(this, true)),
00214        pageWidth(pagesize.width()), pageHeight(pagesize.height()),
00215        pageMargins(margins),
00216        pageSets(prefsData.pageSets),
00217        PageSp(pagesSetup.columnCount), PageSpa(pagesSetup.columnDistance),
00218        currentPageLayout(pagesSetup.pageArrangement),
00219        PageOri(pagesSetup.orientation), m_pageSize(pagesize.name()),
00220        FirstPnum(pagesSetup.firstPageNumber),
00221        useRaster(false),
00222        PageColors(this, true),
00223        appMode(modeNormal),
00224        SubMode(-1),
00225        ShapeValues(0),
00226        ValCount(0),
00227        DocName(docName),
00228        UsedFonts(),
00229        AllFonts(&prefsData.AvailFonts),
00230        AObjects(),
00231        papColor(prefsData.DpapColor),
00232        CurrentSel(-1),
00233        EditClip(false),
00234        EditClipMode(0),
00235        typographicSettings(prefsData.typographicSettings),
00236        guidesSettings(prefsData.guidesSettings),
00237        toolSettings(prefsData.toolSettings),
00238        checkerProfiles(prefsData.checkerProfiles),
00239        curCheckProfile(prefsData.curCheckProfile),
00240        LastAuto(0), FirstAuto(0),
00241        DraggedElem(0),
00242        ElemToLink(0),
00243        DragElements(),
00244        docParagraphStyles(),
00245        docCharStyles(),
00246        Layers(),
00247        marginColored(prefsData.marginColored),
00248        GroupCounter(1),
00249        JavaScripts(),
00250        TotalItems(0),
00251        MinWordLen(prefsData.MinWordLen),
00252        HyCount(prefsData.HyCount),
00253        Language(prefsData.Language),
00254        Automatic(prefsData.Automatic),
00255        AutoCheck(prefsData.AutoCheck),
00256        PDF_Options(prefsData.PDF_Options),
00257        RePos(false),
00258        BookMarks(),
00259        OldBM(false),
00260        hasName(false),
00261        RotMode(0),
00262        AutoSave(prefsData.AutoSave),
00263        AutoSaveTime(prefsData.AutoSaveTime),
00264        autoSaveTimer(new QTimer(this)),
00265        MLineStyles(),
00266        arrowStyles(prefsData.arrowStyles),
00267        WinHan(0),
00268        DoDrawing(true),
00269        OpenNodes(),
00270        CurTimer(0),
00271        docLayerErrors(),
00272        docItemErrors(),
00273        masterItemErrors(),
00274        docItemAttributes(prefsData.defaultItemAttributes),
00275        docToCSetups(prefsData.defaultToCSetups),
00276        // sections
00277        symReturn(), symNewLine(), symTab(), symNonBreak(), symNewCol(), symNewFrame(),
00278        docHyphenator(0),
00279        _itemCreationTransactionStarted(false)
00280 {
00281        pageSets[pagesSetup.pageArrangement].FirstPage = pagesSetup.firstPageLocation;
00282        init();
00283        bleeds = prefsData.bleeds;
00284        PDF_Options.bleeds = bleeds;
00285        Print_Options.firstUse = true;
00286 }
00287 
00288 void ScribusDoc::init()
00289 {
00290        Q_CHECK_PTR(m_Selection);
00291        Q_CHECK_PTR(autoSaveTimer);
00292 
00293        HasCMS = false;
00294        CMSSettings.CMSinUse = false;
00295 
00296        DocInputRGBProf = NULL;
00297        DocInputCMYKProf = NULL;
00298        DocInputImageRGBProf = NULL;
00299        DocInputImageCMYKProf = NULL;
00300        DocOutputProf = NULL;
00301        DocPrinterProf = NULL;
00302        stdTransRGBMon = NULL;
00303        stdTransCMYKMon = NULL;
00304        stdProof = NULL;
00305        stdTransImg = NULL;
00306        stdProofImg = NULL;
00307        stdTransCMYK = NULL;
00308        stdProofCMYK = NULL;
00309        stdTransRGB = NULL;
00310        stdProofGC = NULL;
00311        stdProofCMYKGC = NULL;
00312 
00313        PrefsManager *prefsManager = PrefsManager::instance();
00314        CMSSettings = prefsManager->appPrefs.DCMSset;
00315        PDF_Options.SolidProf = CMSSettings.DefaultSolidColorRGBProfile;
00316        PDF_Options.ImageProf = CMSSettings.DefaultImageRGBProfile;
00317        PDF_Options.PrintProf = CMSSettings.DefaultPrinterProfile;
00318        PDF_Options.Intent = CMSSettings.DefaultIntentColors;
00319        PDF_Options.Intent2 = CMSSettings.DefaultIntentImages;
00320 
00321        AddFont(prefsData.toolSettings.defFont);//, prefsData.AvailFonts[prefsData.toolSettings.defFont]->Font);
00322        toolSettings.defFont = prefsData.toolSettings.defFont;
00323        toolSettings.defSize = prefsData.toolSettings.defSize;
00324        toolSettings.tabFillChar = prefsData.toolSettings.tabFillChar;
00325        toolSettings.dispX = prefsData.toolSettings.dispX;
00326        toolSettings.dispY = prefsData.toolSettings.dispY;
00327        toolSettings.constrain = prefsData.toolSettings.constrain;
00328 
00329        PageColors.ensureBlackAndWhite();
00330        if (prefsData.toolSettings.dPen != CommonStrings::None)
00331               PageColors.insert(prefsData.toolSettings.dPen, prefsData.DColors[prefsData.toolSettings.dPen]);
00332        toolSettings.dPen = prefsData.toolSettings.dPen;
00333        if (prefsData.toolSettings.dPenLine != CommonStrings::None)
00334               PageColors.insert(prefsData.toolSettings.dPenLine, prefsData.DColors[prefsData.toolSettings.dPenLine]);
00335        toolSettings.dPenLine = prefsData.toolSettings.dPenLine;
00336        if (prefsData.toolSettings.dPenText != CommonStrings::None)
00337               PageColors.insert(prefsData.toolSettings.dPenText, prefsData.DColors[prefsData.toolSettings.dPenText]);
00338        toolSettings.dPenText = prefsData.toolSettings.dPenText;
00339        if (prefsData.toolSettings.dStrokeText != CommonStrings::None)
00340               PageColors.insert(prefsData.toolSettings.dStrokeText, prefsData.DColors[prefsData.toolSettings.dStrokeText]);
00341        toolSettings.dStrokeText = prefsData.toolSettings.dStrokeText;
00342        if (prefsData.toolSettings.dBrush != CommonStrings::None)
00343               PageColors.insert(prefsData.toolSettings.dBrush, prefsData.DColors[prefsData.toolSettings.dBrush]);
00344        toolSettings.dBrush = prefsData.toolSettings.dBrush;
00345        if (prefsData.toolSettings.dBrushPict != CommonStrings::None)
00346               PageColors.insert(prefsData.toolSettings.dBrushPict, prefsData.DColors[prefsData.toolSettings.dBrushPict]);
00347        toolSettings.dBrushPict = prefsData.toolSettings.dBrushPict;
00348        if (prefsData.toolSettings.dTextBackGround != CommonStrings::None)
00349               PageColors.insert(prefsData.toolSettings.dTextBackGround, prefsData.DColors[prefsData.toolSettings.dTextBackGround]);
00350        toolSettings.dTextBackGround = prefsData.toolSettings.dTextBackGround;
00351        if (prefsData.toolSettings.dTextLineColor != CommonStrings::None)
00352               PageColors.insert(prefsData.toolSettings.dTextLineColor, prefsData.DColors[prefsData.toolSettings.dTextLineColor]);
00353 
00354        
00355        ParagraphStyle pstyle;
00356        pstyle.setName( tr("Default Paragraph Style"));
00357        pstyle.setLineSpacingMode(ParagraphStyle::FixedLineSpacing);
00358        pstyle.setLineSpacing(15);
00359        pstyle.setAlignment(ParagraphStyle::Leftaligned);
00360        pstyle.setLeftMargin(0);
00361        pstyle.setFirstIndent(0);
00362        pstyle.setRightMargin(0);
00363        pstyle.setGapBefore(0);
00364        pstyle.setGapAfter(0);
00365        pstyle.setHasDropCap(false);
00366        pstyle.setDropCapLines(2);
00367        pstyle.setDropCapOffset(0);
00368        pstyle.charStyle().setParent("");
00369        
00370        CharStyle cstyle;
00371        cstyle.setName( tr("Default Character Style"));
00372        cstyle.setFont(prefsData.AvailFonts[toolSettings.defFont]);
00373        cstyle.setFontSize(toolSettings.defSize);
00374        cstyle.setFeatures(QStringList(CharStyle::INHERIT));
00375        cstyle.setFillColor(toolSettings.dPenText);
00376        cstyle.setFillShade(toolSettings.dTextPenShade);
00377        cstyle.setStrokeColor(toolSettings.dStrokeText);
00378        cstyle.setStrokeShade(toolSettings.dTextStrokeShade);
00379        cstyle.setBaselineOffset(0);
00380        cstyle.setShadowXOffset(50);
00381        cstyle.setShadowYOffset(-50);
00382        cstyle.setOutlineWidth(10);
00383        cstyle.setUnderlineOffset(typographicSettings.valueUnderlinePos);
00384        cstyle.setUnderlineWidth(typographicSettings.valueUnderlineWidth);
00385        cstyle.setStrikethruOffset(typographicSettings.valueStrikeThruPos);
00386        cstyle.setStrikethruWidth(typographicSettings.valueStrikeThruPos);
00387        cstyle.setScaleH(1000);
00388        cstyle.setScaleV(1000);
00389        cstyle.setTracking(0);
00390        cstyle.setLanguage(PrefsManager::instance()->appPrefs.Language);
00391        
00392        docParagraphStyles.create(pstyle);
00393        docParagraphStyles.makeDefault( &(docParagraphStyles[0]) );
00394        
00395        docCharStyles.create(cstyle);
00396        docCharStyles.makeDefault( &(docCharStyles[0]) );
00397        
00398        docParagraphStyles[0].breakImplicitCharStyleInheritance();
00399        docParagraphStyles[0].charStyle().setContext( & docCharStyles );
00400 //     docParagraphStyles[0].charStyle().setName( "cdocdefault" ); // DONT TRANSLATE
00401 
00402        currentStyle = pstyle;
00403        
00404        struct Layer ll;
00405        ll.LNr = 0;
00406        ll.Level = 0;
00407        ll.Name = tr("Background");
00408        ll.isViewable = true;
00409        ll.isPrintable = true;
00410        ll.isEditable = true;
00411        ll.flowControl = true;
00412        ll.outlineMode = false;
00413        ll.markerColor = QColor(0, 0, 0);
00414        ll.transparency = 1.0;
00415        ll.blendMode = 0;
00416        Layers.append(ll);
00417        // Fixme: Check PDF version input
00418        PDF_Options.Version = (PDFOptions::PDFVersion)prefsData.PDF_Options.Version;
00419 
00420        PDF_Options.firstUse = true;
00421        docPatterns.clear();
00422 
00423        if (AutoSave && ScCore->usingGUI())
00424               autoSaveTimer->start(AutoSaveTime);
00425        //Do this after all the collections have been created and cleared!
00426        m_masterPageMode=true; // quick hack to force the change of pointers in setMasterPageMode();
00427        setMasterPageMode(false);
00428        addSymbols();
00429 }
00430 
00431 ScribusDoc::~ScribusDoc()
00432 {
00433        m_guardedObject.nullify();
00434        CloseCMSProfiles();
00435        DocItems.setAutoDelete(true);
00436 //     FrameItems.setAutoDelete(true);
00437        DocItems.clear();
00438        FrameItems.clear();
00439        MasterPages.setAutoDelete(true);
00440        DocPages.setAutoDelete(true);
00441        MasterPages.clear();
00442        DocPages.clear();
00443        MasterItems.setAutoDelete(true);
00444        MasterItems.clear();
00445        QMap<QString,int>::Iterator it3;
00446        for (it3 = UsedFonts.begin(); it3 != UsedFonts.end(); ++it3)
00447        {
00448               if (!(*AllFonts)[it3.key()].localForDocument().isEmpty())
00449                      (*AllFonts).removeFont(it3.key());
00450               else
00451                      (*AllFonts)[it3.key()].decreaseUsage();
00452        }
00453 }
00454 
00455 void ScribusDoc::setup(const int unitIndex, const int fp, const int firstLeft, const int orientation, const int firstPageNumber, const QString& defaultPageSize, const QString& documentName)
00456 {
00457        docUnitIndex=unitIndex;
00458        pageSets[fp].FirstPage = firstLeft;
00459        PageOri = orientation;
00460        m_pageSize = defaultPageSize;
00461        FirstPnum = firstPageNumber;
00462        currentPageLayout = fp;
00463        setName(documentName);
00464        HasCMS = false;
00465        if (!PDF_Options.UseLPI)
00466        {
00467               PDF_Options.LPISettings.clear();
00468               struct LPIData lpo;
00469               lpo.Frequency = 75;
00470               lpo.SpotFunc = 2;
00471               lpo.Angle = 105;
00472               PDF_Options.LPISettings.insert("Cyan", lpo);
00473               lpo.Angle = 75;
00474               PDF_Options.LPISettings.insert("Magenta", lpo);
00475               lpo.Angle = 90;
00476               PDF_Options.LPISettings.insert("Yellow", lpo);
00477               lpo.Angle = 45;
00478               PDF_Options.LPISettings.insert("Black", lpo);
00479               ActiveLayer = 0;
00480        }
00481 
00482        appMode = modeNormal;
00483        PrefsManager *prefsManager=PrefsManager::instance();
00484        PageColors = prefsManager->colorSet();
00485        PageColors.ensureBlackAndWhite();
00486        PageColors.setDocument(this);
00487 
00488        CMSSettings = prefsManager->appPrefs.DCMSset;
00489        PDF_Options.SolidProf = CMSSettings.DefaultSolidColorRGBProfile;
00490        PDF_Options.ImageProf = CMSSettings.DefaultImageRGBProfile;
00491        PDF_Options.PrintProf = CMSSettings.DefaultPrinterProfile;
00492        PDF_Options.Intent = CMSSettings.DefaultIntentColors;
00493        PDF_Options.Intent2 = CMSSettings.DefaultIntentImages;
00494        SoftProofing = CMSSettings.SoftProofOn;
00495        Gamut = CMSSettings.GamutCheck;
00496        IntentColors = CMSSettings.DefaultIntentColors;
00497        IntentImages = CMSSettings.DefaultIntentImages;
00498        if (ScCore->haveCMS() && CMSSettings.CMSinUse)
00499        {
00500               if (OpenCMSProfiles(ScCore->InputProfiles, ScCore->InputProfilesCMYK, ScCore->MonitorProfiles, ScCore->PrinterProfiles))
00501               {
00502                      HasCMS = true;
00503                      PDF_Options.SComp = CMSSettings.ComponentsInput2;
00504               }
00505               else
00506                      HasCMS = false;
00507        }
00508 }
00509 
00510 void ScribusDoc::setGUI(bool hasgui, ScribusMainWindow* mw, ScribusView* view)
00511 {
00512        m_hasGUI = hasgui;
00513        m_ScMW=mw;
00514        m_View=view;
00515        docHyphenator=new Hyphenator(m_ScMW, this);
00516        Q_CHECK_PTR(docHyphenator);
00517 }
00518 
00519 void ScribusDoc::setLoading(const bool docLoading)
00520 {
00521        loading = docLoading;
00522 }
00523 
00524 bool ScribusDoc::isLoading() const
00525 {
00526        return loading;
00527 }
00528 
00529 ScribusView* ScribusDoc::view() const
00530 {
00531 //     return (WinHan ? (((ScribusWin*) WinHan)->view()) : 0);
00532        return m_View;
00533 }
00534 
00535 const ScGuardedPtr<ScribusDoc>& ScribusDoc::guardedPtr() const
00536 {
00537        return m_guardedObject;
00538 }
00539 
00540 void ScribusDoc::CloseCMSProfiles()
00541 {
00542        HasCMS = false;
00543        if (ScCore->haveCMS() /*&& CMSSettings.CMSinUse*/)
00544        {
00545               if (DocInputImageRGBProf)
00546                      cmsCloseProfile(DocInputImageRGBProf);
00547               if (DocInputImageCMYKProf)
00548                      cmsCloseProfile(DocInputImageCMYKProf);
00549               if (DocInputRGBProf)
00550                      cmsCloseProfile(DocInputRGBProf);
00551               if (DocInputCMYKProf)
00552                      cmsCloseProfile(DocInputCMYKProf);
00553               if (DocOutputProf)
00554                      cmsCloseProfile(DocOutputProf);
00555               if (DocPrinterProf)
00556                      cmsCloseProfile(DocPrinterProf);
00557               if (stdTransRGBMon)
00558                      cmsDeleteTransform(stdTransRGBMon);
00559               if (stdTransCMYKMon)
00560                      cmsDeleteTransform(stdTransCMYKMon);
00561               if (stdProof)
00562                      cmsDeleteTransform(stdProof);
00563               if (stdTransImg)
00564                      cmsDeleteTransform(stdTransImg);
00565               if (stdProofImg)
00566                      cmsDeleteTransform(stdProofImg);
00567               if (stdTransCMYK)
00568                      cmsDeleteTransform(stdTransCMYK);
00569               if (stdProofCMYK)
00570                      cmsDeleteTransform(stdProofCMYK);
00571               if (stdTransRGB)
00572                      cmsDeleteTransform(stdTransRGB);
00573               if (stdProofCMYKGC)
00574                      cmsDeleteTransform(stdProofCMYKGC);
00575               if (stdProofGC)
00576                      cmsDeleteTransform(stdProofGC);
00577               DocInputRGBProf = NULL;
00578               DocInputCMYKProf = NULL;
00579               DocInputImageRGBProf = NULL;
00580               DocInputImageCMYKProf = NULL;
00581               DocOutputProf = NULL;
00582               DocPrinterProf = NULL;
00583               stdTransRGBMon = NULL;
00584               stdTransCMYKMon = NULL;
00585               stdProof = NULL;
00586               stdTransImg = NULL;
00587               stdProofImg = NULL;
00588               stdTransCMYK = NULL;
00589               stdProofCMYK = NULL;
00590               stdTransRGB = NULL;
00591               stdProofCMYKGC = NULL;
00592               stdProofGC = NULL;
00593        }
00594 }
00595 
00596 bool ScribusDoc::OpenCMSProfiles(ProfilesL InPo, ProfilesL InPoCMYK, ProfilesL MoPo, ProfilesL PrPo)
00597 {
00598        HasCMS = false;
00599        cmsHPROFILE inputProf = NULL;
00600        cmsErrorAction(LCMS_ERROR_ABORT);
00601        if (setjmp(cmsJumpBuffer))
00602        {
00603               // Reset to the default handler otherwise may enter a loop
00604               // if an error occur afterwards
00605               cmsSetErrorHandler(NULL);
00606               cmsErrorAction(LCMS_ERROR_IGNORE);
00607               CloseCMSProfiles();
00608               cmsErrorAction(LCMS_ERROR_ABORT);
00609               CMSSettings.CMSinUse = false;
00610               QString message = tr("An error occurred while opening ICC profiles, color management is not enabled." );
00611               if (ScCore->usingGUI())
00612                      QMessageBox::warning(m_ScMW, CommonStrings::trWarning, message, QMessageBox::Ok, 0, 0);
00613               else
00614                      qWarning( "%s", message.local8Bit().data() );
00615               return false;
00616        }
00617        cmsSetErrorHandler(&cmsErrorHandler);
00618        const QCString rgbInputProfilePath(InPo[CMSSettings.DefaultSolidColorRGBProfile].local8Bit());
00619        DocInputRGBProf = cmsOpenProfileFromFile(rgbInputProfilePath.data(), "r");
00620        const QCString cmykInputProfilePath(InPoCMYK[CMSSettings.DefaultSolidColorCMYKProfile].local8Bit());
00621        DocInputCMYKProf = cmsOpenProfileFromFile(cmykInputProfilePath.data(), "r");
00622        const QCString monitorProfilePath(MoPo[CMSSettings.DefaultMonitorProfile].local8Bit());
00623        DocOutputProf = cmsOpenProfileFromFile(monitorProfilePath.data(), "r");
00624        const QCString printerProfilePath(PrPo[CMSSettings.DefaultPrinterProfile].local8Bit());
00625        DocPrinterProf = cmsOpenProfileFromFile(printerProfilePath, "r");
00626        const QCString rgbInputImgProfilePath(InPo[CMSSettings.DefaultImageRGBProfile].local8Bit());
00627        DocInputImageRGBProf = cmsOpenProfileFromFile(rgbInputImgProfilePath.data(), "r");
00628        const QCString cmykInputImgProfilePath(InPoCMYK[CMSSettings.DefaultImageCMYKProfile].local8Bit());
00629        DocInputImageCMYKProf = cmsOpenProfileFromFile(cmykInputImgProfilePath.data(), "r");
00630        if ((DocInputRGBProf == NULL) || (DocInputCMYKProf == NULL) || (DocOutputProf == NULL) || (DocPrinterProf == NULL) || (DocInputImageCMYKProf == NULL) || (DocInputImageRGBProf == NULL))
00631        {
00632               CMSSettings.CMSinUse = false;
00633               cmsSetErrorHandler(NULL);
00634               return false;
00635        }
00636        int dcmsFlags = 0;
00637        int dcmsFlagsGC = 0;
00638        dcmsFlags |= cmsFLAGS_LOWRESPRECALC;
00639        dcmsFlagsGC |= cmsFLAGS_LOWRESPRECALC;
00640 //     int dcmsFlags2 = cmsFLAGS_NOTPRECALC;
00641        if (CMSSettings.GamutCheck)
00642               dcmsFlagsGC |= cmsFLAGS_GAMUTCHECK;
00643        if (CMSSettings.BlackPoint)
00644        {
00645               dcmsFlags |= cmsFLAGS_BLACKPOINTCOMPENSATION;
00646               dcmsFlagsGC |= cmsFLAGS_BLACKPOINTCOMPENSATION;
00647        }
00648        // set Gamut alarm color to #00ff00
00649        cmsSetAlarmCodes(0, 255, 0);
00650        stdTransRGBMon  = scCmsCreateTransform(DocInputRGBProf, TYPE_RGB_16,
00651                                                                       DocOutputProf, TYPE_RGB_16,
00652                                                                       IntentColors,
00653                                                                       dcmsFlags);
00654        stdTransCMYKMon = scCmsCreateTransform(DocInputCMYKProf, TYPE_CMYK_16,
00655                                                                       DocOutputProf, TYPE_RGB_16,
00656                                                                       IntentColors,
00657                                                                       dcmsFlags);
00658        // TODO : check input profiles used for images
00659        stdProofImg = scCmsCreateProofingTransform(DocInputImageRGBProf, TYPE_RGBA_8,
00660                      DocOutputProf, TYPE_RGBA_8,
00661                      DocPrinterProf,
00662                      IntentImages,
00663                      INTENT_RELATIVE_COLORIMETRIC, dcmsFlagsGC | cmsFLAGS_SOFTPROOFING);
00664        stdProofImgCMYK = scCmsCreateProofingTransform(DocInputImageCMYKProf, TYPE_CMYK_8,
00665                      DocOutputProf, TYPE_RGBA_8,
00666                      DocPrinterProf,
00667                      IntentImages,
00668                      INTENT_RELATIVE_COLORIMETRIC, dcmsFlagsGC | cmsFLAGS_SOFTPROOFING);
00669        stdTransImg = scCmsCreateTransform(DocInputRGBProf, TYPE_RGBA_8,
00670                                         DocOutputProf, TYPE_RGBA_8,
00671                                         IntentImages,
00672                                         dcmsFlags);
00673        stdTransRGB = scCmsCreateTransform(DocInputCMYKProf, TYPE_CMYK_16,
00674                                           DocInputRGBProf, TYPE_RGB_16,
00675                                           IntentColors,
00676                                           dcmsFlags);
00677        stdTransCMYK = scCmsCreateTransform(DocInputRGBProf, TYPE_RGB_16,
00678                                           DocInputCMYKProf, TYPE_CMYK_16,
00679                                           IntentColors,
00680                                           dcmsFlags);
00681        cmsHPROFILE inputProfRGB = NULL;
00682        cmsHPROFILE inputProfCMYK = NULL;
00683        if (static_cast<int>(cmsGetColorSpace(DocPrinterProf)) == icSigCmykData)
00684        {
00685               inputProf = (CMSSettings.SoftProofOn && CMSSettings.SoftProofFullOn) ? DocInputCMYKProf : DocPrinterProf;
00686               inputProfRGB  = DocInputRGBProf;
00687               inputProfCMYK = inputProf;
00688        }
00689        else
00690        {
00691               inputProf = (CMSSettings.SoftProofOn && CMSSettings.SoftProofFullOn) ? DocInputRGBProf : DocPrinterProf;
00692               inputProfRGB  = inputProf;
00693               inputProfCMYK = DocInputCMYKProf;
00694        }
00695        stdProof = scCmsCreateProofingTransform(inputProfRGB, TYPE_RGB_16,
00696                            DocOutputProf, TYPE_RGB_16,
00697                            DocPrinterProf,
00698                            IntentColors,
00699                            INTENT_RELATIVE_COLORIMETRIC, dcmsFlags | cmsFLAGS_SOFTPROOFING);
00700        stdProofGC = scCmsCreateProofingTransform(inputProfRGB, TYPE_RGB_16,
00701                            DocOutputProf, TYPE_RGB_16,
00702                            DocPrinterProf,
00703                            IntentColors,
00704                            INTENT_RELATIVE_COLORIMETRIC, dcmsFlags | cmsFLAGS_SOFTPROOFING | cmsFLAGS_GAMUTCHECK);
00705        stdProofCMYK = scCmsCreateProofingTransform(inputProfCMYK, TYPE_CMYK_16,
00706                                           DocOutputProf, TYPE_RGB_16,
00707                                           DocPrinterProf,
00708                                           IntentColors,
00709                                           INTENT_RELATIVE_COLORIMETRIC, dcmsFlags | cmsFLAGS_SOFTPROOFING);
00710        stdProofCMYKGC = scCmsCreateProofingTransform(inputProfCMYK, TYPE_CMYK_16,
00711                                           DocOutputProf, TYPE_RGB_16,
00712                                           DocPrinterProf,
00713                                           IntentColors,
00714                                           INTENT_RELATIVE_COLORIMETRIC, dcmsFlags | cmsFLAGS_SOFTPROOFING | cmsFLAGS_GAMUTCHECK);
00715 
00716        if (static_cast<int>(cmsGetColorSpace(DocInputRGBProf)) == icSigRgbData)
00717                      CMSSettings.ComponentsInput2 = 3;
00718        if (static_cast<int>(cmsGetColorSpace(DocInputRGBProf)) == icSigCmykData)
00719                      CMSSettings.ComponentsInput2 = 4;
00720        if (static_cast<int>(cmsGetColorSpace(DocInputRGBProf)) == icSigCmyData)
00721                      CMSSettings.ComponentsInput2 = 3;
00722        if (static_cast<int>(cmsGetColorSpace(DocInputCMYKProf)) == icSigRgbData)
00723                      CMSSettings.ComponentsInput3 = 3;
00724        if (static_cast<int>(cmsGetColorSpace(DocInputCMYKProf)) == icSigCmykData)
00725                      CMSSettings.ComponentsInput3 = 4;
00726        if (static_cast<int>(cmsGetColorSpace(DocInputCMYKProf)) == icSigCmyData)
00727                      CMSSettings.ComponentsInput3 = 3;
00728        if (static_cast<int>(cmsGetColorSpace(DocPrinterProf)) == icSigRgbData)
00729                      CMSSettings.ComponentsPrinter = 3;
00730        if (static_cast<int>(cmsGetColorSpace(DocPrinterProf)) == icSigCmykData)
00731                      CMSSettings.ComponentsPrinter = 4;
00732        if (static_cast<int>(cmsGetColorSpace(DocPrinterProf)) == icSigCmyData)
00733                      CMSSettings.ComponentsPrinter = 3;
00734 
00735        cmsSetErrorHandler(NULL);
00736        return true;
00737 }
00738 
00739 void ScribusDoc::enableCMS(bool enable)
00740 {
00741        m_ScMW->setStatusBarInfoText( tr("Adjusting Colors"));
00742        m_ScMW->mainWindowProgressBar->reset();
00743        int cc = PageColors.count() + Items->count();
00744        m_ScMW->mainWindowProgressBar->setTotalSteps(cc);
00745        HasCMS = CMSSettings.CMSinUse;
00746        SoftProofing = CMSSettings.SoftProofOn;
00747        Gamut = CMSSettings.GamutCheck;
00748        IntentColors = CMSSettings.DefaultIntentColors;
00749        IntentImages = CMSSettings.DefaultIntentImages;
00750        qApp->setOverrideCursor(QCursor(waitCursor), true);
00751        bool oldCM = CMSSettings.CMSinUse;
00752        bool newCM = enable;
00753        CloseCMSProfiles();
00754        CMSSettings.CMSinUse = newCM;
00755        if (!CMSSettings.CMSinUse)
00756        {
00757               HasCMS = false;
00758               if     (oldCM)
00759               {
00760                      m_ScMW->recalcColors(m_ScMW->mainWindowProgressBar);
00761                      RecalcPictures(&ScCore->InputProfiles, &ScCore->InputProfilesCMYK, m_ScMW->mainWindowProgressBar);
00762               }
00763        }
00764        else if (OpenCMSProfiles(ScCore->InputProfiles, ScCore->InputProfilesCMYK, ScCore->MonitorProfiles, ScCore->PrinterProfiles) )
00765        {
00766               HasCMS = true;
00767               PDF_Options.SComp = CMSSettings.ComponentsInput2;
00768               PDF_Options.SolidProf = CMSSettings.DefaultSolidColorRGBProfile;
00769               PDF_Options.ImageProf = CMSSettings.DefaultImageRGBProfile;
00770               PDF_Options.PrintProf = CMSSettings.DefaultPrinterProfile;
00771               PDF_Options.Intent = CMSSettings.DefaultIntentColors;
00772               m_ScMW->recalcColors(m_ScMW->mainWindowProgressBar);
00773               RecalcPictures(&ScCore->InputProfiles, &ScCore->InputProfilesCMYK, m_ScMW->mainWindowProgressBar);
00774        }
00775        else
00776               HasCMS = false;
00777        m_ScMW->mainWindowProgressBar->setProgress(cc);
00778        qApp->setOverrideCursor(QCursor(arrowCursor), true);
00779        m_ScMW->setStatusBarInfoText("");
00780        m_ScMW->mainWindowProgressBar->reset();
00781 }
00782 
00783 
00784 void ScribusDoc::getNamedResources(ResourceCollection& lists) const
00785 {
00786        lists.availableFonts = AllFonts;
00787        lists.availableColors = const_cast<ColorList*>(& PageColors);
00788        
00789        const QPtrList<PageItem> * itemlist = & MasterItems;
00790        while (itemlist != NULL)
00791        {
00792               for (uint i=0; i < itemlist->count(); ++i)
00793               {
00794                      const PageItem * currItem = const_cast<QPtrList<PageItem>*>(itemlist)->at(i);
00795                      if (currItem)
00796                             currItem->getNamedResources(lists);
00797               }
00798               if (itemlist == &MasterItems)
00799                      itemlist = &DocItems;
00800               else if (itemlist == &DocItems)
00801                      itemlist = &FrameItems;
00802               else
00803                      itemlist = NULL;
00804        }
00805        for (uint i = 0; i < docParagraphStyles.count(); ++i)
00806               docParagraphStyles[i].getNamedResources(lists);
00807        for (uint i = 0; i < docCharStyles.count(); ++i)
00808               docCharStyles[i].getNamedResources(lists);
00809 //     for (uint i = 0; i < docLineStyles.count(); ++i)
00810 //            docLineStyles[i].getNamedResources(lists);
00811        
00812        QMap<QString,ScPattern>::ConstIterator it;
00813        for (it = docPatterns.begin(); it != docPatterns.end(); ++it)
00814        {
00815               ScPattern pa = *it;
00816               for (uint o = 0; o < pa.items.count(); o++)
00817               {
00818                      pa.items.at(o)->getNamedResources(lists);
00819               }
00820        }      
00821 }
00822 
00823 
00824 void ScribusDoc::replaceStyles(const QMap<QString,QString>& newNameForOld)
00825 {
00826        ResourceCollection newNames;
00827        newNames.mapStyles(newNameForOld);
00828        replaceNamedResources(newNames);
00829 }
00830 
00831 
00832 void ScribusDoc::replaceNamedResources(ResourceCollection& newNames)
00833 {
00834        // replace names in items
00835        QPtrList<PageItem> * itemlist = & MasterItems;
00836        while (itemlist != NULL)
00837        {
00838               for (uint i=0; i < itemlist->count(); ++i)
00839               {
00840                      PageItem * currItem = itemlist->at(i);
00841                      if (currItem)
00842                             currItem->replaceNamedResources(newNames);
00843               }
00844               if (itemlist == &MasterItems)
00845                      itemlist = &DocItems;
00846               else if (itemlist == &DocItems)
00847                      itemlist = &FrameItems;
00848               else
00849                      itemlist = NULL;
00850        }
00851        
00852        // replace names in styles...
00853        for (int i=docParagraphStyles.count()-1; i >= 0; --i)
00854        {
00855               if (newNames.styles().contains(docParagraphStyles[i].name()))
00856                      docParagraphStyles.remove(i);
00857               else
00858                      docParagraphStyles[i].replaceNamedResources(newNames);
00859        }
00860        for (int i=docCharStyles.count()-1; i >= 0; --i)
00861        {
00862               if (newNames.charStyles().contains(docCharStyles[i].name()))
00863                      docCharStyles.remove(i);
00864               else
00865                      docCharStyles[i].replaceNamedResources(newNames);
00866        }
00867 
00868        QMap<QString,ScPattern>::Iterator it;
00869        for (it = docPatterns.begin(); it != docPatterns.end(); ++it)
00870        {
00871               if (newNames.patterns().contains(it.key()))
00872                      docPatterns.remove(it);
00873               else
00874               {
00875                      ScPattern pa = *it;
00876                      for (uint o = 0; o < pa.items.count(); o++)
00877                      {
00878                             pa.items.at(o)->replaceNamedResources(newNames);
00879                      }
00880               }
00881        }
00882        
00883        if (newNames.colors().count() > 0 || newNames.fonts().count() > 0)
00884        {
00885               docCharStyles.invalidate();
00886               docParagraphStyles.invalidate();
00887        }
00888        else 
00889        {
00890               if (newNames.charStyles().count() > 0)
00891                      docCharStyles.invalidate();
00892               if (newNames.styles().count() > 0)
00893                      docParagraphStyles.invalidate();
00894        }
00895        if (!isLoading() && !(newNames.colors().isEmpty() && newNames.fonts().isEmpty() && newNames.patterns().isEmpty() 
00896                                             && newNames.styles().isEmpty() && newNames.charStyles().isEmpty() && newNames.lineStyles().isEmpty()) )
00897               changed();
00898 }
00899 
00900 
00901 void ScribusDoc::replaceCharStyles(const QMap<QString,QString>& newNameForOld)
00902 {
00903        ResourceCollection newNames;
00904        newNames.mapCharStyles(newNameForOld);
00905        replaceNamedResources(newNames);
00906        
00907        /*
00908        // replace style in items
00909        QPtrList<PageItem> * itemlist = & MasterItems;
00910        while (itemlist != NULL)
00911        {
00912               for (uint i=0; i < itemlist->count(); ++i)
00913               {
00914                      PageItem_TextFrame * currItem = itemlist->at(i)->asTextFrame();
00915                      if (currItem)
00916                             currItem->itemText.replaceCharStyles(newNameForOld);
00917               }
00918               if (itemlist == &MasterItems)
00919                      itemlist = &DocItems;
00920               else if (itemlist == &DocItems)
00921                      itemlist = &FrameItems;
00922               else
00923                      itemlist = NULL;
00924        }
00925        // replace names in styles 
00926        for (uint i=0; i < docParagraphStyles.count(); ++i)
00927        {
00928               // ...parent of parstyle's charstyle
00929               const QString& parent(docParagraphStyles[i].charStyle().parent());
00930               if (newNameForOld.contains(parent))
00931                      docParagraphStyles[i].charStyle().setParent(newNameForOld[parent]);
00932        }
00933        for (int i=docCharStyles.count()-1; i >= 0; --i)
00934        {
00935               // ...parent of charstyle
00936               const QString& parent(docCharStyles[i].parent());
00937               if (newNameForOld.contains(parent))
00938                      docCharStyles[i].setParent(newNameForOld[parent]);
00939               // ... as name
00940               if (newNameForOld.contains(docCharStyles[i].name()))
00941                      docCharStyles.remove(i);
00942        }
00943        */
00944 }
00945 
00946 void ScribusDoc::redefineStyles(const StyleSet<ParagraphStyle>& newStyles, bool removeUnused)
00947 {
00948        docParagraphStyles.redefine(newStyles, false);
00949        if (removeUnused)
00950        {
00951               QMap<QString, QString> deletion;
00952               QString deflt("");
00953               for (uint i=0; i < docParagraphStyles.count(); ++i)
00954               {
00955                      const QString& nam(docParagraphStyles[i].name());
00956                      if (newStyles.find(nam) < 0)
00957                             deletion[nam] = deflt;
00958               }
00959               if (deletion.count() > 0)
00960                      replaceStyles(deletion);
00961        }
00962        // repair charstyle context:
00963        for (uint i=0; i < docParagraphStyles.count(); ++i)
00964        {
00965               ParagraphStyle& sty(docParagraphStyles[i]);
00966               if (docParagraphStyles.isDefault(sty))
00967               {
00968                      sty.breakImplicitCharStyleInheritance(true);
00969                      sty.charStyle().setContext( & docCharStyles );
00970 //                   sty.charStyle().setName( "cdocdefault" ); // DONT TRANSLATE
00971               }
00972               else {
00973                      sty.breakImplicitCharStyleInheritance(false);
00974               }
00975        }
00976        docParagraphStyles.invalidate();
00977 }
00978 
00979 void ScribusDoc::redefineCharStyles(const StyleSet<CharStyle>& newStyles, bool removeUnused)
00980 {
00981        docCharStyles.redefine(newStyles, false);
00982        if (removeUnused)
00983        {
00984               QMap<QString, QString> deletion;
00985               QString deflt("");
00986               for (uint i=0; i < docCharStyles.count(); ++i)
00987               {
00988                      const QString& nam(docCharStyles[i].name());
00989                      if (newStyles.find(nam) < 0)
00990                      {
00991                             deletion[nam] = deflt;
00992                      }
00993               }
00994               if (deletion.count() > 0)
00995                      replaceCharStyles(deletion);
00996        }
00997        docCharStyles.invalidate();
00998 }
00999 
01000 
01001 /*
01002  * Split out from loadStyles in editFormats.cpp so it's callable from anywhere,
01003  * including plugins.
01004  * - 2004-09-14 Craig Ringer
01005  */
01006 // dont like this here. could as well be a static method for reading this stuff into temp., then always use redefineXY() - av
01007 void ScribusDoc::loadStylesFromFile(QString fileName, StyleSet<ParagraphStyle> *tempStyles,
01008                                                       StyleSet<CharStyle> *tempCharStyles,
01009                                                       QMap<QString, multiLine> *tempLineStyles)
01010 {
01011        StyleSet<ParagraphStyle> *wrkStyles     = NULL;
01012        StyleSet<CharStyle> *wrkCharStyles      = NULL;
01013        QMap<QString, multiLine> *wrkLineStyles = NULL;
01014        uint oldStyles, oldCharStyles, oldLineStyles;
01015 
01016        /*
01017         * Use the working styles struct if passed, or work directly
01018         * on the document styles otherwise. 
01019         */
01020        if (tempStyles != NULL)
01021               wrkStyles = tempStyles;
01022        else 
01023               wrkStyles = &docParagraphStyles;
01024        oldStyles = wrkStyles->count();
01025        
01026        if (tempCharStyles != NULL)
01027               wrkCharStyles = tempCharStyles;
01028        else
01029               wrkCharStyles = &docCharStyles;
01030        oldCharStyles = wrkCharStyles->count();
01031        
01032        if (tempLineStyles != NULL)
01033               wrkLineStyles = tempLineStyles;
01034        else
01035               wrkLineStyles = &MLineStyles;
01036        oldLineStyles = wrkLineStyles->count();
01037        
01038        if (!fileName.isEmpty())
01039        {
01040               FileLoader fl(fileName);
01041               if (fl.TestFile() == -1)
01042               //TODO put in nice user warning
01043                      return;
01044 
01045               if (!fl.ReadStyles(fileName, this, *wrkStyles))
01046               {
01047                      //TODO put in nice user warning
01048               }
01049 
01050               if (!fl.ReadCharStyles(fileName, this, *wrkCharStyles))
01051               {
01052                      //TODO put in nice user warning
01053               }
01054 
01055               if (!fl.ReadLineStyles(fileName, wrkLineStyles))
01056               {
01057                      //TODO put in nice user warning
01058               }
01059               
01060                if ( !isLoading() && (   (wrkStyles == &docParagraphStyles && wrkStyles->count() > oldStyles)
01061                                                     || (wrkCharStyles == &docCharStyles && wrkCharStyles->count() > oldCharStyles)
01062                                                     || (wrkLineStyles == &MLineStyles && wrkLineStyles->count() > oldLineStyles) ) )
01063                       changed();
01064        }
01065 }
01066 
01067 void ScribusDoc::lockGuides(bool isLocked)
01068 {
01069        if (GuideLock == isLocked)
01070               return;
01071        GuideLock = isLocked;
01072        if (UndoManager::undoEnabled())
01073        {
01074               QString name;
01075               if (isLocked)
01076                      name = Um::LockGuides;
01077               else
01078                      name = Um::UnlockGuides;
01079               SimpleState *ss = new SimpleState(name, "", Um::ILockGuides);
01080               ss->set("GUIDE_LOCK", isLocked);
01081               undoManager->action(this, ss);
01082        }
01083 }
01084 
01085 void ScribusDoc::restore(UndoState* state, bool isUndo)
01086 {
01087        SimpleState *ss = dynamic_cast<SimpleState*>(state);
01088        if (ss)
01089        {
01090               bool layersUndo=false;
01091               if (ss->contains("GUIDE_LOCK"))
01092               {
01093                      if (isUndo)
01094                             GuideLock = !ss->getBool("GUIDE_LOCK");
01095                      else
01096                             GuideLock = ss->getBool("GUIDE_LOCK");
01097               }
01098               else if (ss->contains("UP_LAYER"))
01099               {
01100                      if (isUndo)
01101                             lowerLayer(ss->getInt("ACTIVE"));
01102                      else
01103                             raiseLayer(ss->getInt("ACTIVE"));
01104                      layersUndo=true;
01105               }
01106               else if (ss->contains("DOWN_LAYER"))
01107               {
01108                      if (isUndo)
01109                             raiseLayer(ss->getInt("ACTIVE"));
01110                      else
01111                             lowerLayer(ss->getInt("ACTIVE"));
01112                      layersUndo=true;
01113               }
01114               else if (ss->contains("PRINT_LAYER"))
01115               {
01116                      bool print = ss->getBool("PRINT");
01117                      setLayerPrintable(ss->getInt("ACTIVE"), isUndo ? !print : print);
01118                      layersUndo=true;
01119               }
01120               else if (ss->contains("ADD_LAYER"))
01121               {
01122                      if (isUndo)
01123                             deleteLayer(ss->getInt("LAYER_NR"), false);
01124                      else
01125                      {
01126                             int layerNumber=addLayer( ss->get("NAME"), false );
01127                             int newLayerNumber=ss->getInt("LAYER_NR");
01128                             bool renumberedOk=renumberLayer(layerNumber, newLayerNumber);
01129                             Q_ASSERT(renumberedOk);
01130                      }
01131                      layersUndo=true;
01132               }
01133               else if (ss->contains("REMOVE_LAYER"))
01134               {
01135                      if (isUndo)
01136                      {
01137                             int layerNumber=addLayer( ss->get("NAME"), false );
01138                             int newLayerNumber=ss->getInt("LAYER_NR");
01139                             bool renumberedOk=renumberLayer(layerNumber, newLayerNumber);
01140                             Q_ASSERT(renumberedOk);
01141                             layerNumber=newLayerNumber;
01142                             //Layer is at the top now, lower it until it reaches the old level
01143                             int level = ss->getInt("LEVEL");
01144                             while (layerLevelFromNumber(layerNumber)!=level)
01145                                    lowerLayer(layerNumber);
01146                      }
01147                      else
01148                             deleteLayer(ss->getInt("LAYER_NR"), ss->getBool("DELETE"));
01149                      layersUndo=true;
01150               }
01151               else if (ss->contains("CHANGE_NAME"))
01152               {
01153                      QString name = ss->get("OLD_NAME");
01154                      if (!isUndo)
01155                             name = ss->get("NEW_NAME");
01156                      changeLayerName(ss->getInt("ACTIVE"), name);
01157                      layersUndo=true;
01158               }
01159               else if (ss->contains("OLD_MASTERPAGE"))
01160                      restoreMasterPageApplying(ss, isUndo);
01161               else if (ss->contains("COPY_PAGE"))
01162                      restorePageCopy(ss, isUndo);
01163 
01164               if (layersUndo)
01165               {
01166                      if (ScCore->usingGUI())
01167                      {
01168                             m_ScMW->changeLayer(ss->getInt("ACTIVE"));
01169                             m_ScMW->layerPalette->rebuildList();
01170                      }
01171               }
01172        }
01173 }
01174 
01175 void ScribusDoc::setName(const QString& name)
01176 {
01177        DocName = name;
01178 }
01179 
01180 void ScribusDoc::setModified(const bool isModified)
01181 {
01182        modified = isModified;
01183 }
01184 
01185 bool ScribusDoc::isModified() const
01186 {
01187   return modified;
01188 }
01190 void ScribusDoc::setPage(double b, double h, double t, double l, double r, double bo, double sp, double ab, bool atf, int fp)
01191 {
01192        pageWidth = b;
01193        pageHeight = h;
01194        pageMargins.Top = t;
01195        pageMargins.Left = l;
01196        pageMargins.Right = r;
01197        pageMargins.Bottom = bo;
01198        PageSp = sp;
01199        PageSpa = ab;
01200        currentPageLayout = fp;
01201        automaticTextFrames = atf;
01202 
01203        //CB Moved from scribus.cpp. Overrides the defaults...
01204 //     PDF_Options.BleedTop = pageMargins.Top;
01205 //     PDF_Options.BleedLeft = pageMargins.Left;
01206 //     PDF_Options.BleedRight = pageMargins.Right;
01207 //     PDF_Options.BleedBottom = pageMargins.Bottom;
01208 }
01209 
01210 void ScribusDoc::resetPage(double t, double l, double r, double bo, int fp)
01211 {
01212        pageMargins.Top = t;
01213        pageMargins.Left = l;
01214        pageMargins.Right = r;
01215        pageMargins.Bottom = bo;
01216        currentPageLayout = fp;
01217 }
01218 
01219 bool ScribusDoc::AddFont(QString name, int fsize)
01220 {
01221        bool ret = false;
01222 //     FT_Face      face;
01223 
01224        if (UsedFonts.contains(name))
01225               return true;
01226 
01227        if (! AllFonts->contains(name) || name == "" )
01228               return false;
01229 
01230 //     face = (*AllFonts)[name]->ftFace();
01231 //     if ( !face )
01232 //            return false;
01233 
01234 /*     if ((*AllFonts)[name].ReadMetrics())         FIXME: needed?
01235        {
01236 //            (*AllFonts)[name]->CharWidth[13] = 0;
01237 //            (*AllFonts)[name]->CharWidth[28] = 0;
01238 //            (*AllFonts)[name]->CharWidth[26] = 0;
01239 //            (*AllFonts)[name]->CharWidth[9] = 1;
01240               QString afnm = (*AllFonts)[name].fontFilePath().left((*AllFonts)[name].fontFilePath().length()-3);
01241               QFile afm(afnm+"afm");
01242               if(!(afm.exists()))
01243               {
01244                      afm.setName(afnm+"pfm");
01245               }
01246               if(!(afm.exists())) {
01247                      afm.setName(afnm+"AFM");
01248               }
01249               if(!(afm.exists()))
01250               {
01251                      afm.setName(afnm+"PFM");
01252               }
01253               if(!(afm.exists()))
01254               {
01255                      afm.setName(afnm+"Afm");
01256               }
01257               if(!(afm.exists()))
01258               {
01259                      afm.setName(afnm+"Pfm");
01260               }
01261               if (afm.exists())
01262                      FT_Attach_File(face, afm.name());
01263        }
01264        */
01265        UsedFonts[name] = fsize;
01266        (*AllFonts)[name].increaseUsage();
01267        ret = true;
01268        return ret;
01269 }
01270 
01271 QStringList ScribusDoc::getItemAttributeNames()
01272 {
01273        QStringList nameList;
01274 
01275        for(ObjAttrVector::Iterator it = docItemAttributes.begin(); it!= docItemAttributes.end(); ++it)
01276               nameList.append((*it).name);
01277        return nameList;
01278 }
01279 
01280 void ScribusDoc::addSymbols()
01281 {
01282        symReturn.resize(0);
01283        symReturn.addQuadPoint(1.98438, 9.14062, 1.98438, 9.14062, 1.98438, 4.03125, 1.98438, 4.03125);
01284        symReturn.addQuadPoint(1.98438, 4.03125, 1.98438, 4.03125, 0.546875, 3.45312, 1.09375, 4);
01285        symReturn.addQuadPoint(0.546875, 3.45312, 0.546875, 3.45312, 0, 2.0625, 0, 2.92188);
01286        symReturn.addQuadPoint(0, 2.0625, 0, 2.0625, 0.65625, 0.5, 0, 1.04688);
01287        symReturn.addQuadPoint(0.65625, 0.5, 0.65625, 0.5, 2.3125, 0, 1.28125, 0);
01288        symReturn.addQuadPoint(2.3125, 0, 2.3125, 0, 5.40625, 0, 5.40625, 0);
01289        symReturn.addQuadPoint(5.40625, 0, 5.40625, 0, 5.40625, 0.84375, 5.40625, 0.84375);
01290        symReturn.addQuadPoint(5.40625, 0.84375, 5.40625, 0.84375, 4.70312, 0.84375, 4.70312, 0.84375);
01291        symReturn.addQuadPoint(4.70312, 0.84375, 4.70312, 0.84375, 4.70312, 9.14062, 4.70312, 9.14062);
01292        symReturn.addQuadPoint(4.70312, 9.14062, 4.70312, 9.14062, 3.875, 9.14062, 3.875, 9.14062);
01293        symReturn.addQuadPoint(3.875, 9.14062, 3.875, 9.14062, 3.875, 0.84375, 3.875, 0.84375);
01294        symReturn.addQuadPoint(3.875, 0.84375, 3.875, 0.84375, 2.78125, 0.84375, 2.78125, 0.84375);
01295        symReturn.addQuadPoint(2.78125, 0.84375, 2.78125, 0.84375, 2.78125, 9.14062, 2.78125, 9.14062);
01296        symReturn.addQuadPoint(2.78125, 9.14062, 2.78125, 9.14062, 1.98438, 9.14062, 1.98438, 9.14062);
01297        symNewLine.resize(0);
01298        symNewLine.addQuadPoint(6.51562, 2.625, 6.51562, 2.625, 0.90625, 2.64062, 0.90625, 2.64062);
01299        symNewLine.addQuadPoint(0.90625, 2.64062, 0.90625, 2.64062, 1.4375, 1.92188, 1.26562, 2.1875);
01300        symNewLine.addQuadPoint(1.4375, 1.92188, 1.4375, 1.92188, 1.76562, 1.14062, 1.75, 1.42188);
01301        symNewLine.addQuadPoint(1.76562, 1.14062, 1.76562, 1.14062, 1.60938, 1.03125, 1.60938, 1.03125);
01302        symNewLine.addQuadPoint(1.60938, 1.03125, 1.60938, 1.03125, 0.90625, 1.92188, 0.90625, 1.92188);
01303        symNewLine.addQuadPoint(0.90625, 1.92188, 0.90625, 1.92188, 0, 2.90625, 0.578125, 2.23438);
01304        symNewLine.addQuadPoint(0, 2.90625, 0, 2.90625, 0.75, 3.875, 0.75, 3.875);
01305        symNewLine.addQuadPoint(0.75, 3.875, 0.75, 3.875, 1.57812, 4.78125, 1.1875, 4.40625);
01306        symNewLine.addQuadPoint(1.57812, 4.78125, 1.57812, 4.78125, 1.65625, 4.79688, 1.65625, 4.79688);
01307        symNewLine.addQuadPoint(1.65625, 4.79688, 1.65625, 4.79688, 1.76562, 4.65625, 1.76562, 4.65625);
01308        symNewLine.addQuadPoint(1.76562, 4.65625, 1.76562, 4.65625, 0.90625, 3.17188, 1.73438, 4.34375);
01309        symNewLine.addQuadPoint(0.90625, 3.17188, 0.90625, 3.17188, 0.96875, 3.125, 0.96875, 3.125);
01310        symNewLine.addQuadPoint(0.96875, 3.125, 0.96875, 3.125, 6.75, 3.125, 6.75, 3.125);
01311        symNewLine.addQuadPoint(6.75, 3.125, 6.75, 3.125, 6.51562, 2.625, 6.51562, 2.625);
01312        symNewLine.addQuadPoint(6.51562, 2.625, 6.51562, 2.625, 6.51562, 2.625, 6.51562, 2.625);
01313        symNewLine.addQuadPoint(999999, 999999, 999999, 999999, 999999, 999999, 999999, 999999);
01314        symNewLine.addQuadPoint(6.875, 0, 6.875, 0, 6.51562, 0, 6.51562, 0);
01315        symNewLine.addQuadPoint(6.51562, 0, 6.51562, 0, 6.51562, 2.84375, 6.51562, 2.84375);
01316        symNewLine.addQuadPoint(6.51562, 2.84375, 6.51562, 2.84375, 6.75, 3.125, 6.51562, 3.125);
01317        symNewLine.addQuadPoint(6.75, 3.125, 6.75, 3.125, 6.85938, 3.0625, 6.85938, 3.0625);
01318        symNewLine.addQuadPoint(6.85938, 3.0625, 6.85938, 3.0625, 6.875, 0, 6.875, 0);
01319        symTab.resize(0);
01320        symTab.addQuadPoint(4.82812, 3.96875, 4.82812, 3.96875, 4.5625, 3.73438, 4.5625, 3.96875);
01321        symTab.addQuadPoint(4.5625, 3.73438, 4.5625, 3.73438, 5.07812, 3.10938, 4.5625, 3.57812);
01322        symTab.addQuadPoint(5.07812, 3.10938, 5.07812, 3.10938, 0, 3.10938, 0, 3.10938);
01323        symTab.addQuadPoint(0, 3.10938, 0, 3.10938, 0, 2.625, 0, 2.625);
01324        symTab.addQuadPoint(0, 2.625, 0, 2.625, 5.53125, 2.625, 5.53125, 2.625);
01325        symTab.addQuadPoint(5.53125, 2.625, 5.53125, 2.625, 6.3125, 1.8125, 6.3125, 1.8125);
01326        symTab.addQuadPoint(6.3125, 1.8125, 6.3125, 1.8125, 5.64062, 1.29688, 5.64062, 1.29688);
01327        symTab.addQuadPoint(5.64062, 1.29688, 5.64062, 1.29688, 0, 1.29688, 0, 1.29688);
01328        symTab.addQuadPoint(0, 1.29688, 0, 1.29688, 0, 0.8125, 0, 0.8125);
01329        symTab.addQuadPoint(0, 0.8125, 0, 0.8125, 5.01562, 0.8125, 5.01562, 0.8125);
01330        symTab.addQuadPoint(5.01562, 0.8125, 5.01562, 0.8125, 4.45312, 0.265625, 4.45312, 0.453125);
01331        symTab.addQuadPoint(4.45312, 0.265625, 4.45312, 0.265625, 4.6875, 0, 4.45312, 0);
01332        symTab.addQuadPoint(4.6875, 0, 4.6875, 0, 5.90625, 0.828125, 4.875, 0);
01333        symTab.addQuadPoint(5.90625, 0.828125, 5.90625, 0.828125, 6.9375, 1.79688, 6.9375, 1.64062);
01334        symTab.addQuadPoint(6.9375, 1.79688, 6.9375, 1.79688, 5.95312, 2.96875, 6.9375, 1.95312);
01335        symTab.addQuadPoint(5.95312, 2.96875, 5.95312, 2.96875, 4.82812, 3.96875, 4.98438, 3.96875);
01336        symNonBreak.resize(0);
01337        symNonBreak.addQuadPoint(1.32812, 2.59375, 1.32812, 2.59375, 0.390625, 2.21875, 0.796875, 2.59375);
01338        symNonBreak.addQuadPoint(0.390625, 2.21875, 0.390625, 2.21875, 0, 1.3125, 0, 1.84375);
01339        symNonBreak.addQuadPoint(0, 1.3125, 0, 1.3125, 0.390625, 0.390625, 0, 0.765625);
01340        symNonBreak.addQuadPoint(0.390625, 0.390625, 0.390625, 0.390625, 1.32812, 0, 0.796875, 0);
01341        symNonBreak.addQuadPoint(1.32812, 0, 1.32812, 0, 2.23438, 0.390625, 1.85938, 0);
01342        symNonBreak.addQuadPoint(2.23438, 0.390625, 2.23438, 0.390625, 2.60938, 1.29688, 2.60938, 0.765625);
01343        symNonBreak.addQuadPoint(2.60938, 1.29688, 2.60938, 1.29688, 2.23438, 2.21875, 2.60938, 1.84375);
01344        symNonBreak.addQuadPoint(2.23438, 2.21875, 2.23438, 2.21875, 1.32812, 2.59375, 1.875, 2.59375);
01345        symNewCol.resize(0);
01346        symNewCol.addQuadPoint(1.73438, 0, 1.73438, 0, 2.67188, 0.109375, 2.03125, 0);
01347        symNewCol.addQuadPoint(2.67188, 0.109375, 2.67188, 0.109375, 3.59375, 0.203125, 3.26562, 0.21875);
01348        symNewCol.addQuadPoint(3.59375, 0.203125, 3.59375, 0.203125, 3.79688, 0.1875, 3.64062, 0.203125);
01349        symNewCol.addQuadPoint(3.79688, 0.1875, 3.79688, 0.1875, 4, 0.171875, 3.92188, 0.171875);
01350        symNewCol.addQuadPoint(4, 0.171875, 4, 0.171875, 4.20312, 0.1875, 4.20312, 0.1875);
01351        symNewCol.addQuadPoint(4.20312, 0.1875, 4.20312, 0.1875, 4.3125, 1.39062, 4.20312, 0.5625);
01352        symNewCol.addQuadPoint(4.3125, 1.39062, 4.3125, 1.39062, 4.42188, 2.64062, 4.42188, 2.21875);
01353        symNewCol.addQuadPoint(4.42188, 2.64062, 4.42188, 2.64062, 4.28125, 2.73438, 4.28125, 2.73438);
01354        symNewCol.addQuadPoint(4.28125, 2.73438, 4.28125, 2.73438, 3.75, 1.03125, 4.01562, 2.64062);
01355        symNewCol.addQuadPoint(3.75, 1.03125, 3.75, 1.03125, 3.67188, 1.03125, 3.67188, 1.03125);
01356        symNewCol.addQuadPoint(3.67188, 1.03125, 3.67188, 1.03125, 0.28125, 6.20312, 0.28125, 6.20312);
01357        symNewCol.addQuadPoint(0.28125, 6.20312, 0.28125, 6.20312, 0, 5.95312, 0.03125, 6.17188);
01358        symNewCol.addQuadPoint(0, 5.95312, 0, 5.95312, 3.35938, 0.71875, 3.35938, 0.71875);
01359        symNewCol.addQuadPoint(3.35938, 0.71875, 3.35938, 0.71875, 3.375, 0.640625, 3.375, 0.640625);
01360        symNewCol.addQuadPoint(3.375, 0.640625, 3.375, 0.640625, 2.4375, 0.484375, 2.79688, 0.5625);
01361        symNewCol.addQuadPoint(2.4375, 0.484375, 2.4375, 0.484375, 1.67188, 0.140625, 1.71875, 0.328125);
01362        symNewCol.addQuadPoint(1.67188, 0.140625, 1.67188, 0.140625, 1.73438, 0, 1.73438, 0);
01363        symNewFrame.resize(0);
01364        symNewFrame.addQuadPoint(1.75, 6.20312, 1.75, 6.20312, 2.67188, 6.09375, 2.0625, 6.20312);
01365        symNewFrame.addQuadPoint(2.67188, 6.09375, 2.67188, 6.09375, 3.60938, 5.98438, 3.28125, 5.98438);
01366        symNewFrame.addQuadPoint(3.60938, 5.98438, 3.60938, 5.98438, 3.84375, 6.01562, 3.6875, 5.98438);
01367        symNewFrame.addQuadPoint(3.84375, 6.01562, 3.84375, 6.01562, 4.07812, 6.03125, 4, 6.03125);
01368        symNewFrame.addQuadPoint(4.07812, 6.03125, 4.07812, 6.03125, 4.20312, 6.01562, 4.20312, 6.01562);
01369        symNewFrame.addQuadPoint(4.20312, 6.01562, 4.20312, 6.01562, 4.32812, 4.79688, 4.21875, 5.625);
01370        symNewFrame.addQuadPoint( 4.32812, 4.79688, 4.32812, 4.79688, 4.42188, 3.5625, 4.42188, 3.98438);
01371        symNewFrame.addQuadPoint(4.42188, 3.5625, 4.42188, 3.5625, 4.29688, 3.45312, 4.29688, 3.45312);
01372        symNewFrame.addQuadPoint(4.29688, 3.45312, 4.29688, 3.45312, 3.75, 5.17188, 4.03125, 3.54688);
01373        symNewFrame.addQuadPoint(3.75, 5.17188, 3.75, 5.17188, 3.67188, 5.17188, 3.67188, 5.17188);
01374        symNewFrame.addQuadPoint(3.67188, 5.17188, 3.67188, 5.17188, 0.28125, 0, 0.28125, 0);
01375        symNewFrame.addQuadPoint(0.28125, 0, 0.28125, 0, 0, 0.25, 0.03125, 0.015625);
01376        symNewFrame.addQuadPoint(0, 0.25, 0, 0.25, 3.375, 5.46875, 3.375, 5.46875);
01377        symNewFrame.addQuadPoint(3.375, 5.46875, 3.375, 5.46875, 3.39062, 5.54688, 3.39062, 5.54688);
01378        symNewFrame.addQuadPoint(3.39062, 5.54688, 3.39062, 5.54688, 2.4375, 5.70312, 2.8125, 5.625);
01379        symNewFrame.addQuadPoint(2.4375, 5.70312, 2.4375, 5.70312, 1.67188, 6.0625, 1.71875, 5.875);
01380        symNewFrame.addQuadPoint(1.67188, 6.0625, 1.67188, 6.0625, 1.75, 6.20312, 1.75, 6.20312);
01381 }
01382 
01383 Page* ScribusDoc::addPage(const int pageIndex, const QString& masterPageName, const bool addAutoFrame)
01384 {
01385        assert(masterPageMode()==false);
01386        Page* addedPage = new Page(scratch.Left, DocPages.count()*(pageHeight+scratch.Bottom+scratch.Top)+scratch.Top, pageWidth, pageHeight);
01387        assert(addedPage!=NULL);
01388        addedPage->setDocument(this);
01389        addedPage->Margins.Top = pageMargins.Top;
01390        addedPage->Margins.Bottom = pageMargins.Bottom;
01391        addedPage->initialMargins.Top = pageMargins.Top;
01392        addedPage->initialMargins.Bottom = pageMargins.Bottom;
01393        addedPage->initialMargins.Left = pageMargins.Left;
01394        addedPage->initialMargins.Right = pageMargins.Right;
01395        addedPage->setPageNr(pageIndex);
01396        addedPage->m_pageSize = m_pageSize;
01397        addedPage->PageOri = PageOri;
01398        bool insertsuccess=DocPages.insert(pageIndex, addedPage);
01399        assert(insertsuccess==true && DocPages.at(pageIndex)!=NULL);
01400        setCurrentPage(addedPage);
01401        //if (!masterPageMode())
01402        if (!masterPageName.isEmpty())
01403               applyMasterPage(masterPageName, pageIndex);
01404        setLocationBasedPageLRMargins(pageIndex);
01405        if (addAutoFrame && automaticTextFrames)
01406               addAutomaticTextFrame(pageIndex);
01407        if (!isLoading())
01408               changed();
01409        return addedPage;
01410 }
01411 
01412 Page* ScribusDoc::addMasterPage(const int pageNumber, const QString& pageName)
01413 {
01414        //CB We dont create master pages (yet) with a pageCount based location
01415        //Page* addedPage = new Page(ScratchLeft, MasterPages.count()*(pageHeight+ScratchBottom+ScratchTop)+ScratchTop, pageWidth, pageHeight);
01416        Page* addedPage = new Page(scratch.Left, scratch.Top, pageWidth, pageHeight);
01417        assert(addedPage!=NULL);
01418        addedPage->setDocument(this);
01419        addedPage->Margins.Top = pageMargins.Top;
01420        addedPage->Margins.Bottom = pageMargins.Bottom;
01421        addedPage->Margins.Left = pageMargins.Left;//todo fix for layouts
01422        addedPage->Margins.Right = pageMargins.Right;
01423        addedPage->initialMargins.Top = pageMargins.Top;
01424        addedPage->initialMargins.Bottom = pageMargins.Bottom;
01425        addedPage->initialMargins.Left = pageMargins.Left;
01426        addedPage->initialMargins.Right = pageMargins.Right;
01427        addedPage->m_pageSize = m_pageSize;
01428        addedPage->PageOri = PageOri;
01429        addedPage->MPageNam = "";
01430        addedPage->setPageName(pageName);
01431        addedPage->setPageNr(pageNumber);
01432        MasterNames.insert(pageName, pageNumber);
01433        bool insertsuccess=MasterPages.insert(pageNumber, addedPage);
01434        assert(insertsuccess==true && MasterPages.at(pageNumber)!=NULL);
01435        if  (!isLoading())
01436               changed();
01437        return addedPage;
01438 }
01439 
01440 bool ScribusDoc::renameMasterPage(const QString& oldPageName, const QString& newPageName)
01441 {
01442        Q_ASSERT(oldPageName!=CommonStrings::masterPageNormal && oldPageName!=CommonStrings::trMasterPageNormal);
01443        if (MasterNames.contains(oldPageName) && !MasterNames.contains(newPageName))
01444        {
01445               //Rename our master page lists
01446               int number=MasterNames[oldPageName];
01447               MasterNames.insert(newPageName, number);
01448               MasterNames.remove(oldPageName);
01449               Q_ASSERT(MasterPages.at(number)->pageName()==oldPageName);
01450               MasterPages.at(number)->setPageName(newPageName);
01451               //Update any pages that were linking to our old name
01452               for (Page* docPage = DocPages.first(); docPage; docPage = DocPages.next() )
01453               {
01454                      if (docPage->MPageNam == oldPageName)
01455                             docPage->MPageNam = newPageName;
01456               }
01457               //Update any items that were linking to our old name
01458               uint masterItemsCount=MasterItems.count();
01459               for (uint i = 0; i < masterItemsCount; ++i)
01460               {
01461                      if (MasterItems.at(i)->OnMasterPage == oldPageName)
01462                             MasterItems.at(i)->OnMasterPage = newPageName;
01463               }
01464               changed();
01465               return true;
01466        }
01467        return false;
01468 }
01469 
01470 void ScribusDoc::deleteMasterPage(const int pageNumber)
01471 {
01472        assert(masterPageMode());
01473        assert( Pages->count() > 1 && Pages->count() > static_cast<uint>(pageNumber) );
01474        setCurrentPage(Pages->at(0));
01475        Page* page = Pages->at(pageNumber);
01476        QString oldPageName(page->pageName());
01477        Pages->remove(pageNumber);
01478        delete page;
01479        // remove the master page from the master page name list
01480        //MasterNames.remove(page->PageNam);
01481        /*CB TODO moved back to muster.cpp for now as this must happen after reformPages
01482        MasterNames.clear();
01483        for (uint a = 0; a < Pages->count(); ++a)
01484               MasterNames[Pages->at(a)->PageNam] = Pages->at(a)->pageNr();
01485        // and fix up any pages that refer to the deleted master page
01486        for (Page* docPage = DocPages.first(); docPage; docPage = DocPages.next() )
01487        {
01488               if (docPage->MPageNam == oldPageName)
01489                      docPage->MPageNam = CommonStrings::masterPageNormal;
01490        }
01491        */
01492        //QPtrList docs: The item after the removed item becomes the new current list item if the removed item is not the last item in the list. If the last item is removed, the new last item becomes the current item.
01493        changed();
01494 }
01495 
01496 void ScribusDoc::deletePage(const int pageNumber)
01497 {
01498        assert( Pages->count() > 1 && Pages->count() > static_cast<uint>(pageNumber) );
01499        //#5561: If we are going to delete the first page, do not set the current page to it
01500        if (pageNumber!=0)
01501               setCurrentPage(Pages->at(pageNumber!=0?0:1));
01502        Page* page = Pages->at(pageNumber);
01503        Pages->remove(pageNumber);
01504        delete page;
01505        changed();
01506 }
01507 
01508 void ScribusDoc::movePage(const int from, const int to, const int ziel, const int art)
01509 {
01510        QPtrList<Page> Buf;
01511        int zz = ziel;
01512        Buf.clear();
01513        for (int a = from; a < to; ++a)
01514        {
01515               Buf.append(Pages->at(from));
01516               Pages->remove(from);
01517               if (a <= zz)
01518                      --zz;
01519        }
01520        uint bufCount=Buf.count();
01521        switch (art)
01522        {
01523               case 0:
01524                      for (uint b = 0; b < bufCount; ++b)
01525                             Pages->insert(zz++, Buf.at(b));
01526                      break;
01527               case 1:
01528                      for (uint b = 0; b < bufCount; ++b)
01529                             Pages->insert(++zz, Buf.at(b));
01530                      break;
01531               case 2:
01532                      for (uint b = 0; b < bufCount; ++b)
01533                             Pages->append(Buf.at(b));
01534                      break;
01535        }
01536        changed();
01537 }
01538 
01539 int ScribusDoc::addAutomaticTextFrame(const int pageNumber)
01540 {
01541        if (!automaticTextFrames)
01542               return -1;
01543        Page *addToPage=DocPages.at(pageNumber);
01544        if ((!masterPageMode()) && (usesAutomaticTextFrames()))// && (!isLoading()))
01545        {
01546               int z = itemAdd(PageItem::TextFrame, PageItem::Unspecified,
01547                                    addToPage->Margins.Left+addToPage->xOffset(),
01548                                    addToPage->Margins.Top+addToPage->yOffset(), pageWidth-addToPage->Margins.Right-addToPage->Margins.Left,
01549                                    pageHeight-addToPage->Margins.Bottom-addToPage->Margins.Top,
01550                                                   1, CommonStrings::None, toolSettings.dPen, true);
01551               Items->at(z)->isAutoText = true;
01552               Items->at(z)->Cols = qRound(PageSp);
01553               Items->at(z)->ColGap = PageSpa;
01554               if (LastAuto != 0) {
01555                      LastAuto->link(Items->at(z));
01556               }      
01557               else
01558                      FirstAuto = Items->at(z);
01559               LastAuto = Items->at(z);
01560               Items->at(z)->setRedrawBounding();
01561               return z;
01562        }
01563        return -1;
01564 }
01565 
01566 int ScribusDoc::addLayer(const QString& layerName, const bool activate)
01567 {
01568        struct Layer ll;
01569        ll.LNr = Layers.last().LNr + 1;
01570        ll.Level = Layers.count();
01571        if (layerName.isNull() || layerName.isEmpty())
01572        {
01573               QString tmp;
01574               ll.Name = tr("New Layer")+" "+tmp.setNum(ll.LNr);
01575        }
01576        else
01577               ll.Name = layerName;
01578        ll.isViewable = true;
01579        ll.isPrintable = true;
01580        ll.isEditable = true;
01581        ll.flowControl = true;
01582        ll.outlineMode = false;
01583        ll.transparency = 1.0;
01584        ll.blendMode = 0;
01585        QColor marker;
01586        switch (ll.LNr % 7)
01587        {
01588               case 0:
01589                      marker = Qt::black;
01590                      break;
01591               case 1:
01592                      marker = Qt::red;
01593                      break;
01594               case 2:
01595                      marker = Qt::green;
01596                      break;
01597               case 3:
01598                      marker = Qt::blue;
01599                      break;
01600               case 4:
01601                      marker = Qt::cyan;
01602                      break;
01603               case 5:
01604                      marker = Qt::magenta;
01605                      break;
01606               case 6:
01607                      marker = Qt::yellow;;
01608                      break;
01609        }
01610        ll.markerColor = marker;
01611        Layers.append(ll);
01612        if (activate)
01613               setActiveLayer(ll.LNr);
01614 
01615        if (UndoManager::undoEnabled())
01616        {
01617               SimpleState *ss = new SimpleState(Um::AddLayer, "", Um::ICreate);
01618               ss->set("ADD_LAYER", "add_layer");
01619               ss->set("ACTIVE", ActiveLayer);
01620               ss->set("NAME", ll.Name);
01621               ss->set("LAYER_NR", ll.LNr);
01622               undoManager->action(this, ss, DocName, Um::ILayer);
01623        }
01624        return ll.LNr;
01625 }
01626 
01627 void ScribusDoc::copyLayer(int layerNumberToCopy, int whereToInsert)
01628 {
01629        int GrMax = GroupCounter;
01630        QMap<int,int> TableID;
01631        QPtrList<PageItem> TableItems;
01632        TableID.clear();
01633        TableItems.clear();
01634        uint oldItems = Items->count();
01635        QPixmap pgPix(10, 10);
01636        QRect rd = QRect(0,0,9,9);
01637        ScPainter *painter = new ScPainter(&pgPix, pgPix.width(), pgPix.height());
01638        RePos = true;
01639        for (uint ite = 0; ite < oldItems; ++ite)
01640        {
01641               PageItem *itemToCopy = Items->at(ite);
01642               if (itemToCopy->LayerNr == layerNumberToCopy)
01643               {
01644                      struct CopyPasteBuffer Buffer;
01645                      itemToCopy->copyToCopyPasteBuffer(&Buffer);
01646                      if (itemToCopy->Groups.count() != 0)
01647                      {
01648                             Buffer.Groups.clear();
01649                             QValueStack<int>::Iterator nx;
01650                             QValueStack<int> tmpGroup;
01651                             for (nx = itemToCopy->Groups.begin(); nx != itemToCopy->Groups.end(); ++nx)
01652                             {
01653                                    tmpGroup.push((*nx)+GroupCounter);
01654                                    GrMax = QMAX(GrMax, (*nx)+GroupCounter);
01655                             }
01656                             for (nx = tmpGroup.begin(); nx != tmpGroup.end(); ++nx)
01657                             {
01658                                    Buffer.Groups.push((*nx));
01659                             }
01660                      }
01661                      m_View->PasteItem(&Buffer, true, true);
01662                      PageItem* Neu = Items->at(Items->count()-1);
01663                      Neu->LayerNr = whereToInsert;
01664                      Neu->OnMasterPage = "";
01665                      if (itemToCopy->isBookmark)
01666                             m_ScMW->AddBookMark(Neu);
01667                      if (Neu->isTableItem)
01668                      {
01669                             TableItems.append(Neu);
01670                             TableID.insert(ite, Neu->ItemNr);
01671                      }
01672                      bool upDtImg = false;
01673                      if (itemToCopy->pixm.imgInfo.valid)
01674                      {
01675                             Neu->pixm.imgInfo = itemToCopy->pixm.imgInfo;
01676                             upDtImg = true;
01677                      }
01678                      if (itemToCopy->effectsInUse.count() != 0)
01679                      {
01680                             Neu->effectsInUse = itemToCopy->effectsInUse;
01681                             upDtImg = true;
01682                      }
01683                      if (upDtImg)
01684                      {
01685                             int fho = Neu->imageFlippedH();
01686                             int fvo = Neu->imageFlippedV();
01687                             loadPict(Neu->Pfile, Neu, true);
01688                             Neu->setImageFlippedH(fho);
01689                             Neu->setImageFlippedV(fvo);
01690                             Neu->AdjustPictScale();
01691                      }
01692                      Neu->DrawObj(painter, rd);
01693               }
01694        }
01695        delete painter;
01696        RePos = false;
01697        if (TableItems.count() != 0)
01698        {
01699               for (uint ttc = 0; ttc < TableItems.count(); ++ttc)
01700               {
01701                      PageItem* ta = TableItems.at(ttc);
01702                      if (ta->TopLinkID != -1)
01703                             ta->TopLink = Items->at(TableID[ta->TopLinkID]);
01704                      else
01705                             ta->TopLink = 0;
01706                      if (ta->LeftLinkID != -1)
01707                             ta->LeftLink = Items->at(TableID[ta->LeftLinkID]);
01708                      else
01709                             ta->LeftLink = 0;
01710                      if (ta->RightLinkID != -1)
01711                             ta->RightLink = Items->at(TableID[ta->RightLinkID]);
01712                      else
01713                             ta->RightLink = 0;
01714                      if (ta->BottomLinkID != -1)
01715                             ta->BottomLink = Items->at(TableID[ta->BottomLinkID]);
01716                      else
01717                             ta->BottomLink = 0;
01718               }
01719        }
01720        GroupCounter = GrMax + 1;
01721        changed();
01722 }
01723 
01724 bool ScribusDoc::deleteLayer(const int layerNumber, const bool deleteItems)
01725 {
01726        if (Layers.count() < 2)
01727               return false;
01728        QValueList<Layer>::iterator it2;
01729        QValueList<Layer>::iterator it2end=Layers.end();
01730        bool found=false;
01731        int layerLevel = -1;
01732        for (it2 = Layers.begin(); it2 != it2end; ++it2)
01733        {
01734               if ((*it2).LNr == layerNumber)
01735               {
01736                      layerLevel=(*it2).Level;
01737                      found=true;
01738                      break;
01739               }
01740        }
01741        if (!found)
01742               return false;
01743        if (UndoManager::undoEnabled())
01744               undoManager->beginTransaction("Layer", Um::IDocument, Um::DeleteLayer, "", Um::IDelete);
01745 
01746        if (ScCore->usingGUI())
01747               removeLayer(layerNumber, deleteItems);
01748        /*
01749        //Layer found, do we want to delete its items too?
01750        if (masterPageMode)
01751               MasterPages = Pages;
01752        else
01753               DocPages = Pages;
01754        for (uint b = 0; b < MasterItems.count(); ++b)
01755        {
01756               if (MasterItems.at(b)->LayerNr == layerNumber)
01757               {
01758                      if (deleteItems)
01759                      {
01760                             MasterItems.at(b)->setTagged(true);
01761                             DocItems.at(b)->setLocked(false);
01762                      }
01763                      else
01764                             MasterItems.at(b)->setTagged(false);
01765               }
01766        }
01767 //     if (view->SelItem.count() != 0)
01768 //            view->DeleteItem();
01769 //     view->SelItem.clear();
01770        for (uint b = 0; b < DocItems.count(); ++b)
01771        {
01772               if (DocItems.at(b)->LayerNr == l)
01773               {
01774                      if (deleteItems)
01775                      {
01776                             DocItems.at(b)->setTagged(true);
01777                             DocItems.at(b)->setLocked(false);
01778                      }
01779                      else
01780                             DocItems.at(b)->setLayer(0);
01781               }
01782        }
01783 //     if (view->SelItem.count() != 0)
01784 //            view->DeleteItem();
01785 
01786        bool deletedOk=deleteTaggedItems();
01787        Q_ASSERT(deletedOk);
01788 
01789        */
01790        //Now delete the layer
01791 
01792        QString name = (*it2).Name;
01793        Layers.remove(it2);
01794        QValueList<Layer>::iterator it;
01795        QValueList<Layer>::iterator itend=Layers.end();
01796        for (it = Layers.begin(); it != itend; ++it)
01797        {
01798               if ((*it).Level > layerLevel)
01799                      (*it).Level -= 1;
01800        }
01801        if (UndoManager::undoEnabled())
01802        {
01803               SimpleState *ss = new SimpleState(Um::DeleteLayer, "", Um::IDelete);
01804               ss->set("REMOVE_LAYER", "remove_layer");
01805               ss->set("ACTIVE", layerNumber);
01806               ss->set("LEVEL", layerLevel);
01807               ss->set("NAME", name);
01808               ss->set("LAYER_NR", layerNumber);
01809               ss->set("DELETE", deleteItems);
01810               undoManager->action(this, ss, DocName, Um::ILayer);
01811               undoManager->commit();
01812        }
01813        setActiveLayer(layerNumberFromLevel(0));
01814        return true;
01815 }
01816 
01817 int ScribusDoc::activeLayer()
01818 {
01819        return ActiveLayer;
01820 }
01821 
01822 const QString& ScribusDoc::activeLayerName()
01823 {
01824        QValueList<Layer>::iterator itend=Layers.end();
01825        QValueList<Layer>::iterator it;
01826        bool found=false;
01827        for (it = Layers.begin(); it != itend; ++it)
01828        {
01829               if ((*it).LNr == ActiveLayer)
01830               {
01831                      found=true;
01832                      break;
01833               }
01834        }
01835        Q_ASSERT(found);
01836        return (*it).Name;
01837 }
01838 
01839 bool ScribusDoc::setActiveLayer(const int layerToActivate)
01840 {
01841        bool found=false;
01842        uint layerCount=Layers.count();
01843 
01844        for (uint i=0; i < layerCount; ++i)
01845        {
01846               if (Layers[i].LNr == layerToActivate)
01847               {
01848                      found = true;
01849                      break;
01850               }
01851        }
01852        Q_ASSERT(found);
01853        if (found)
01854               ActiveLayer=layerToActivate;
01855        return found;
01856 }
01857 
01858 bool ScribusDoc::setActiveLayer(const QString& layerNameToActivate)
01859 {
01860        bool found=false;
01861        uint layerCount=Layers.count();
01862        uint i;
01863        for (i=0; i < layerCount; ++i)
01864        {
01865               if (Layers[i].Name == layerNameToActivate)
01866               {
01867                      found = true;
01868                      break;
01869               }
01870        }
01871        if (found)
01872               ActiveLayer=Layers[i].LNr;
01873        return found;
01874 }
01875 
01876 bool ScribusDoc::setLayerPrintable(const int layerNumber, const bool isPrintable)
01877 {
01878        QValueList<Layer>::iterator itend=Layers.end();
01879        QValueList<Layer>::iterator it;
01880        bool found=false;
01881        for (it = Layers.begin(); it != itend; ++it)
01882        {
01883               if ((*it).LNr == layerNumber)
01884               {
01885                      bool oldPrintable = (*it).isPrintable;
01886                      (*it).isPrintable = isPrintable;
01887 
01888                      if (oldPrintable!=isPrintable && UndoManager::undoEnabled())
01889                      {
01890                             SimpleState *ss = new SimpleState(isPrintable ? Um::PrintLayer : Um::DoNotPrintLayer,
01891                                                                     "", Um::IPrint);
01892                             ss->set("PRINT_LAYER", "print_layer");
01893                             ss->set("ACTIVE", (*it).LNr);
01894                             ss->set("PRINT", isPrintable);
01895                             undoManager->action(this, ss, DocName, Um::IDocument);
01896                      }
01897                      found=true;
01898                      break;
01899               }
01900        }
01901        if (found)
01902               changed();
01903        return found;
01904 }
01905 
01906 bool ScribusDoc::layerPrintable(const int layerNumber)
01907 {
01908        QValueList<Layer>::iterator itend=Layers.end();
01909        QValueList<Layer>::iterator it;
01910        for (it = Layers.begin(); it != itend; ++it)
01911        {
01912               if ((*it).LNr == layerNumber)
01913                      return (*it).isPrintable;
01914        }
01915        return false;
01916 }
01917 
01918 bool ScribusDoc::setLayerVisible(const int layerNumber, const bool isViewable)
01919 {
01920        QValueList<Layer>::iterator itend=Layers.end();
01921        QValueList<Layer>::iterator it;
01922        bool found=false;
01923        for (it = Layers.begin(); it != itend; ++it)
01924        {
01925               if ((*it).LNr == layerNumber)
01926               {
01927                      (*it).isViewable = isViewable;
01928                      found=true;
01929                      break;
01930               }
01931        }
01932        if (found)
01933               changed();
01934        return found;
01935 }
01936 
01937 bool ScribusDoc::layerVisible(const int layerNumber)
01938 {
01939        QValueList<Layer>::iterator itend=Layers.end();
01940        QValueList<Layer>::iterator it;
01941        for (it = Layers.begin(); it != itend; ++it)
01942        {
01943               if ((*it).LNr == layerNumber)
01944                      return (*it).isViewable;
01945        }
01946        return false;
01947 }
01948 
01949 bool ScribusDoc::setLayerLocked(const int layerNumber, const bool isLocked)
01950 {
01951        QValueList<Layer>::iterator itend=Layers.end();
01952        QValueList<Layer>::iterator it;
01953        bool found=false;
01954        for (it = Layers.begin(); it != itend; ++it)
01955        {
01956               if ((*it).LNr == layerNumber)
01957               {
01958                      (*it).isEditable = !isLocked;
01959                      found=true;
01960                      break;
01961               }
01962        }
01963        if (found)
01964               changed();
01965        return found;
01966 }
01967 
01968 bool ScribusDoc::layerLocked(const int layerNumber)
01969 {
01970        QValueList<Layer>::iterator itend=Layers.end();
01971        QValueList<Layer>::iterator it;
01972        for (it = Layers.begin(); it != itend; ++it)
01973        {
01974               if ((*it).LNr == layerNumber)
01975                      return !(*it).isEditable;
01976        }
01977        return false;
01978 }
01979 
01980 bool ScribusDoc::setLayerFlow(const int layerNumber, const bool flow)
01981 {
01982        QValueList<Layer>::iterator itend=Layers.end();
01983        QValueList<Layer>::iterator it;
01984        bool found=false;
01985        for (it = Layers.begin(); it != itend; ++it)
01986        {
01987               if ((*it).LNr == layerNumber)
01988               {
01989                      (*it).flowControl = flow;
01990                      found=true;
01991                      break;
01992               }
01993        }
01994        if (found)
01995               changed();
01996        return found;
01997 }
01998 
01999 bool ScribusDoc::layerFlow(const int layerNumber)
02000 {
02001        QValueList<Layer>::iterator itend=Layers.end();
02002        QValueList<Layer>::iterator it;
02003        for (it = Layers.begin(); it != itend; ++it)
02004        {
02005               if ((*it).LNr == layerNumber)
02006                      return (*it).flowControl;
02007        }
02008        return false;
02009 }
02010 
02011 bool ScribusDoc::setLayerTransparency(const int layerNumber, double trans)
02012 {
02013        QValueList<Layer>::iterator itend=Layers.end();
02014        QValueList<Layer>::iterator it;
02015        bool found=false;
02016        for (it = Layers.begin(); it != itend; ++it)
02017        {
02018               if ((*it).LNr == layerNumber)
02019               {
02020                      (*it).transparency = trans;
02021                      found=true;
02022                      break;
02023               }
02024        }
02025        if (found)
02026               changed();
02027        return found;
02028 }
02029 
02030 double ScribusDoc::layerTransparency(const int layerNumber)
02031 {
02032        QValueList<Layer>::iterator itend=Layers.end();
02033        QValueList<Layer>::iterator it;
02034        for (it = Layers.begin(); it != itend; ++it)
02035        {
02036               if ((*it).LNr == layerNumber)
02037                      return (*it).transparency;
02038        }
02039        return 1.0;
02040 }
02041 
02042 bool ScribusDoc::setLayerBlendMode(const int layerNumber, int blend)
02043 {
02044        QValueList<Layer>::iterator itend=Layers.end();
02045        QValueList<Layer>::iterator it;
02046        bool found=false;
02047        for (it = Layers.begin(); it != itend; ++it)
02048        {
02049               if ((*it).LNr == layerNumber)
02050               {
02051                      (*it).blendMode = blend;
02052                      found=true;
02053                      break;
02054               }
02055        }
02056        if (found)
02057               changed();
02058        return found;
02059 }
02060 
02061 int ScribusDoc::layerBlendMode(const int layerNumber)
02062 {
02063        QValueList<Layer>::iterator itend=Layers.end();
02064        QValueList<Layer>::iterator it;
02065        for (it = Layers.begin(); it != itend; ++it)
02066        {
02067               if ((*it).LNr == layerNumber)
02068                      return (*it).blendMode;
02069        }
02070        return 0;
02071 }
02072 
02073 bool ScribusDoc::setLayerOutline(const int layerNumber, const bool outline)
02074 {
02075        QValueList<Layer>::iterator itend=Layers.end();
02076        QValueList<Layer>::iterator it;
02077        bool found=false;
02078        for (it = Layers.begin(); it != itend; ++it)
02079        {
02080               if ((*it).LNr == layerNumber)
02081               {
02082                      (*it).outlineMode = outline;
02083                      found=true;
02084                      break;
02085               }
02086        }
02087        if (found)
02088               changed();
02089        return found;
02090 }
02091 
02092 bool ScribusDoc::layerOutline(const int layerNumber)
02093 {
02094        QValueList<Layer>::iterator itend=Layers.end();
02095        QValueList<Layer>::iterator it;
02096        for (it = Layers.begin(); it != itend; ++it)
02097        {
02098               if ((*it).LNr == layerNumber)
02099                      return (*it).outlineMode;
02100        }
02101        return false;
02102 }
02103 
02104 bool ScribusDoc::setLayerMarker(const int layerNumber, QColor color)
02105 {
02106        QValueList<Layer>::iterator itend=Layers.end();
02107        QValueList<Layer>::iterator it;
02108        bool found=false;
02109        for (it = Layers.begin(); it != itend; ++it)
02110        {
02111               if ((*it).LNr == layerNumber)
02112               {
02113                      (*it).markerColor = color;
02114                      found=true;
02115                      break;
02116               }
02117        }
02118        if (found)
02119               changed();
02120        return found;
02121 }
02122 
02123 QColor ScribusDoc::layerMarker(const int layerNumber)
02124 {
02125        QValueList<Layer>::iterator itend=Layers.end();
02126        QValueList<Layer>::iterator it;
02127        for (it = Layers.begin(); it != itend; ++it)
02128        {
02129               if ((*it).LNr == layerNumber)
02130                      return (*it).markerColor;
02131        }
02132        return QColor(0, 0, 0);
02133 }
02134 
02135 int ScribusDoc::layerLevelFromNumber(const int layerNumber)
02136 {
02137        uint layerCount=Layers.count();
02138        for (uint i=0; i < layerCount; ++i)
02139        {
02140               if (Layers[i].LNr == layerNumber)
02141                      return Layers[i].Level;
02142        }
02143        return -1;
02144 }
02145 
02146 int ScribusDoc::layerCount() const
02147 {
02148        return Layers.count();
02149 }
02150 
02151 int ScribusDoc::layerNumberFromLevel(const int layerLevel)
02152 {
02153        uint layerCount=Layers.count();
02154        for (uint i=0; i < layerCount; ++i)
02155        {
02156               if (Layers[i].Level == layerLevel)
02157                      return Layers[i].LNr;
02158        }
02159        return -1;
02160 }
02161 
02162 bool ScribusDoc::lowerLayer(const int layerNumber)
02163 {
02164        return lowerLayerByLevel(layerLevelFromNumber(layerNumber));
02165 }
02166 
02167 bool ScribusDoc::lowerLayerByLevel(const int layerLevel)
02168 {
02169        if (Layers.count() < 2)
02170               return false;
02171        if (UndoManager::undoEnabled())
02172        {
02173               SimpleState *ss = new SimpleState(Um::LowerLayer, "", Um::IDown);
02174               ss->set("DOWN_LAYER", "down_layer");
02175               ss->set("ACTIVE", layerLevel-1);
02176               undoManager->action(this, ss, DocName, Um::ILayer);
02177        }
02178 
02179        QValueList<Layer>::iterator it;
02180        QValueList<Layer>::iterator itend=Layers.end();
02181        for (it = Layers.begin(); it != itend; ++it)
02182        {
02183               if ((*it).Level == layerLevel-1)
02184                      break;
02185        }
02186        QValueList<Layer>::iterator it2;
02187        QValueList<Layer>::iterator it2end=Layers.end();
02188        for (it2 = Layers.begin(); it2 != it2end; ++it2)
02189        {
02190               if ((*it2).Level == layerLevel)
02191                      break;
02192        }
02193        (*it2).Level -= 1;
02194        (*it).Level += 1;
02195        return true;
02196 }
02197 
02198 bool ScribusDoc::raiseLayer(const int layerNumber)
02199 {
02200        return raiseLayerByLevel(layerLevelFromNumber(layerNumber));
02201 }
02202 
02203 bool ScribusDoc::raiseLayerByLevel(const int layerLevel)
02204 {
02205        if (Layers.count() < 2)
02206               return false;
02207        if (UndoManager::undoEnabled())
02208        {
02209               SimpleState *ss = new SimpleState(Um::RaiseLayer, "", Um::IUp);
02210               ss->set("UP_LAYER", "up_layer");
02211               ss->set("ACTIVE", layerLevel+1);
02212               undoManager->action(this, ss, DocName, Um::ILayer);
02213        }
02214 
02215        QValueList<Layer>::iterator it;
02216        QValueList<Layer>::iterator itend=Layers.end();
02217        for (it = Layers.begin(); it != itend; ++it)
02218        {
02219               if ((*it).Level == layerLevel+1)
02220                      break;
02221        }
02222        QValueList<Layer>::iterator it2;
02223        QValueList<Layer>::iterator it2end=Layers.end();
02224        for (it2 = Layers.begin(); it2 != it2end; ++it2)
02225        {
02226               if ((*it2).Level == layerLevel)
02227                      break;
02228        }
02229        (*it2).Level += 1;
02230        (*it).Level -= 1;
02231        return true;
02232 }
02233 
02234 const QString& ScribusDoc::layerName(const int layerNumber) const
02235 {
02236        uint layerCount=Layers.count();
02237        for (uint i=0; i < layerCount; ++i)
02238        {
02239               if (Layers[i].LNr == layerNumber)
02240                      return Layers[i].Name;
02241        }
02242        return QString::null;
02243 }
02244 
02245 bool ScribusDoc::changeLayerName(const int layerNumber, const QString& newName)
02246 {
02247        uint layerCount=Layers.count();
02248        bool found=false;
02249        for (uint i=0; i < layerCount; ++i)
02250        {
02251               if (Layers[i].LNr == layerNumber)
02252               {
02253                      if (Layers[i].Name != newName)
02254                      {
02255                             if (UndoManager::undoEnabled())
02256                             {
02257                                    SimpleState *ss = new SimpleState(Um::SetLayerName,
02258                                                                                            QString(Um::FromTo).arg(Layers[i].Name).arg(newName),
02259                                                                                            Um::IDown);
02260                                    ss->set("CHANGE_NAME", "change_name");
02261                                    ss->set("ACTIVE", ActiveLayer);
02262                                    ss->set("NEW_NAME", newName);
02263                                    ss->set("OLD_NAME", Layers[i].Name);
02264                                    undoManager->action(this, ss, DocName, Um::ILayer);
02265                             }
02266                             Layers[i].Name = newName;
02267                             found=true;
02268                      }
02269                      break;
02270               }
02271        }
02272        if (found)
02273               changed();
02274        return found;
02275 }
02276 
02277 bool ScribusDoc::layerContainsItems(const int layerNumber)
02278 {
02279        uint masterItemsCount=MasterItems.count();
02280        for (uint i = 0; i < masterItemsCount; ++i)
02281        {
02282               if (MasterItems.at(i)->LayerNr == layerNumber)
02283                      return true;
02284        }
02285        uint docItemsCount=DocItems.count();
02286        for (uint i = 0; i < docItemsCount; ++i)
02287        {
02288               if (DocItems.at(i)->LayerNr == layerNumber)
02289                      return true;
02290        }
02291        return false;
02292 }
02293 
02294 void ScribusDoc::orderedLayerList(QStringList* list)
02295 {
02296        Q_ASSERT(list!=NULL);
02297        uint layerCount=Layers.count();
02298        if (layerCount != 0)
02299        {
02300               for (uint i=0; i < layerCount; ++i)
02301               {
02302                      QValueList<Layer>::iterator itend=Layers.end();
02303                      for (QValueList<Layer>::iterator it = Layers.begin(); it != itend; ++it)
02304                      {
02305                             if (layerCount-(*it).Level-1 == i)
02306                                    list->append((*it).Name);
02307                      }
02308               }
02309        }
02310 }
02311 
02312 bool ScribusDoc::renumberLayer(const int layerNumber, const int newLayerNumber)
02313 {
02314        uint layerCount=Layers.count();
02315        uint foundIndex = 0;
02316        bool found=false;
02317        //Find layer to renumber, if found the new number, return as it exists already.
02318        for (uint i=0; i < layerCount; ++i)
02319        {
02320               if (Layers[i].LNr == layerNumber)
02321               {
02322                      foundIndex=i;
02323                      found=true;
02324               }
02325               else
02326               if (Layers[i].LNr == newLayerNumber)
02327                      return false;
02328        }
02329        if (!found)
02330               return false;
02331        Layers[foundIndex].LNr=newLayerNumber;
02332        return true;
02333 }
02334 
02335 //Make the doc delete the items, not the view. TODO: Currently does nada, zilch, zero
02336 bool ScribusDoc::deleteTaggedItems()
02337 {
02338        QString tooltip = Um::ItemsInvolved + "\n";
02339        //Master Items
02340        for (uint b = 0; b < MasterItems.count(); ++b)
02341        {
02342               if (MasterItems.at(b)->isTagged())
02343               {
02344               }
02345        }
02346        //Doc Items
02347        for (uint b = 0; b < DocItems.count(); ++b)
02348        {
02349               if (DocItems.at(b)->isTagged())
02350               {
02351               }
02352        }
02353        return true;
02354 }
02355 
02356 void ScribusDoc::replaceLineStyleColors(const QMap<QString, QString>& colorMap)
02357 {
02358        multiLine::iterator its;
02359        QMap<QString, QString>::const_iterator it;
02360        QMap<QString,multiLine>::iterator  itl;
02361        for (itl = MLineStyles.begin(); itl != MLineStyles.end(); ++itl)
02362        {
02363               multiLine& mline = itl.data();
02364               for (its = mline.begin(); its != mline.end(); ++its)
02365               {
02366                      struct SingleLine& sline = *its;
02367                      it = colorMap.find(sline.Color);
02368                      if (it != colorMap.end())
02369                             sline.Color = it.data();
02370               }
02371        }
02372 }
02373 
02374 void ScribusDoc::getUsedColors(ColorList &colorsToUse, bool spot)
02375 {
02376        bool found;
02377        colorsToUse.clear();
02378        colorsToUse.setDocument(this);
02379        ColorList::Iterator it;
02380 
02381        ResourceCollection resources;
02382        this->getNamedResources(resources);
02383        const QMap<QString, QString>& resColors = resources.colors();
02384 
02385        for (it = PageColors.begin(); it != PageColors.end(); ++it)
02386        {
02387               found = false;
02388               // Tool preferences colors
02389               if ((it.key() == toolSettings.dBrush) || (it.key() == toolSettings.dPen) || (it.key() == toolSettings.dBrushPict)
02390                       || (it.key() == toolSettings.dPenLine) || (it.key() == toolSettings.dPenText))
02391               {
02392                      if (spot)
02393                      {
02394                             if (it.data().isSpotColor())
02395                                    colorsToUse.insert(it.key(), it.data());
02396                      }
02397                      else
02398                             colorsToUse.insert(it.key(), it.data());
02399                      continue;
02400               }
02401               // Current paragraph style colors
02402               if ((it.key() == currentStyle.charStyle().fillColor()) || (it.key() == currentStyle.charStyle().strokeColor()))
02403                      found = true;
02404               // Resources colors
02405               if (!found)
02406                      found = resColors.contains(it.key());
02407               // Line styles colors
02408               if (!found)
02409                      found = lineStylesUseColor(it.key());
02410               if (found)
02411               {
02412                      if (spot)
02413                      {
02414                             if (it.data().isSpotColor())
02415                                    colorsToUse.insert(it.key(), it.data());
02416                      }
02417                      else
02418                             colorsToUse.insert(it.key(), it.data());
02419                      continue;
02420               }
02421        }
02422 }
02423 
02424 bool ScribusDoc::lineStylesUseColor(const QString& colorName)
02425 {
02426        bool found = false;
02427        QMap<QString,multiLine>::const_iterator itm, itmend;
02428        multiLine::const_iterator its, itsend;
02429        itmend = MLineStyles.constEnd();
02430        for (itm = MLineStyles.constBegin(); itm != itmend && !found; ++itm)
02431        {
02432               const multiLine& ml = itm.data();
02433               itsend = ml.constEnd();
02434               for (its = ml.constBegin(); its != itsend; ++its)
02435               {
02436                      if ( its->Color == colorName )
02437                      {
02438                             found = true;
02439                             break;
02440                      }
02441               }
02442        }
02443        return found;
02444 }
02445 
02446 bool ScribusDoc::addPattern(QString &name, ScPattern& pattern)
02447 {
02448        docPatterns.insert(name, pattern);
02449        return true;
02450 }
02451 
02452 void ScribusDoc::setPatterns(QMap<QString, ScPattern> &patterns)
02453 {
02454        docPatterns.clear();
02455        docPatterns=patterns;
02456 //     for (QMap<QString, ScPattern>::Iterator it = patterns.begin(); it != patterns.end(); ++it)
02457 //     {
02458 //            docPatterns.insert(it.key(), it.data());
02459 //     }
02460        for (uint c=0; c<DocItems.count(); ++c)
02461        {
02462               PageItem *ite = DocItems.at(c);
02463               if ((!docPatterns.contains(ite->pattern())) && (ite->GrType == 8))
02464               {
02465                      ite->setPattern("");
02466                      ite->GrType = 0;
02467               }
02468        }
02469        for (uint c=0; c<MasterItems.count(); ++c)
02470        {
02471               PageItem *ite = MasterItems.at(c);
02472               if ((!docPatterns.contains(ite->pattern())) && (ite->GrType == 8))
02473               {
02474                      ite->setPattern("");
02475                      ite->GrType = 0;
02476               }
02477        }
02478        for (uint c=0; c<FrameItems.count(); ++c)
02479        {
02480               PageItem *ite = FrameItems.at(c);
02481               if ((!docPatterns.contains(ite->pattern())) && (ite->GrType == 8))
02482               {
02483                      ite->setPattern("");
02484                      ite->GrType = 0;
02485               }
02486        }
02487 }
02488 
02489 QStringList ScribusDoc::getUsedPatterns()
02490 {
02491        QStringList results;
02492        for (uint c = 0; c < MasterItems.count(); ++c)
02493        {
02494               if ((!results.contains(MasterItems.at(c)->pattern())) && (MasterItems.at(c)->GrType == 8))
02495                      results.append(MasterItems.at(c)->pattern());
02496        }
02497        for (uint c = 0; c < DocItems.count(); ++c)
02498        {
02499               if ((!results.contains(DocItems.at(c)->pattern())) && (DocItems.at(c)->GrType == 8))
02500                      results.append(DocItems.at(c)->pattern());
02501        }
02502        for (uint c = 0; c < FrameItems.count(); ++c)
02503        {
02504               if ((!results.contains(FrameItems.at(c)->pattern())) && (FrameItems.at(c)->GrType == 8))
02505                      results.append(FrameItems.at(c)->pattern());
02506        }
02507        for (uint c = 0; c < results.count(); ++c)
02508        {
02509               QStringList pats = getUsedPatternsHelper(results[c], results);
02510               if (!pats.isEmpty())
02511                      results += pats;
02512        }
02513        return results;
02514 }
02515 
02516 QStringList ScribusDoc::getUsedPatternsSelection()
02517 {
02518        QStringList results;
02519        uint selectedItemCount=m_Selection->count();
02520        if (selectedItemCount != 0)
02521        {
02522               for (uint a = 0; a < selectedItemCount; ++a)
02523               {
02524                      PageItem *currItem = m_Selection->itemAt(a);
02525                      if ((!results.contains(currItem->pattern())) && (currItem->GrType == 8))
02526                             results.append(currItem->pattern());
02527               }
02528               for (uint c = 0; c < results.count(); ++c)
02529               {
02530                      QStringList pats = getUsedPatternsHelper(results[c], results);
02531                      if (!pats.isEmpty())
02532                             results += pats;
02533               }
02534               return results;
02535        }
02536        else
02537               return QStringList();
02538 }
02539 
02540 QStringList ScribusDoc::getUsedPatternsHelper(QString pattern, QStringList &results)
02541 {
02542        ScPattern *pat = &docPatterns[pattern];
02543        QStringList pats;
02544        pats.clear();
02545        for (uint c = 0; c < pat->items.count(); ++c)
02546        {
02547               if ((!results.contains(pat->items.at(c)->pattern())) && (pat->items.at(c)->GrType == 8))
02548                      pats.append(pat->items.at(c)->pattern());
02549        }
02550        if (!pats.isEmpty())
02551        {
02552               for (uint c = 0; c < pats.count(); ++c)
02553               {
02554                      getUsedPatternsHelper(pats[c], results);
02555               }
02556        }
02557        return pats;
02558 }
02559 
02560 void ScribusDoc::getUsedFonts(QMap<QString, QMap<uint, FPointArray> > & Really)
02561 {
02562        PageItem* it = NULL;
02563        uint counter = 0;
02564        for (uint lc = 0; lc < 3; ++lc)
02565        {
02566               switch (lc)
02567               {
02568                      case 0:
02569                             counter = MasterItems.count();
02570                             break;
02571                      case 1:
02572                             counter = DocItems.count();
02573                             break;
02574                      case 2:
02575                             counter = FrameItems.count();
02576                             break;
02577               }
02578               for (uint d = 0; d < counter; ++d)
02579               {
02580                      switch (lc)
02581                      {
02582                             case 0:
02583                                    it = MasterItems.at(d);
02584                                    break;
02585                             case 1:
02586                                    it = DocItems.at(d);
02587                                    break;
02588                             case 2:
02589                                    it = FrameItems.at(d);
02590                                    break;
02591                      }
02592                      checkItemForFonts(it, Really, lc);
02593               }
02594        }
02595        QStringList patterns = getUsedPatterns();
02596        for (uint c = 0; c < patterns.count(); ++c)
02597        {
02598               ScPattern pa = docPatterns[patterns[c]];
02599               for (uint o = 0; o < pa.items.count(); o++)
02600               {
02601                      checkItemForFonts(pa.items.at(o), Really, 3);
02602               }
02603        }
02604 }
02605 
02606 void ScribusDoc::checkItemForFonts(PageItem *it, QMap<QString, QMap<uint, FPointArray> > & Really, uint lc)
02607 {
02608        FPointArray gly;
02609        QString chstr;
02610        if ((it->itemType() == PageItem::TextFrame) || (it->itemType() == PageItem::PathText))
02611        {
02612                      for (int e = 0; e < it->itemText.length(); ++e)
02613                      {
02614                             if (! Really.contains(it->itemText.charStyle(e).font().replacementName()) ) {
02615                                    Really.insert(it->itemText.charStyle(e).font().replacementName(), QMap<uint, FPointArray>());
02616                      }
02617                      uint chr = it->itemText.text(e).unicode();
02618                      if ((chr == 13) || (chr == 32) || (chr == 29))
02619                             continue;
02620                      if (chr == 9)
02621                      {
02622                             for (uint t1 = 0; t1 < it->itemText.paragraphStyle(e).tabValues().count(); t1++)
02623                             {
02624                                    if (it->itemText.paragraphStyle(e).tabValues()[t1].tabFillChar.isNull())
02625                                           continue;
02626                                    chstr = QString(it->itemText.paragraphStyle(e).tabValues()[t1].tabFillChar);
02627                                    if ((it->itemText.charStyle(e).effects() & ScStyle_SmallCaps) || (it->itemText.charStyle(e).effects() & ScStyle_AllCaps))
02628                                    {
02629                                           if (chstr.upper() != QString(it->itemText.paragraphStyle(e).tabValues()[t1].tabFillChar))
02630                                                  chstr = chstr.upper();
02631                                    }
02632                                    chr = chstr[0].unicode();
02633                                    uint gl = it->itemText.charStyle(e).font().char2CMap(chstr[0]);
02634                                    gly = it->itemText.charStyle(e).font().glyphOutline(gl);
02635                                    Really[it->itemText.charStyle(e).font().replacementName()].insert(gl, gly);
02636                             }
02637                             for (uint t1 = 0; t1 < it->itemText.defaultStyle().tabValues().count(); t1++)
02638                             {
02639                                    if (it->itemText.defaultStyle().tabValues()[t1].tabFillChar.isNull())
02640                                           continue;
02641                                    chstr = QString(it->itemText.defaultStyle().tabValues()[t1].tabFillChar);
02642                                    if ((it->itemText.charStyle(e).effects() & ScStyle_SmallCaps) || (it->itemText.charStyle(e).effects() & ScStyle_AllCaps))
02643                                    {
02644                                           if (chstr.upper() != QString(it->itemText.defaultStyle().tabValues()[t1].tabFillChar))
02645                                                  chstr = chstr.upper();
02646                                    }
02647                                    chr = chstr[0].unicode();
02648                                    uint gl = it->itemText.charStyle(e).font().char2CMap(chstr[0]);
02649                                    gly = it->itemText.charStyle(e).font().glyphOutline(gl);
02650                                    Really[it->itemText.charStyle(e).font().replacementName()].insert(gl, gly);
02651                             }
02652                             continue;
02653                      }
02654                      if (chr == 30)
02655                      {
02656                             /* CB Removed forced loading of 0-9 for section based numbering
02657                             for (uint numco = 0x30; numco < 0x3A; ++numco)
02658                             {
02659                                    if (it->itemText.charStyle(e)->cfont->CharWidth.contains(numco))
02660                                    {
02661                                           gly = it->itemText.charStyle(e)->cfont->GlyphArray[numco].Outlines.copy();
02662                                           it->itemText.charStyle(e)->cfont->RealGlyphs.insert(numco, gly);
02663                                    }
02664                             }*/
02665                             //Our page number collection string
02666                             QString pageNumberText(QString::null);
02667                             //If not on a master page just get the page number for the page and the text
02668                             if (lc!=0)
02669                                    pageNumberText=getSectionPageNumberForPageIndex(it->OwnPage);
02670                             else
02671                             {
02672                                    //Else, for a page number in a text frame on a master page we must scan
02673                                    //all pages to see which ones use this page and get their page numbers.
02674                                    //We only add each character of the pages' page number text if its nothing
02675                                    //already in the pageNumberText variable. No need to add glyphs twice.
02676                                    QString newText;
02677                                    uint docPageCount=DocPages.count();
02678                                    for (uint a = 0; a < docPageCount; ++a)
02679                                    {
02680                                           if (DocPages.at(a)->MPageNam == it->OnMasterPage)
02681                                           {
02682                                                  newText=getSectionPageNumberForPageIndex(a);
02683                                                  for (uint nti=0;nti<newText.length();++nti)
02684                                                         if (pageNumberText.find(newText[nti])==-1)
02685                                                                pageNumberText+=newText[nti];
02686                                           }
02687                                    }
02688                             }
02689                             //Now scan and add any glyphs used in page numbers
02690                             for (uint pnti=0;pnti<pageNumberText.length(); ++pnti)
02691                             {
02692                                    uint chr = pageNumberText[pnti].unicode();
02693                                    if (it->itemText.charStyle(e).font().canRender(chr))
02694                                    {
02695                                           uint gl = it->itemText.charStyle(e).font().char2CMap(pageNumberText[pnti]);
02696                                           FPointArray gly(it->itemText.charStyle(e).font().glyphOutline(gl));
02697                                           Really[it->itemText.charStyle(e).font().replacementName()].insert(gl, gly);
02698                                    }
02699                             }
02700                             continue;
02701                      }
02702                      if (it->itemText.charStyle(e).effects() & ScStyle_SmartHyphenVisible)
02703                      {
02704                             uint gl = it->itemText.charStyle(e).font().char2CMap(QChar('-'));
02705                             FPointArray gly(it->itemText.charStyle(e).font().glyphOutline(gl));
02706                             Really[it->itemText.charStyle(e).font().replacementName()].insert(gl, gly);
02707                      }
02708                      if ((it->itemText.charStyle(e).effects() & ScStyle_SmallCaps) || (it->itemText.charStyle(e).effects() & ScStyle_AllCaps))
02709                      {
02710                             chstr = it->itemText.text(e, 1);
02711                             if (chstr.upper() != it->itemText.text(e, 1))
02712                                    chstr = chstr.upper();
02713                             chr = chstr[0].unicode();
02714                      }
02715                      if (it->itemText.charStyle(e).font().canRender(chr))
02716                      {
02717                             uint gl = it->itemText.charStyle(e).font().char2CMap(chr);
02718                             gly = it->itemText.charStyle(e).font().glyphOutline(gl);
02719                             Really[it->itemText.charStyle(e).font().replacementName()].insert(gl, gly);
02720                      }
02721               }
02722        }
02723 }
02724 
02725 void ScribusDoc::getUsedProfiles(ProfilesL& usedProfiles)
02726 {
02727        PageItem* it = NULL;
02728        QString profileName;
02729        QStringList profileNames;
02730        uint counter = 0;
02731        usedProfiles.clear();
02732 
02733        profileNames.append(CMSSettings.DefaultSolidColorRGBProfile);
02734        profileNames.append(CMSSettings.DefaultSolidColorCMYKProfile);
02735        if( profileNames.findIndex(CMSSettings.DefaultImageRGBProfile) < 0 )
02736               profileNames.append(CMSSettings.DefaultImageRGBProfile);
02737        if( profileNames.findIndex(CMSSettings.DefaultImageCMYKProfile) < 0 )
02738               profileNames.append(CMSSettings.DefaultImageCMYKProfile);
02739        if( profileNames.findIndex(CMSSettings.DefaultMonitorProfile) < 0 )
02740               profileNames.append(CMSSettings.DefaultMonitorProfile);
02741        if( profileNames.findIndex(CMSSettings.DefaultPrinterProfile) < 0 )
02742               profileNames.append(CMSSettings.DefaultPrinterProfile);
02743        
02744        for (uint lc = 0; lc < 3; ++lc)
02745        {
02746               if (lc == 0)
02747                      counter = MasterItems.count();
02748               else if(lc == 1)
02749                      counter = DocItems.count();
02750               else if(lc == 2)
02751                      counter = FrameItems.count();
02752               for (uint d = 0; d < counter; ++d)
02753               {
02754                      if (lc == 0)
02755                             it = MasterItems.at(d);
02756                      else if(lc == 1)
02757                             it = DocItems.at(d);
02758                      else if(lc == 2)
02759                             it = FrameItems.at(d);
02760                      if (it->IProfile.isEmpty() || profileNames.contains(it->IProfile))
02761                             continue;
02762                      profileNames.append(it->IProfile);
02763               }
02764        }
02765 
02766        for( QStringList::Iterator pIter = profileNames.begin(); pIter != profileNames.end(); pIter++ )
02767        {
02768               if (ScCore->InputProfiles.contains(*pIter))
02769                      usedProfiles[*pIter] = ScCore->InputProfiles[*pIter];
02770               else if (ScCore->InputProfilesCMYK.contains(*pIter))
02771                      usedProfiles[*pIter] = ScCore->InputProfilesCMYK[*pIter];
02772               else if (ScCore->PrinterProfiles.contains(*pIter))
02773                      usedProfiles[*pIter] = ScCore->PrinterProfiles[*pIter];
02774        }
02775 }
02776 
02777 void ScribusDoc::reorganiseFonts()
02778 {
02779        QMap<QString,int> Really;
02780        //QMap<QString,QFont> DocF;
02781        //DocF = UsedFonts;
02782        uint counter = 0;
02783        for (uint lc = 0; lc < 3; ++lc)
02784        {
02785               switch (lc)
02786               {
02787                      case 0:
02788                             counter = MasterItems.count();
02789                             break;
02790                      case 1:
02791                             counter = DocItems.count();
02792                             break;
02793                      case 2:
02794                             counter = FrameItems.count();
02795                             break;
02796               }
02797               PageItem* it = NULL;
02798               for (uint d = 0; d < counter; ++d)
02799               {
02800                      switch (lc)
02801                      {
02802                             case 0:
02803                                    it = MasterItems.at(d);
02804                                    break;
02805                             case 1:
02806                                    it = DocItems.at(d);
02807                                    break;
02808                             case 2:
02809                                    it = FrameItems.at(d);
02810                                    break;
02811                      }
02812                      QString fontName(it->itemText.defaultStyle().charStyle().font().replacementName());
02813                      Really.insert(fontName, UsedFonts[fontName]);
02814                      if ((it->itemType() == PageItem::TextFrame) || (it->itemType() == PageItem::PathText))
02815                      {
02816                             uint itemTextCount=it->itemText.length();
02817                             for (uint e = 0; e < itemTextCount; ++e)
02818                             {
02819                                    Really.insert(it->itemText.charStyle(e).font().replacementName(), UsedFonts[it->itemText.charStyle(e).font().replacementName()]);
02820                             }
02821                      }
02822               }
02823        }
02824        QMap<QString,int>::Iterator itfo, itnext;
02825        for (itfo = UsedFonts.begin(); itfo != UsedFonts.end(); itfo = itnext)
02826        {
02827               itnext = itfo;
02828               ++itnext;
02829               if (!Really.contains(itfo.key()))
02830               {
02831                      (*AllFonts)[itfo.key()].decreaseUsage();
02832                      UsedFonts.remove(itfo);
02833               }
02834        }
02835        PrefsManager* prefsManager=PrefsManager::instance();
02836        AddFont(prefsManager->appPrefs.toolSettings.defFont);//, prefsManager->appPrefs.AvailFonts[prefsManager->appPrefs.toolSettings.defFont]->Font);
02837        AddFont(toolSettings.defFont);//, prefsManager->appPrefs.AvailFonts[toolSettings.defFont]->Font);
02838 }
02839 
02840 void ScribusDoc::setUnitIndex(const int newIndex)
02841 {
02842        docUnitIndex=newIndex;
02843        docUnitRatio = unitGetRatioFromIndex( docUnitIndex );
02844 }
02845 
02846 int ScribusDoc::unitIndex() const
02847 {
02848        return docUnitIndex;
02849 }
02850 
02851 double ScribusDoc::unitRatio() const
02852 {
02853        return docUnitRatio;
02854 }
02855 
02856 bool ScribusDoc::applyMasterPage(const QString& pageName, const int pageNumber)
02857 {
02858        if (!MasterNames.contains(pageName))
02859               return false;
02860        if (UndoManager::undoEnabled())
02861        {
02862               if (DocPages.at(pageNumber)->MPageNam != pageName)
02863               {
02864                      SimpleState *ss = new SimpleState(Um::ApplyMasterPage, QString(Um::FromTo).arg(DocPages.at(pageNumber)->MPageNam).arg(pageName));
02865                      ss->set("PAGE_NUMBER", pageNumber);
02866                      ss->set("OLD_MASTERPAGE", DocPages.at(pageNumber)->MPageNam);
02867                      ss->set("NEW_MASTERPAGE", pageName);
02868                      undoManager->action(this, ss);
02869               }
02870        }
02871 
02872 //     QString mna = pageName;
02873 //     if (mna == CommonStrings::trMasterPageNormal)
02874 //            mna = CommonStrings::masterPageNormal;
02875 //     if (!MasterNames.contains(mna))
02876 //            mna = CommonStrings::masterPageNormal;
02877        Page* Ap = DocPages.at(pageNumber);
02878        Ap->MPageNam = pageName;
02879        const int MpNr = MasterNames[pageName];
02880        Page* Mp = MasterPages.at(MpNr);
02881        PageItem *currItem;
02882        for (currItem = Ap->FromMaster.first(); currItem; currItem = Ap->FromMaster.next())
02883        {
02884               if (currItem->ChangedMasterItem)
02885               {
02886                      Ap->FromMaster.remove(currItem);
02887                      delete currItem;
02888               }
02889        }
02890        Ap->FromMaster.clear();
02891        for (currItem = MasterItems.first(); currItem; currItem = MasterItems.next())
02892        {
02893               if (currItem->OwnPage == MpNr)
02894                      Ap->FromMaster.append(currItem);
02895        }
02896        if (!isLoading())
02897        {
02898               // PV - apply auto guides from MP only if there are no auto guides
02899               // on original page
02900               if (Ap->guides.horizontalAutoCount() != 0 || Ap->guides.horizontalAutoCount() != 0)
02901                      Mp->guides.copy(&Ap->guides, GuideManagerCore::Standard);
02902               else
02903                      Mp->guides.copy(&Ap->guides);
02904 
02905               Ap->initialMargins.Top = Mp->Margins.Top;
02906               Ap->initialMargins.Bottom = Mp->Margins.Bottom;
02907               if (pageSets[currentPageLayout].Columns != 1)
02908               {
02909                      PageLocation pageLoc=locationOfPage(pageNumber);
02910                      if (pageLoc==LeftPage) //Left hand page
02911                      {
02912                             if (Mp->LeftPg != 0)
02913                             {
02914                                    Ap->initialMargins.Right = Mp->initialMargins.Right;
02915                                    Ap->initialMargins.Left = Mp->initialMargins.Left;
02916                             }
02917                             else
02918                             {
02919                                    Ap->initialMargins.Left = Mp->initialMargins.Right;
02920                                    Ap->initialMargins.Right = Mp->initialMargins.Left;
02921                             }
02922                      }
02923                      else if (pageLoc==RightPage) // Right hand page
02924                      {
02925                             if (Mp->LeftPg != 0)
02926                             {
02927                                    Ap->initialMargins.Left = Mp->initialMargins.Right;
02928                                    Ap->initialMargins.Right = Mp->initialMargins.Left;
02929                             }
02930                             else
02931                             {
02932                                    Ap->initialMargins.Right = Mp->initialMargins.Right;
02933                                    Ap->initialMargins.Left = Mp->initialMargins.Left;
02934                             }
02935                      }
02936                      else //Middle pages
02937                      {
02938                             Ap->initialMargins.Left = Mp->initialMargins.Left;
02939                             Ap->initialMargins.Right = Mp->initialMargins.Right;
02940                      }
02941               }
02942               else
02943               {
02944                      Ap->initialMargins.Left = Mp->Margins.Left;
02945                      Ap->initialMargins.Right = Mp->Margins.Right;
02946               }
02947        }
02948        //TODO make a return false if not possible to apply the master page
02949        if (!isLoading())
02950               changed();
02951        return true;
02952 }
02953 
02954 void ScribusDoc::restoreMasterPageApplying(SimpleState *state, bool isUndo)
02955 {
02956        int pageNumber = state->getInt("PAGE_NUMBER");
02957        QString oldName = state->get("OLD_MASTERPAGE");
02958        QString newName = state->get("NEW_MASTERPAGE");
02959        if (isUndo)
02960               applyMasterPage(oldName, pageNumber);
02961        else
02962               applyMasterPage(newName, pageNumber);
02963 }
02964 
02965 void ScribusDoc::restorePageCopy(SimpleState *state, bool isUndo)
02966 {
02967        int pnum = state->getInt("PAGE_NUM");
02968        int extPage = state->getInt("EXISTING_PAGE");
02969        int whereTo = state->getInt("WHERE_TO");
02970        int copyCount = state->getInt("COPY_COUNT");
02971 
02972        if (isUndo)
02973        {
02974               int destLocation=extPage+1;
02975               if (whereTo==0)
02976                      --destLocation;
02977               else if (whereTo==2)
02978                      destLocation=DocPages.count();
02979 
02980               for (int i = 0; i < copyCount; ++i)
02981               {
02982                      m_ScMW->DeletePage(destLocation, destLocation);
02983                      if (whereTo == 2)
02984                             --destLocation;
02985               }
02986        }
02987        else
02988               copyPage(pnum, extPage, whereTo, copyCount);
02989 
02990 }
02991 
02992 //TODO: Handle saving to versions of SLA, and other formats
02993 bool ScribusDoc::save(const QString& fileName)
02994 {
02995        QFileInfo fi(fileName);
02996        QDir::setCurrent(fi.dirPath(true));
02997        QProgressBar* mainWindowProgressBar=NULL;
02998        if (ScCore->usingGUI())
02999        {
03000               mainWindowProgressBar=m_ScMW->mainWindowProgressBar;
03001               mainWindowProgressBar->reset();
03002        }
03003        FileLoader fl(fileName);
03004        bool ret = fl.SaveFile(fileName, this, mainWindowProgressBar);
03005        if (ret)
03006        {
03007               setModified(false);
03008               setName(fileName);
03009               hasName = true;
03010        }
03011        return ret;
03012 }
03013 
03014 bool ScribusDoc::changePageMargins(const double initialTop, const double initialBottom, const double initialLeft, const double initialRight, const double initialHeight, const double initialWidth, const double height, const double width, const int orientation, const QString& pageSize, const int pageNumber, const int pageType)
03015 {
03016        bool retVal=true;
03017        if (pageNumber==-1)
03018        {
03019               //find page and set values
03020               return false;
03021        }
03022        else
03023        {
03024               if (currentPage()==NULL)
03025                      retVal=false;
03026               else
03027               {
03028                      //set the current page's values
03029                      currentPage()->initialMargins.Top = initialTop;
03030                      currentPage()->initialMargins.Bottom = initialBottom;
03031                      currentPage()->initialMargins.Left = initialLeft;
03032                      currentPage()->initialMargins.Right = initialRight;
03033                      currentPage()->setInitialHeight(initialHeight);
03034                      currentPage()->setInitialWidth(initialWidth);
03035                      currentPage()->setHeight(height);
03036                      currentPage()->setWidth(width);
03037                      currentPage()->PageOri = orientation;
03038                      currentPage()->m_pageSize = pageSize;
03039                      currentPage()->LeftPg = pageType;
03040                      changed();
03041               }
03042        }
03043        return retVal;
03044 }
03045 
03046 void ScribusDoc::recalculateColors()
03047 {
03048        //Adjust Items of the 3 types to the colors
03049        uint itemsCount=Items->count();
03050        updateAllItemQColors();
03051        for (uint c=0; c<itemsCount; ++c)
03052        {
03053               PageItem *ite = Items->at(c);
03054               QPtrVector<VColorStop> cstops = ite->fill_gradient.colorStops();
03055               for (uint cst = 0; cst < ite->fill_gradient.Stops(); ++cst)
03056                      ite->SetFarbe(&cstops.at(cst)->color, cstops.at(cst)->name, cstops.at(cst)->shade);
03057        }
03058        uint masterItemsCount=MasterItems.count();
03059        for (uint c=0; c<masterItemsCount; ++c)
03060        {
03061               PageItem *ite = MasterItems.at(c);
03062               QPtrVector<VColorStop> cstops = ite->fill_gradient.colorStops();
03063               for (uint cst = 0; cst < ite->fill_gradient.Stops(); ++cst)
03064                      ite->SetFarbe(&cstops.at(cst)->color, cstops.at(cst)->name, cstops.at(cst)->shade);
03065        }
03066        uint frameItemsCount=FrameItems.count();
03067        for (uint c=0; c<frameItemsCount; ++c)
03068        {
03069               PageItem *ite = FrameItems.at(c);
03070               QPtrVector<VColorStop> cstops = ite->fill_gradient.colorStops();
03071               for (uint cst = 0; cst < ite->fill_gradient.Stops(); ++cst)
03072                      ite->SetFarbe(&cstops.at(cst)->color, cstops.at(cst)->name, cstops.at(cst)->shade);
03073        }
03074        QStringList patterns = docPatterns.keys();
03075        for (uint c = 0; c < patterns.count(); ++c)
03076        {
03077               ScPattern pa = docPatterns[patterns[c]];
03078               for (uint o = 0; o < pa.items.count(); o++)
03079               {
03080                      PageItem *ite = pa.items.at(o);
03081                      QPtrVector<VColorStop> cstops = ite->fill_gradient.colorStops();
03082                      for (uint cst = 0; cst < ite->fill_gradient.Stops(); ++cst)
03083                             ite->SetFarbe(&cstops.at(cst)->color, cstops.at(cst)->name, cstops.at(cst)->shade);
03084                      if (ite->asImageFrame())
03085                             loadPict(ite->Pfile, ite, true, false);
03086               }
03087               PageItem *ite = pa.items.at(0);
03088               docPatterns[patterns[c]].pattern = ite->DrawObj_toImage(pa.items);
03089        }
03090 }
03091 
03092 void ScribusDoc::setScTextDefaultsFromDoc(ScText *sctextdata)
03093 {
03094        if (sctextdata==NULL)
03095               return;
03096 #ifndef NLS_PROTO
03097        reinterpret_cast<CharStyle&>(*sctextdata) = currentStyle.charStyle();
03098 //     sctextdata->cab = 0;
03099 #endif
03100 }
03101 
03102 const bool ScribusDoc::copyPageToMasterPage(const int pageNumber, const int leftPage, const int maxLeftPage,  const QString& masterPageName)
03103 {
03104        assert(!masterPageMode());
03105        if (masterPageMode())
03106               return false;
03107        int GrMax = GroupCounter;
03108        Page* sourcePage = Pages->at(pageNumber);
03109        int nr = MasterPages.count();
03110        Page* targetPage=addMasterPage(nr, masterPageName);
03111        assert(targetPage!=NULL);
03112        //Backup currentpage, and dont use sourcepage here as we might convert a non current page
03113        Page* oldCurrentPage = currentPage();
03114        //Must set current page for pasteitem to work properly
03115        setLoading(true);
03116        targetPage->copySizingProperties(sourcePage, sourcePage->Margins);
03117        //Grab the left page setting for the current document layout from the dialog, and increment, singlePage==1 remember.
03118        if (currentPageLayout != singlePage)
03119        {
03120               int lp = leftPage;
03121               if (lp == 0)
03122                      lp = 1;
03123               else if (lp == maxLeftPage-1)
03124                      lp = 0;
03125               else
03126                      ++lp;
03127               targetPage->LeftPg = lp;
03128        }
03129        sourcePage->guides.copy(&targetPage->guides);
03130        uint end = DocItems.count();
03131        uint end2 = MasterItems.count();
03132        m_Selection->clear();
03133        QValueList<Layer>::iterator it;
03134        if (Layers.count()!= 0)
03135        {
03136               int currActiveLayer = activeLayer();
03137               for (it = Layers.begin(); it != Layers.end(); ++it)
03138               {
03139                      setActiveLayer((*it).LNr);
03140                      for (uint ite = 0; ite < end; ++ite)
03141                      {
03142                             PageItem *itemToCopy = DocItems.at(ite);
03143                             if ((itemToCopy->OwnPage == static_cast<int>(sourcePage->pageNr())) && ((*it).LNr == itemToCopy->LayerNr))
03144                                    m_Selection->addItem(itemToCopy, true);
03145                      }
03146                      if (m_Selection->count() != 0)
03147                      {
03148                             ScriXmlDoc *ss = new ScriXmlDoc();
03149                             QString dataS = ss->WriteElem(this, view(), m_Selection);
03150                             setMasterPageMode(true);
03151                             setCurrentPage(targetPage);
03152                             ss->ReadElem(dataS, prefsData.AvailFonts, this, targetPage->xOffset(), targetPage->yOffset(), false, true, prefsData.GFontSub, view());
03153                             delete ss;
03154                      }
03155                      m_Selection->clear();
03156               }
03157               setActiveLayer(currActiveLayer);
03158        }
03159        uint end3 = MasterItems.count();
03160        for (uint a = end2; a < end3; ++a)
03161        {
03162               PageItem *newItem = MasterItems.at(a);
03163               newItem->OnMasterPage = masterPageName;
03164               newItem->OwnPage = MasterNames[masterPageName];
03165        }
03166        targetPage->MPageNam = "";
03167        setLoading(false);
03168        GroupCounter = GrMax + 1;
03169        //Reset the current page..
03170        setMasterPageMode(false);
03171        setCurrentPage(oldCurrentPage);
03172        changed();
03173        return true;
03174 }
03175 
03176 int ScribusDoc::itemAdd(const PageItem::ItemType itemType, const PageItem::ItemFrameType frameType, const double x, const double y, const double b, const double h, const double w, const QString& fill, const QString& outline, const bool itemFinalised)
03177 {
03178        if (UndoManager::undoEnabled() && !_itemCreationTransactionStarted)
03179        {
03180               _itemCreationTransactionStarted = true;
03181               undoManager->beginTransaction();
03182        }
03183        PageItem* newItem=NULL;
03184        switch( itemType )
03185        {
03186               //Q_ASSERTs here will warn on creation issues when a coder specifies the frameType incorrectly
03187               //for items that do not have/need a frameType for creation.
03188               case PageItem::ImageFrame:
03189                      newItem = new PageItem_ImageFrame(this, x, y, b, h, 1, toolSettings.dBrushPict, CommonStrings::None);
03190                      Q_ASSERT(frameType==PageItem::Rectangle || frameType==PageItem::Unspecified);
03191                      break;
03192               case PageItem::TextFrame:
03193                      newItem = new PageItem_TextFrame(this, x, y, b, h, w, CommonStrings::None, outline);
03194                      Q_ASSERT(frameType==PageItem::Rectangle || frameType==PageItem::Unspecified);
03195                      break;
03196               case PageItem::Line:
03197                      {
03198                             //CB 5521 remove false minimum for line width
03199                             double lineWidth = w; // == 0.0 ? 1.0 : w;
03200                             newItem = new PageItem_Line(this, x, y, b, h, lineWidth, CommonStrings::None, outline);
03201                             Q_ASSERT(frameType==PageItem::Unspecified);
03202                      }
03203                      break;
03204               case PageItem::Polygon:
03205                      newItem = new PageItem_Polygon(this, x, y, b, h, w, fill, outline);
03206                      Q_ASSERT(frameType==PageItem::Rectangle || frameType==PageItem::Ellipse || frameType==PageItem::Unspecified);
03207                      break;
03208               case PageItem::PolyLine:
03209                      newItem = new PageItem_PolyLine(this, x, y, b, h, w, fill, outline);
03210                      Q_ASSERT(frameType==PageItem::Unspecified);
03211                      break;
03212               case PageItem::PathText:
03213                      //Currently used only in fileloader
03214                      newItem = new PageItem_PathText(this, x, y, b, h, w, fill, outline);
03215                      Q_ASSERT(frameType==PageItem::Unspecified);
03216                      break;
03217               default:
03218                      qDebug("unknown item type");
03219                      break;
03220        }
03221        Q_CHECK_PTR(newItem);
03222        if (newItem==NULL)
03223               return -1;
03224        Items->append(newItem);
03225        newItem->ItemNr = Items->count()-1;
03226        //Add in item default values based on itemType and frameType
03227        itemAddDetails(itemType, frameType, newItem->ItemNr);
03228        if (UndoManager::undoEnabled())
03229        {
03230               ItemState<PageItem*> *is = new ItemState<PageItem*>("Create PageItem");
03231               is->set("CREATE_ITEM", "create_item");
03232               is->setItem(newItem);
03233               //Undo target rests with the Page for object specific undo
03234               UndoObject *target = Pages->at(0);
03235               if (newItem->OwnPage > -1)
03236                      target = Pages->at(newItem->OwnPage);
03237               undoManager->action(target, is);
03238               //If the item is created "complete" (ie, not being created by drag/resize, commit to undomanager)
03239               if (itemFinalised)
03240               {
03241                      //dont think we need this now ... newItem->checkChanges(true);
03242                      undoManager->commit(Pages->at(newItem->OwnPage)->getUName(), newItem->getUPixmap(),
03243                                                         Um::Create + " " + newItem->getUName(),  "", Um::ICreate);
03244                      _itemCreationTransactionStarted = false;
03245               }
03246        }
03247        return newItem->ItemNr;
03248 }
03249 
03250 int ScribusDoc::itemAddArea(const PageItem::ItemType itemType, const PageItem::ItemFrameType frameType, const double x, const double y, const double w, const QString& fill, const QString& outline, const bool itemFinalised)
03251 {
03252        double xo = _currentPage->xOffset();
03253        double yo = _currentPage->yOffset();
03254        QPair<double, double> tl = _currentPage->guides.topLeft(x - xo, y - yo);
03255        QPair<double, double> tr = _currentPage->guides.topRight(x - xo, y - yo);
03256        QPair<double, double> bl = _currentPage->guides.bottomLeft(x - xo, y - yo);
03257        return itemAdd(itemType, frameType, tl.first + xo, tl.second + yo, tr.first - tl.first, bl.second - tl.second, w, fill, outline, itemFinalised);
03258 }
03259 
03260 
03261 int ScribusDoc::itemAddUserFrame(InsertAFrameData &iafData)
03262 {
03263        double x1=0.0,y1=0.0,w1=iafData.width,h1=iafData.height;
03264        std::vector<int> pageNs;
03265        if (iafData.locationType==0) // On the current page or ona range of pages
03266               pageNs.push_back(currentPage()->pageNr()+1);
03267        else if (iafData.locationType==2) // On all pages
03268        {
03269               parsePagesString(QString("1-%1").arg(DocPages.count()), &pageNs, DocPages.count());
03270        }
03271        else
03272               parsePagesString(iafData.pageList, &pageNs, DocPages.count());
03273        Page* oldCurrentPage = currentPage();
03274        int z=-2;
03275        PageItem *prevItem=0; //Previous item for text frame linking
03276 
03277        undoManager->beginTransaction(
03278                      iafData.frameType==PageItem::TextFrame ? Um::TextFrame : Um::ImageFrame,
03279                      iafData.frameType==PageItem::TextFrame ? Um::ITextFrame : Um::IImageFrame,
03280                      Um::InsertFrame, "", Um::ICreate);
03281 
03282        for (uint i=0;i<pageNs.size();++i)
03283        {
03284               Page* targetPage=Pages->at(pageNs[i]-1);
03285               //We need this for the itemAdd, FIXME later
03286               setCurrentPage(targetPage);
03287               
03288               if (iafData.positionType==0) // Frame starts at top left of page margins
03289               {
03290                      x1=targetPage->xOffset()+targetPage->Margins.Left;
03291                      y1=targetPage->yOffset()+targetPage->Margins.Top;
03292               }
03293               else if (iafData.positionType==1) // Frame starts at top left of page
03294               {
03295                      x1=targetPage->xOffset();
03296                      y1=targetPage->yOffset();
03297               }
03298               else
03299               if (iafData.positionType==2) // Frame starts at top left of page - bleeds
03300               {
03301                      x1=targetPage->xOffset()-bleeds.Left;
03302                      y1=targetPage->yOffset()-bleeds.Top;
03303               }
03304               else if (iafData.positionType==99) // Frame starts at custom position
03305               {
03306                      x1=targetPage->xOffset()+iafData.x/docUnitRatio;
03307                      y1=targetPage->yOffset()+iafData.y/docUnitRatio;
03308               }
03309               
03310 
03311               if (iafData.sizeType==0) // Frame is size of page margins
03312               {
03313                      w1=targetPage->width()-targetPage->Margins.Right-targetPage->Margins.Left;
03314                      h1=targetPage->height()-targetPage->Margins.Bottom-targetPage->Margins.Top;
03315               }
03316               else if (iafData.sizeType==1) // Frame is size of page
03317               {
03318                      w1=targetPage->width();
03319                      h1=targetPage->height();
03320               }
03321               else
03322               if (iafData.sizeType==2) // Frame is size of page + bleed 
03323               {
03324                      w1=targetPage->width()+bleeds.Right+bleeds.Left;
03325                      h1=targetPage->height()+bleeds.Bottom+bleeds.Top;
03326               }
03327               else if (iafData.sizeType==3) //Frame is size of imported image, we resize below when we load it
03328               {
03329                      w1=h1=1;
03330               }
03331               else if (iafData.sizeType==99) // Frame is custom size
03332               {
03333                      w1=iafData.width/docUnitRatio;
03334                      h1=iafData.height/docUnitRatio;
03335               }
03336               z=itemAdd(iafData.frameType, PageItem::Unspecified, x1, y1, w1, h1, toolSettings.dWidth, CommonStrings::None, toolSettings.dPenText, true);
03337               if (z!=-1)
03338               {
03339                      PageItem* currItem=Items->at(z);
03340                      setRedrawBounding(currItem);
03341                      if (iafData.frameType==PageItem::ImageFrame && !iafData.source.isEmpty())
03342                      {
03343                             if (QFile::exists(iafData.source))
03344                             {
03345                                    PrefsManager::instance()->prefsFile->getContext("dirs")->set("images", iafData.source.left(iafData.source.findRev("/")));
03346                                    currItem->EmProfile = "";
03347                                    currItem->pixm.imgInfo.isRequest = false;
03348                                    currItem->UseEmbedded = true;
03349                                    currItem->IProfile = CMSSettings.DefaultImageRGBProfile;
03350                                    currItem->IRender = CMSSettings.DefaultIntentImages;
03351                                    qApp->setOverrideCursor( QCursor(Qt::WaitCursor) );
03352                                    qApp->eventLoop()->processEvents(QEventLoop::ExcludeUserInput);
03353                                    loadPict(iafData.source, currItem, false, true);
03354                                    if (iafData.sizeType==3) //Frame is size of imported image
03355                                    {
03356                                           currItem->setWidth(static_cast<double>(currItem->OrigW * 72.0 / currItem->pixm.imgInfo.xres));
03357                                           currItem->setHeight(static_cast<double>(currItem->OrigH * 72.0 / currItem->pixm.imgInfo.yres));
03358                                           currItem->OldB2 = currItem->width();
03359                                           currItem->OldH2 = currItem->height();
03360                                           currItem->updateClip();
03361                                    }
03362                                    qApp->eventLoop()->processEvents(QEventLoop::ExcludeUserInput);
03363                                    qApp->restoreOverrideCursor();
03364                             }
03365                      }
03366                      if (iafData.frameType==PageItem::TextFrame)
03367                      {
03368                             currItem->setColumns(iafData.columnCount);
03369                             currItem->setColumnGap(iafData.columnGap/docUnitRatio);
03370                             if (iafData.linkTextFrames && prevItem != NULL )
03371                             {
03372                                    prevItem->link(currItem);
03373                             }
03374                             if (!iafData.source.isEmpty() && prevItem == NULL && QFile::exists(iafData.source))
03375                             {
03376                                    gtGetText* gt = new gtGetText(this);
03377                                    if (iafData.impsetup.runDialog)
03378                                           gt->launchImporter(iafData.impsetup.importer, iafData.impsetup.filename, iafData.impsetup.textOnly, iafData.impsetup.encoding, true, currItem);
03379                                    delete gt;
03380                             }
03381                             prevItem=currItem;
03382                      }
03383               }
03384        }
03385 
03386        undoManager->commit();
03387        setCurrentPage(oldCurrentPage);
03388        changed();
03389        emit updateContents();
03390        return z;
03391 }
03392 
03393 void ScribusDoc::itemAddDetails(const PageItem::ItemType itemType, const PageItem::ItemFrameType frameType, const int itemNumber)
03394 {
03395        PageItem* newItem=Items->at(itemNumber);
03396        Q_ASSERT(newItem->itemType()==itemType);
03397        switch( itemType )
03398        {
03399               case PageItem::ImageFrame:
03400                      newItem->setFillShade(toolSettings.shadePict);
03401                      newItem->setImageXYScale(toolSettings.scaleX, toolSettings.scaleY);
03402                      newItem->ScaleType = toolSettings.scaleType;
03403                      newItem->AspectRatio = toolSettings.aspectRatio;
03404                      newItem->IProfile = CMSSettings.DefaultImageRGBProfile;
03405                      newItem->IRender = CMSSettings.DefaultIntentImages;
03406                      break;
03407               case PageItem::TextFrame:
03408 //                   newItem->setFontFillShade(toolSettings.dTextPenShade);
03409 //                   newItem->setFontStrokeShade(toolSettings.dTextStrokeShade);
03410                      newItem->setFillColor(toolSettings.dTextBackGround);
03411                      newItem->setFillShade(toolSettings.dTextBackGroundShade);
03412                      newItem->setLineColor(toolSettings.dTextLineColor);
03413                      newItem->setLineShade(toolSettings.dTextLineShade);
03414                      break;
03415               case PageItem::Line:
03416                      newItem->PLineArt = Qt::PenStyle(toolSettings.dLstyleLine);
03417                      newItem->setLineShade(toolSettings.dShadeLine);
03418                      break;
03419               case PageItem::Polygon:
03420                      if(frameType!=PageItem::Rectangle && frameType!=PageItem::Ellipse)
03421                      {
03422                             newItem->ClipEdited = true;
03423                             newItem->FrameType = 3;
03424                      }
03425                      break;
03426               case PageItem::PolyLine:
03427                      newItem->ClipEdited = true;
03428                      break;
03429               case PageItem::PathText:
03430               //At this point, we cannot create a PathText item like this, only by conversion, do nothing
03431                      break;
03432               default:
03433                      break;
03434        }
03435 
03436        if (frameType==PageItem::Rectangle || itemType==PageItem::TextFrame || itemType==PageItem::ImageFrame)
03437        {
03438               newItem->SetRectFrame();
03439               //TODO one day hopefully, if(ScCore->usingGUI())
03440               newItem->setRedrawBounding();
03441               //m_View->setRedrawBounding(newItem);
03442               newItem->ContourLine = newItem->PoLine.copy();
03443        }
03444 
03445        if (frameType==PageItem::Ellipse)
03446        {
03447               newItem->SetOvalFrame();
03448               //TODO one day hopefully, if(ScCore->usingGUI())
03449               newItem->setRedrawBounding();
03450               //m_View->setRedrawBounding(newItem);
03451               newItem->ContourLine = newItem->PoLine.copy();
03452        }
03453 
03454        //ItemType Polygon
03455        if (itemType==PageItem::Polygon || itemType==PageItem::PolyLine)
03456        {
03457               newItem->PLineArt = Qt::PenStyle(toolSettings.dLineArt);
03458               newItem->setFillShade(toolSettings.dShade);
03459               newItem->setLineShade(toolSettings.dShade2);
03460        }
03461 }
03462 
03463 
03464 bool ScribusDoc::itemAddCommit(const int /*itemNumber*/)
03465 {
03466        //TODO use the parameter
03467        if (_itemCreationTransactionStarted && appMode !=  modeDrawBezierLine)
03468        {
03469               PageItem *createdItem=m_Selection->itemAt(0);
03470               if (createdItem!=NULL)
03471               {
03472                      createdItem->checkChanges(true);
03473                      QString targetName = Um::ScratchSpace;
03474                      if (createdItem->OwnPage > -1)
03475                             targetName = Pages->at(createdItem->OwnPage)->getUName();
03476                      undoManager->commit(targetName, createdItem->getUPixmap(),
03477                                                         Um::Create + " " + createdItem->getUName(),  "", Um::ICreate);
03478                      _itemCreationTransactionStarted = false;
03479                      if (!isLoading())
03480                             return true;
03481               }
03482        }
03483        return false;
03484 }
03485 
03486 uint ScribusDoc::getItemNrfromUniqueID(uint unique)
03487 {
03488        uint ret = 0;
03489        for (uint a = 0; a < Items->count(); ++a)
03490        {
03491               if (Items->at(a)->uniqueNr == unique)
03492               {
03493                      ret = Items->at(a)->ItemNr;
03494                      break;
03495               }
03496        }
03497        return ret;
03498 }
03499 
03500 void ScribusDoc::updateFrameItems()
03501 {
03502        uint frameItemsCount=FrameItems.count();
03503        for (uint a = 0; a < frameItemsCount; ++a)
03504               FrameItems.at(a)->ItemNr = a;
03505 }
03506 
03507 void ScribusDoc::renumberItemsInListOrder( )
03508 {
03509        uint itemsCount=Items->count();
03510        for (uint i = 0; i < itemsCount; ++i)
03511               Items->at(i)->ItemNr = i;
03512 }
03513 
03514 bool ScribusDoc::usesAutomaticTextFrames() const
03515 {
03516        return automaticTextFrames;
03517 }
03518 
03519 void ScribusDoc::setUsesAutomaticTextFrames(const bool atf)
03520 {
03521        automaticTextFrames=atf;
03522 }
03523 
03524 bool ScribusDoc::LoadPict(QString fn, int ItNr, bool reload, bool showMsg )
03525 {
03526        return loadPict(fn, Items->at(ItNr), reload, showMsg);
03527 }
03528 
03529 bool ScribusDoc::loadPict(QString fn, PageItem *pageItem, bool reload, bool showMsg)
03530 {
03531        if (!reload)
03532        {
03533               if ((ScCore->fileWatcher->files().contains(pageItem->Pfile) != 0) && (pageItem->PicAvail))
03534                      ScCore->fileWatcher->removeFile(pageItem->Pfile);
03535        }
03536        if(!pageItem->loadImage(fn, reload, -1, showMsg))
03537               return false;
03538        if (!reload)
03539               ScCore->fileWatcher->addFile(pageItem->Pfile);
03540        if (!isLoading())
03541        {
03542               //TODO: Make this a signal again one day
03543               //emit RasterPic(pageItem->isRaster);
03544               m_ScMW->HaveRaster(pageItem->isRaster);
03545               //TODO: Previously commented out.. unsure why, remove later
03546               //emit UpdtObj(PageNr, ItNr);
03547               //CB: probably because we are therefore not always refreshing the view when an image changes...
03548               emit refreshItem(pageItem);
03549               changed();
03550        }
03551        return true;
03552 }
03553 
03554 void ScribusDoc::canvasMinMax(FPoint& minPoint, FPoint& maxPoint)
03555 {
03556        PageItem *currItem;
03557        double minx = 99999.9;
03558        double miny = 99999.9;
03559        double maxx = -99999.9;
03560        double maxy = -99999.9;
03561        uint docItemsCount=Items->count();
03562        for (uint ic = 0; ic < docItemsCount; ++ic)
03563        {
03564               currItem = Items->at(ic);
03565               if (currItem->rotation() != 0)
03566               {
03567                      FPointArray pb;
03568                      pb.resize(0);
03569                      pb.addPoint(FPoint(currItem->xPos(), currItem->yPos()));
03570                      FPoint p1(currItem->width(), 0.0, currItem->xPos(), currItem->yPos(), currItem->rotation(), 1.0, 1.0);
03571                      pb.addPoint(p1);
03572                      FPoint p2(currItem->width(), currItem->height(), currItem->xPos(), currItem->yPos(), currItem->rotation(), 1.0, 1.0);
03573                      pb.addPoint(p2);
03574                      FPoint p3(0.0, currItem->height(), currItem->xPos(), currItem->yPos(), currItem->rotation(), 1.0, 1.0);
03575                      pb.addPoint(p3);
03576                      for (uint pc = 0; pc < 4; ++pc)
03577                      {
03578                             minx = QMIN(minx, pb.point(pc).x());
03579                             miny = QMIN(miny, pb.point(pc).y());
03580                             maxx = QMAX(maxx, pb.point(pc).x());
03581                             maxy = QMAX(maxy, pb.point(pc).y());
03582                      }
03583               }
03584               else
03585               {
03586                      minx = QMIN(minx, currItem->xPos());
03587                      miny = QMIN(miny, currItem->yPos());
03588                      maxx = QMAX(maxx, currItem->xPos() + currItem->width());
03589                      maxy = QMAX(maxy, currItem->yPos() + currItem->height());
03590               }
03591        }
03592        minPoint.setX(minx);
03593        minPoint.setY(miny);
03594        maxPoint.setX(maxx);
03595        maxPoint.setY(maxy);
03596 }
03597 
03598 int ScribusDoc::OnPage(double x2, double  y2)
03599 {
03600        int retw = -1;
03601        if (masterPageMode())
03602        {
03603               int x = static_cast<int>(currentPage()->xOffset());
03604               int y = static_cast<int>(currentPage()->yOffset());
03605               int w = static_cast<int>(currentPage()->width());
03606               int h = static_cast<int>(currentPage()->height());
03607               if (QRect(x, y, w, h).contains(qRound(x2), qRound(y2)))
03608                      retw = currentPage()->pageNr();
03609        }
03610        else
03611        {
03612               uint docPageCount = Pages->count();
03613               for (uint a = 0; a < docPageCount; ++a)
03614               {
03615                      int x = static_cast<int>(Pages->at(a)->xOffset());
03616                      int y = static_cast<int>(Pages->at(a)->yOffset());
03617                      int w = static_cast<int>(Pages->at(a)->width());
03618                      int h = static_cast<int>(Pages->at(a)->height());
03619                      if (QRect(x, y, w, h).contains(qRound(x2), qRound(y2)))
03620                      {
03621                             retw = static_cast<int>(a);
03622                             break;
03623                      }
03624               }
03625        }
03626        return retw;
03627 }
03628 
03629 int ScribusDoc::OnPage(PageItem *currItem)
03630 {
03631        int retw = -1;
03632        if (masterPageMode())
03633        {
03634 /*            int x = static_cast<int>(currentPage()->xOffset());
03635               int y = static_cast<int>(currentPage()->yOffset());
03636               int w = static_cast<int>(currentPage()->width());
03637               int h = static_cast<int>(currentPage()->height());
03638               QRect itemRect(qRound(currItem->BoundingX), qRound(currItem->BoundingY), qRound(currItem->BoundingW), qRound(currItem->BoundingH));
03639               if (QRect(x, y, w, h).intersects(itemRect)) */
03640               double x = currentPage()->xOffset();
03641               double y = currentPage()->yOffset();
03642               double w = currentPage()->width();
03643               double h1 = currentPage()->height();
03644               double x2 = currItem->BoundingX;
03645               double y2 = currItem->BoundingY;
03646               double w2 = currItem->BoundingW;
03647               double h2 = currItem->BoundingH;
03648               if (( QMAX( x, x2 ) <= QMIN( x+w, x2+w2 ) && QMAX( y, y2 ) <= QMIN( y+h1, y2+h2 )))
03649                      retw = currentPage()->pageNr();
03650        }
03651        else
03652        {
03653               uint docPageCount = Pages->count();
03654               for (uint a = 0; a < docPageCount; ++a)
03655               {
03656                      double x = Pages->at(a)->xOffset();
03657                      double y = Pages->at(a)->yOffset();
03658                      double w = Pages->at(a)->width();
03659                      double h1 = Pages->at(a)->height();
03660                      double x2 = currItem->BoundingX;
03661                      double y2 = currItem->BoundingY;
03662                      double w2 = currItem->BoundingW;
03663                      double h2 = currItem->BoundingH;
03664                      if (( QMAX( x, x2 ) <= QMIN( x+w, x2+w2 ) && QMAX( y, y2 ) <= QMIN( y+h1, y2+h2 )))
03665                      {
03666                             retw = static_cast<int>(a);
03667                             break;
03668                      }
03669 /*                   int x = static_cast<int>(Pages->at(a)->xOffset());
03670                      int y = static_cast<int>(Pages->at(a)->yOffset());
03671                      int w = static_cast<int>(Pages->at(a)->width());
03672                      int h = static_cast<int>(Pages->at(a)->height());
03673                      QRect itemRect(qRound(currItem->BoundingX), qRound(currItem->BoundingY), qRound(currItem->BoundingW), qRound(currItem->BoundingH));
03674                      if (QRect(x, y, w, h).intersects(itemRect))
03675                      {
03676                             retw = static_cast<int>(a);
03677                             break;
03678                      } */
03679               }
03680        }
03681        if ((retw == -1) && (currItem->isBookmark))
03682        {
03683               //FIXME emit DelBM(currItem);
03684               currItem->isBookmark = false;
03685        }
03686        return retw;
03687 }
03688 
03689 void ScribusDoc::GroupOnPage(PageItem* currItem)
03690 {
03691        QPtrList<PageItem> Objects;
03692        PageItem* item;
03693        if (currItem->Groups.count() == 0)
03694               return;
03695        int ObjGroup = currItem->Groups.top();
03696        uint docItemCount=Items->count();
03697        for (uint a = 0; a < docItemCount; ++a)
03698        {
03699               item = Items->at(a);
03700               if (item->Groups.count() != 0)
03701               {
03702                      if (item->Groups.top() == ObjGroup)
03703                             Objects.append(item);
03704               }
03705        }
03706        int Off_Page = -1;
03707        int On_Page = 999999;
03708        uint objectCount=Objects.count();
03709        for (uint a = 0; a < objectCount; ++a)
03710        {
03711               int res = OnPage(Objects.at(a));
03712               Off_Page = QMAX(Off_Page, res);
03713               if (res != -1)
03714                      On_Page = QMIN(On_Page, res);
03715        }
03716        int final = -1;
03717        if (Off_Page != -1)
03718               final = On_Page;
03719        for (uint a = 0; a < objectCount; ++a)
03720        {
03721               Objects.at(a)->OwnPage = final;
03722        }
03723 }
03724 
03725 //CB TODO make a function to determine the place of the page.. ie, so we know the left and right margins
03726 // without running this monster
03727 void ScribusDoc::reformPages(bool moveObjects)
03728 {
03729        QMap<uint, ScribusView::oldPageVar> pageTable;
03730        struct ScribusView::oldPageVar oldPg;
03731        int counter = pageSets[currentPageLayout].FirstPage;
03732        int rowcounter = 0;
03733        double maxYPos=0.0, maxXPos=0.0;
03734        double currentXPos=scratch.Left, currentYPos=scratch.Top, lastYPos=Pages->at(0)->initialHeight();
03735        currentXPos += (pageWidth+pageSets[currentPageLayout].GapHorizontal) * counter;
03736 
03737        lastYPos = Pages->at(0)->initialHeight();
03738        Page* Seite;
03739        uint docPageCount=Pages->count();
03740        for (uint a = 0; a < docPageCount; ++a)
03741        {
03742               Seite = Pages->at(a);
03743               oldPg.oldXO = Seite->xOffset();
03744               oldPg.oldYO = Seite->yOffset();
03745               oldPg.newPg = a;
03746               pageTable.insert(Seite->pageNr(), oldPg);
03747               Seite->setPageNr(a);
03748               if (masterPageMode())
03749               {
03750                      Seite->setXOffset(scratch.Left);
03751                      Seite->setYOffset(scratch.Top);
03752                      if (Seite->LeftPg == 0)
03753                      {
03754                             Seite->Margins.Right = Seite->initialMargins.Right;
03755                             Seite->Margins.Left = Seite->initialMargins.Left;
03756                      }
03757                      else if ((Seite->LeftPg > 1) && (Seite->LeftPg < pageSets[currentPageLayout].Columns))
03758                      {
03759                             Seite->Margins.Left = Seite->initialMargins.Left;
03760                             Seite->Margins.Right = Seite->initialMargins.Left;
03761                      }
03762                      else
03763                      {
03764                             Seite->Margins.Left = Seite->initialMargins.Right;
03765                             Seite->Margins.Right = Seite->initialMargins.Left;
03766                      }
03767               }
03768               else
03769               {
03770                      Seite->setWidth(Seite->initialWidth());
03771                      Seite->setHeight(Seite->initialHeight());
03772                      Seite->setXOffset(currentXPos);
03773                      Seite->setYOffset(currentYPos);
03774                      if (counter < pageSets[currentPageLayout].Columns-1)
03775                      {
03776                             currentXPos += Seite->width() + pageSets[currentPageLayout].GapHorizontal;
03777                             lastYPos = QMAX(lastYPos, Seite->height());
03778                             if (counter == 0)
03779                             {
03780                                    Seite->Margins.Left = Seite->initialMargins.Right;
03781                                    Seite->Margins.Right = Seite->initialMargins.Left;
03782                             }
03783                             else
03784                             {
03785                                    Seite->Margins.Left = Seite->initialMargins.Left;
03786                                    Seite->Margins.Right = Seite->initialMargins.Left;
03787                             }
03788                      }
03789                      else
03790                      {
03791                             currentXPos = scratch.Left;
03792                             if (pageSets[currentPageLayout].Columns > 1)
03793                                    currentYPos += QMAX(lastYPos, Seite->height())+pageSets[currentPageLayout].GapVertical;
03794                             else
03795                                    currentYPos += Seite->height()+pageSets[currentPageLayout].GapVertical;
03796 //                          lastYPos = QMAX(lastYPos, Seite->height());
03797                             lastYPos = 0;
03798                             Seite->Margins.Right = Seite->initialMargins.Right;
03799                             Seite->Margins.Left = Seite->initialMargins.Left;
03800                      }
03801                      counter++;
03802                      if (counter > pageSets[currentPageLayout].Columns-1)
03803                      {
03804                             counter = 0;
03805                             rowcounter++;
03806                             if (rowcounter > pageSets[currentPageLayout].Rows-1)
03807                             {
03808                                    currentYPos += pageSets[currentPageLayout].GapBelow;
03809                                    rowcounter = 0;
03810                             }
03811                      }
03812               }
03813               Seite->Margins.Top = Seite->initialMargins.Top;
03814               Seite->Margins.Bottom = Seite->initialMargins.Bottom;
03815               maxXPos = QMAX(maxXPos, Seite->xOffset()+Seite->width()+scratch.Right);
03816               maxYPos = QMAX(maxYPos, Seite->yOffset()+Seite->height()+scratch.Bottom);
03817        }
03818        if (!isLoading())
03819        {
03820               uint docItemsCount=Items->count();
03821               for (uint ite = 0; ite < docItemsCount; ++ite)
03822               {
03823                      PageItem *item = Items->at(ite);
03824                      if (item->OwnPage < 0)
03825                      {
03826                             if (item->Groups.count() != 0)
03827                                    GroupOnPage(item);
03828                             else
03829                                    item->OwnPage = OnPage(item);
03830                      }
03831                      else
03832                      {
03833                             if (moveObjects)
03834                             {
03835                                    oldPg = pageTable[item->OwnPage];
03836                                    item->moveBy(-oldPg.oldXO + Pages->at(oldPg.newPg)->xOffset(), -oldPg.oldYO + Pages->at(oldPg.newPg)->yOffset());
03837                                    item->OwnPage = static_cast<int>(oldPg.newPg);
03838                             }
03839                             else
03840                             {
03841                                    if (item->Groups.count() != 0)
03842                                           GroupOnPage(item);
03843                                    else
03844                                           item->OwnPage = OnPage(item);
03845                             }
03846                      }
03847                      item->setRedrawBounding();
03848               }
03849        }
03850 
03851        if(isLoading() && is12doc)
03852               return;
03853        if (!isLoading())
03854        {
03855               FPoint minPoint, maxPoint;
03856               canvasMinMax(minPoint, maxPoint);
03857               FPoint maxSize(QMAX(maxXPos, maxPoint.x()+scratch.Right), QMAX(maxYPos, maxPoint.y()+scratch.Bottom));
03858               adjustCanvas(FPoint(QMIN(0, minPoint.x()-scratch.Left),QMIN(0, minPoint.y()-scratch.Top)), maxSize, true);
03859               changed();
03860        }
03861        else
03862        {
03863               FPoint maxSize(maxXPos, maxYPos);
03864               adjustCanvas(FPoint(0, 0), maxSize);
03865        }
03866 }
03867 
03868 const double ScribusDoc::getXOffsetForPage(const int pageNumber)
03869 {
03870        if (Pages->at(pageNumber)!=NULL)
03871               return Pages->at(pageNumber)->xOffset();
03872        return -1.0;
03873 }
03874 
03875 const double ScribusDoc::getYOffsetForPage(const int pageNumber)
03876 {
03877        if (Pages->at(pageNumber)!=NULL)
03878               return Pages->at(pageNumber)->yOffset();
03879        return -1.0;
03880 }
03881 
03882 void ScribusDoc::getBleeds(int pageNumber, double *bleedTop, double *bleedBottom, double *bleedLeft, double *bleedRight)
03883 {
03884        *bleedBottom = bleeds.Bottom;
03885        *bleedTop = bleeds.Top;
03886        if (pageSets[currentPageLayout].Columns == 1)
03887        {
03888               *bleedRight = bleeds.Right;
03889               *bleedLeft = bleeds.Left;
03890        }
03891        else
03892        {
03893               if (locationOfPage(Pages->at(pageNumber)->pageNr()) == LeftPage)
03894               {
03895                      *bleedRight = bleeds.Left;
03896                      *bleedLeft = bleeds.Right;
03897               }
03898               else if (locationOfPage(Pages->at(pageNumber)->pageNr()) == RightPage)
03899               {
03900                      *bleedRight = bleeds.Right;
03901                      *bleedLeft = bleeds.Left;
03902               }
03903               else
03904               {
03905                      *bleedRight = bleeds.Left;
03906                      *bleedLeft = bleeds.Left;
03907               }
03908        }
03909 }
03910 
03911 void ScribusDoc::getBleeds(Page* page, double *bleedTop, double *bleedBottom, double *bleedLeft, double *bleedRight)
03912 {
03913        *bleedBottom = bleeds.Bottom;
03914        *bleedTop = bleeds.Top;
03915        if (pageSets[currentPageLayout].Columns == 1)
03916        {
03917               *bleedRight = bleeds.Right;
03918               *bleedLeft = bleeds.Left;
03919        }
03920        else
03921        {
03922               if (locationOfPage(page->pageNr()) == LeftPage)
03923               {
03924                      *bleedRight = bleeds.Left;
03925                      *bleedLeft = bleeds.Right;
03926               }
03927               else if (locationOfPage(page->pageNr()) == RightPage)
03928               {
03929                      *bleedRight = bleeds.Right;
03930                      *bleedLeft = bleeds.Left;
03931               }
03932               else
03933               {
03934                      *bleedRight = bleeds.Left;
03935                      *bleedLeft = bleeds.Left;
03936               }
03937        }
03938 }
03939 
03940 PageItem* ScribusDoc::convertItemTo(PageItem *currItem, PageItem::ItemType newType, PageItem* secondaryItem)
03941 {
03942        //Item to convert is null, return
03943        Q_ASSERT(currItem!=NULL);
03944        if (currItem==NULL)
03945               return false;
03946        //Dont attempt a Line conversion
03947        if (currItem->itemType()==PageItem::Line || newType==PageItem::Line)
03948               return false;
03949        //Take the item to convert from the docs Items list
03950 //     PageItem *oldItem = Items->take(currItem->ItemNr);
03951        // Don't use take as we will insert the new item later at the same position
03952        PageItem *oldItem = Items->at(currItem->ItemNr);
03953        uint oldItemNr = currItem->ItemNr;
03954        //Remove old item from the doc's selection if it was in it
03955        bool removedFromSelection=m_Selection->removeItem(oldItem);
03956        //Create a new item from the old one
03957        bool transactionConversion=false;
03958        PageItem *newItem;
03959        switch (newType)
03960        {
03961               case PageItem::ImageFrame:
03962                      newItem = new PageItem_ImageFrame(*oldItem);
03963                      break;
03964               case PageItem::TextFrame:
03965                      newItem = new PageItem_TextFrame(*oldItem);
03966                      if (UndoManager::undoEnabled() && oldItem->itemType()==PageItem::PathText)
03967                      {
03968                             undoManager->beginTransaction(currentPage()->getUName(), 0, Um::TextFrame, "", Um::ITextFrame);
03969                             transactionConversion=true;
03970                      }
03971                      break;
03972               //We dont allow this
03973               //case PageItem::Line:
03974               //     newItem = new PageItem_Line(*oldItem);
03975               //     break;
03976               case PageItem::Polygon:
03977                      newItem = new PageItem_Polygon(*oldItem);
03978                      break;
03979               case PageItem::PolyLine:
03980                      newItem = new PageItem_PolyLine(*oldItem);
03981                      break;
03982               case PageItem::PathText:
03983                      if (secondaryItem==NULL)
03984                             return false;
03985                      if (UndoManager::undoEnabled())
03986                      {
03987                             undoManager->beginTransaction(currentPage()->getUName(), 0, Um::PathText, "", Um::ITextFrame);
03988                             transactionConversion=true;
03989                      }
03990                      newItem = new PageItem_PathText(*oldItem);
03991                      break;
03992               default:
03993                      newItem=NULL;
03994                      break;
03995        }
03996        Q_ASSERT(newItem!=NULL);
03997        //If the new item is null, return. If converting Text to Path, start a transaction
03998        //as the old bezier will be deleted
03999        if (newItem==NULL)
04000        {
04001               if (transactionConversion)
04002                      undoManager->cancelTransaction();
04003               return false;
04004        }
04005        //Do new item type specific adjustments to the new item. Some of this may move when new
04006        //constructors are built into the item classes
04007        switch (newType)
04008        {
04009               case PageItem::ImageFrame:
04010                      newItem->convertTo(PageItem::ImageFrame);
04011                      newItem->Frame = true;
04012                      break;
04013               case PageItem::TextFrame:
04014                      newItem->convertTo(PageItem::TextFrame);
04015                      newItem->Frame = true;
04016                      if (oldItem->itemType()==PageItem::PathText)
04017                      {
04018                             uint newPolyItemNo = itemAdd(PageItem::PolyLine, PageItem::Unspecified, currItem->xPos(), currItem->yPos(), currItem->width(), currItem->height(), currItem->lineWidth(), CommonStrings::None, currItem->lineColor(), true);
04019                             PageItem *polyLineItem = Items->at(newPolyItemNo);
04020                             polyLineItem->PoLine = currItem->PoLine.copy();
04021                             polyLineItem->ClipEdited = true;
04022                             polyLineItem->FrameType = 3;
04023                             polyLineItem->setRotation(currItem->rotation());
04024 //                          polyLineItem->setPolyClip(qRound(QMAX(polyLineItem->lineWidth() / 2, 1)));
04025                             AdjustItemSize(polyLineItem);
04026 
04027                             newItem->setLineColor(CommonStrings::None);
04028                             newItem->SetRectFrame();
04029                             newItem->setRedrawBounding();
04030                      }
04031                      break;
04032               //We dont allow this right now
04033               //case PageItem::Line:
04034               //     newItem->convertTo(PageItem::Line);
04035               //     break;
04036               case PageItem::Polygon:
04037                      newItem->convertTo(PageItem::Polygon);
04038                      newItem->Frame = false;
04039                      newItem->ClipEdited = true;
04040                      newItem->FrameType = 3;
04041                      if(oldItem->itemType()==PageItem::PolyLine)
04042                      {
04043                             newItem->PoLine.addPoint(newItem->PoLine.point(newItem->PoLine.size()-2));
04044                             newItem->PoLine.addPoint(newItem->PoLine.point(newItem->PoLine.size()-3));
04045                             newItem->PoLine.addPoint(newItem->PoLine.point(0));
04046                             newItem->PoLine.addPoint(newItem->PoLine.point(0));
04047                      }
04048                      newItem->Clip = FlattenPath(newItem->PoLine, newItem->Segments);
04049                      newItem->ContourLine = newItem->PoLine.copy();
04050                      break;
04051               case PageItem::PolyLine:
04052                      newItem->convertTo(PageItem::PolyLine);
04053                      newItem->ClipEdited = true;
04054 //                   newItem->setPolyClip(qRound(QMAX(newItem->lineWidth() / 2, 1)));
04055                      AdjustItemSize(newItem);
04056                      break;
04057               case PageItem::PathText:
04058                      {
04059                             newItem->convertTo(PageItem::PathText);
04060                             newItem->Frame = true;
04061                             newItem->ClipEdited = true;
04062                             newItem->PoLine = secondaryItem->PoLine.copy();
04063                             newItem->setLineWidth(secondaryItem->lineWidth());
04064                             newItem->setLineColor(secondaryItem->lineColor());
04065                             newItem->PLineArt = secondaryItem->PLineArt;
04066                             newItem->PLineEnd = secondaryItem->PLineEnd;
04067                             newItem->PLineJoin = secondaryItem->PLineJoin;
04068                             /*     if (!Doc->loading)
04069                                    emit UpdtObj(Doc->currentPage->pageNr(), b->ItemNr); */
04070                             //FIXME: Stop using the view here
04071                             AdjustItemSize(newItem);
04072 //                          newItem->updatePolyClip();
04073                             double dx = secondaryItem->xPos() - newItem->xPos();
04074                             double dy = secondaryItem->yPos() - newItem->yPos();
04075                             MoveItem(dx, dy, newItem);
04076                             newItem->setRotation(secondaryItem->rotation());
04077                             newItem->FrameType = 3;
04078                      }
04079                      break;
04080               default:
04081                      newItem=NULL;
04082                      break;
04083        }
04084        //Append the new item to the docs items list
04085        //Items->append(newItem);
04086        //We could append and renumber the list, or, we can insert at the same position..
04087        //for (uint a = 0; a < Items->count(); ++a)
04088        //     Items->at(a)->ItemNr = a;
04089 //     Items->insert(oldItem->ItemNr, newItem);
04090        newItem->ItemNr = oldItemNr;
04091        newItem->uniqueNr = oldItem->uniqueNr;
04092        Items->replace(oldItemNr, newItem);
04093        //Add new item back to selection if old item was in selection
04094        if (removedFromSelection)
04095               m_Selection->addItem(newItem);
04096        if (oldItem->Groups.count() != 0)
04097        {
04098               PageItem *currItem;
04099               for (uint a = 0; a < Items->count(); ++a)
04100               {
04101                      currItem = Items->at(a);
04102                      if (currItem->isGroupControl)
04103                      {
04104                             if (currItem->groupsLastItem == oldItem)
04105                                    currItem->groupsLastItem = newItem;
04106                      }
04107               }
04108        }
04109        //If converting text to path, delete the bezier
04110        if (newType==PageItem::PathText)
04111        {
04112               //FIXME: Stop using the view here
04113               m_View->SelectItem(secondaryItem);
04114               itemSelection_DeleteItem();
04115               emit updateContents();
04116               m_View->Deselect(true);
04117        }
04118        //Create the undo action for the new item
04119        if (UndoManager::undoEnabled())
04120        {
04121               ItemState<std::pair<PageItem*, PageItem*> > *is = new ItemState<std::pair<PageItem*, PageItem*> >("Convert Item");
04122               is->set("CONVERT_ITEM", "convert_item");
04123               is->setItem(std::pair<PageItem*, PageItem*>(oldItem, newItem));
04124               //Undo target rests with the Page for object specific undo
04125               UndoObject *target = Pages->at(0);
04126               if (newItem->OwnPage > -1)
04127                      target = Pages->at(newItem->OwnPage);
04128               undoManager->action(target, is);
04129        }
04130        //Close any undo transaction
04131        if (transactionConversion)
04132        {
04133               if (UndoManager::undoEnabled())
04134                      undoManager->commit();
04135        }
04136        return newItem;
04137 }
04138 
04139 const int ScribusDoc::currentPageNumber()
04140 {
04141        return currentPage()->pageNr();
04142 }
04143 
04144 bool ScribusDoc::itemNameExists(const QString checkItemName)
04145 {
04146        bool found = false;
04147        uint docItemCount=Items->count();
04148        for (uint i = 0; i < docItemCount; ++i)
04149        {
04150               if (checkItemName == Items->at(i)->itemName())
04151               {
04152                      found = true;
04153                      break;
04154               }
04155        }
04156        return found;
04157 }
04158 
04159 void ScribusDoc::setMasterPageMode(bool changeToMasterPageMode)
04160 {
04161        if (changeToMasterPageMode==m_masterPageMode)
04162               return;
04163        if (changeToMasterPageMode)
04164        {
04165               Pages=&MasterPages;
04166               Items=&MasterItems;
04167        }
04168        else
04169        {
04170               Pages=&DocPages;
04171               Items=&DocItems;
04172        }
04173        m_masterPageMode=changeToMasterPageMode;
04174 }
04175 
04176 void ScribusDoc::addSection(const int number, const QString& name, const uint fromindex, const uint toindex, const DocumentSectionType type, const uint sectionstartindex, const bool reversed, const bool active)
04177 {
04178        struct DocumentSection newSection;
04179        uint docPageCount=DocPages.count();
04180        bool empty=sections.isEmpty();
04181        if (empty)
04182        {
04183               newSection.number=0;
04184               newSection.name="0";
04185               newSection.fromindex=0;
04186               newSection.toindex=docPageCount-1;
04187               newSection.type=Type_1_2_3;
04188               newSection.sectionstartindex=1;
04189               newSection.reversed=false;
04190               newSection.active=true;
04191               sections.insert(newSection.number, newSection);
04192        }
04193        else if (number!=-1)
04194        {
04195               newSection.number=number;
04196               newSection.name=name;
04197               newSection.fromindex=fromindex;
04198               newSection.toindex=toindex;
04199               if (newSection.toindex>docPageCount-1)
04200                      newSection.toindex=docPageCount-1;
04201               newSection.type=type;
04202               newSection.sectionstartindex=sectionstartindex;
04203               newSection.reversed=reversed;
04204               newSection.active=active;
04205               sections.insert(newSection.number, newSection);
04206        }
04207 }
04208 
04209 bool ScribusDoc::deleteSection(const uint number)
04210 {
04211        if (!sections.contains(number))
04212               return false;
04213        if (sections.count()<=1)
04214               return false;
04215        QMap<uint, DocumentSection>::Iterator itprev=sections.begin();
04216        QMap<uint, DocumentSection>::Iterator it=itprev;
04217        uint currMinIndex = itprev.data().fromindex;
04218        uint currMaxIndex = itprev.data().toindex;
04219        for ( ; it != sections.end(); ++it )
04220        {
04221               currMinIndex=it.data().fromindex;
04222               currMaxIndex=it.data().toindex;
04223 
04224               if (it.key()!=number)
04225                      itprev=it;
04226               else
04227                      break;
04228        }
04229        if (it != itprev)
04230               itprev.data().toindex=currMaxIndex;
04231        else {
04232               // special case: delete first section
04233               QMap<uint, DocumentSection>::Iterator itnext = it;
04234               ++itnext;
04235               itnext.data().fromindex=it.data().fromindex;
04236        }
04237        sections.remove(it);
04238        return true;
04239 }
04240 
04241 int ScribusDoc::getSectionKeyForPageIndex(const uint pageIndex) const
04242 {
04243        bool found=false;
04244        int retVal=-1;
04245        DocumentSectionMap::ConstIterator it = sections.begin();
04246        for (; it!= sections.end(); ++it)
04247        {
04248               if (pageIndex>=it.data().fromindex && pageIndex<=it.data().toindex)
04249               {
04250                      found=true;
04251                      retVal=it.key();
04252                      break;
04253               }
04254        }
04255 
04256        return retVal;
04257 }
04258 
04259 const QString ScribusDoc::getSectionPageNumberForPageIndex(const uint pageIndex) const
04260 {
04261        QString retVal(QString::null);
04262        /*
04263        bool found=false;
04264 
04265        DocumentSectionMap::ConstIterator it = sections.begin();
04266        for (; it!= sections.end(); ++it)
04267        {
04268               if (pageIndex>=it.data().fromindex && pageIndex<=it.data().toindex)
04269               {
04270                      found=true;
04271                      break;
04272               }
04273        }
04274        if (!found)
04275               return retVal;
04276        */
04277        int key=getSectionKeyForPageIndex(pageIndex);
04278        if (key==-1)
04279               return retVal;
04280 
04281        uint sectionIndexOffset=pageIndex-sections[key].fromindex+sections[key].sectionstartindex;
04282        //If a section is inactive, theres no page numbers printed
04283        if (sections[key].active==false)
04284               return "";
04285        retVal=getStringFromSequence(sections[key].type, sectionIndexOffset);
04286        return retVal;
04287 }
04288 
04289 void ScribusDoc::updateSectionPageNumbersToPages()
04290 {
04291        uint docPageCount=DocPages.count();
04292        for (uint i=0;i<docPageCount;++i)
04293               DocPages.at(i)->setPageSectionNumber(getSectionPageNumberForPageIndex(i));
04294 }
04295 
04296 void ScribusDoc::addPageToSection(const uint otherPageIndex, const uint location, const uint count)
04297 {
04298        //Get the section of the new page index.
04299        bool found=false;
04300        DocumentSectionMap::Iterator it = sections.begin();
04301        if (otherPageIndex==0)
04302               found=true;
04303        for (; it!= sections.end(); ++it)
04304        {
04305               if (otherPageIndex-1>=it.data().fromindex && otherPageIndex-1<=it.data().toindex)
04306               {
04307                      found=true;
04308                      break;
04309               }
04310        }
04311        Q_ASSERT(found);
04312        if (!found)
04313               return;
04314        DocumentSectionMap::Iterator it2(it);
04315 
04316        //For this if: We are adding before the beginning of a section, so we must put this
04317        //new page in the previous section and then increment the rest
04318        if (otherPageIndex-1==it.data().fromindex && location==0 && it!=sections.begin())
04319               --it2;
04320        it2.data().toindex+=count;
04321        ++it2;
04322        while (it2!=sections.end())
04323        {
04324               it2.data().fromindex+=count;
04325               it2.data().toindex+=count;
04326               ++it2;
04327        }
04328        //Now update the Pages' internal storage of their page number
04329        updateSectionPageNumbersToPages();
04330 }
04331 
04332 
04333 void ScribusDoc::removePageFromSection(const uint pageIndex)
04334 {
04335        //Get the section of the new page index.
04336        bool found=false;
04337        DocumentSectionMap::Iterator it = sections.begin();
04338        for (; it!= sections.end(); ++it)
04339        {
04340               if (pageIndex>=it.data().fromindex && pageIndex<=it.data().toindex)
04341               {
04342                      found=true;
04343                      break;
04344               }
04345        }
04346        Q_ASSERT(found);
04347        if (!found)
04348               return;
04349        --it.data().toindex;
04350        ++it;
04351        while (it!=sections.end())
04352        {
04353               --it.data().fromindex;
04354               --it.data().toindex;
04355               ++it;
04356        }
04357        //Now update the Pages' internal storage of their page number
04358        updateSectionPageNumbersToPages();
04359 }
04360 
04361 void ScribusDoc::setFirstSectionFromFirstPageNumber()
04362 {
04363        DocumentSectionMap::Iterator it = sections.begin();
04364        it.data().sectionstartindex=FirstPnum;
04365        updateSectionPageNumbersToPages();
04366 }
04367 
04368 void ScribusDoc::copyPage(int pageNumberToCopy, int existingPage, int whereToInsert, int copyCount)
04369 {
04370        undoManager->beginTransaction(getUName(), Um::IDocument, Um::CopyPage, "", Um::ICreate);
04371        SimpleState *ss = new SimpleState(Um::Copy, "", Um::ICreate);
04372        ss->set("COPY_PAGE", "copy_page");
04373        ss->set("PAGE_NUM", pageNumberToCopy);
04374        ss->set("EXISTING_PAGE", existingPage);
04375        ss->set("WHERE_TO", whereToInsert);
04376        ss->set("COPY_COUNT", copyCount);
04377        undoManager->action(this, ss);
04378 
04379        //CB Should we really be disabled auto text frames here?
04380        bool autoText = usesAutomaticTextFrames();
04381        setUsesAutomaticTextFrames(false);
04382        Page* from = DocPages.at(pageNumberToCopy);
04383        Page* lastDest = NULL;
04384        int GrMax = GroupCounter;
04385        for (int copyNumber=1; copyNumber<=copyCount; ++copyNumber)
04386        {
04387               //For multiple insertions we can insert in the same place
04388               int destLocation=existingPage;
04389               if (whereToInsert==0)
04390                      --destLocation;
04391               else if (whereToInsert==2)
04392                      destLocation=DocPages.count();
04393               Page* destination = new Page(scratch.Left, DocPages.count()*(pageHeight+scratch.Bottom+scratch.Top)+scratch.Top, pageWidth, pageHeight);
04394               destination->setDocument(this);
04395               destination->setPageNr(destLocation);
04396               lastDest = destination;
04397               DocPages.insert(destLocation, destination);
04398               setLocationBasedPageLRMargins(destLocation);
04399               applyMasterPage(from->MPageNam, destLocation);
04400               destination->setInitialHeight(from->height());
04401               destination->setInitialWidth(from->width());
04402               destination->PageOri = from->PageOri;
04403               destination->m_pageSize = from->m_pageSize;
04404               destination->initialMargins.Top = from->initialMargins.Top;
04405               destination->initialMargins.Bottom = from->initialMargins.Bottom;
04406               if (pageSets[currentPageLayout].Columns == 1)
04407               {
04408                      destination->initialMargins.Left = from->initialMargins.Left;
04409                      destination->initialMargins.Right = from->initialMargins.Right;
04410               }
04411               else
04412               {
04413                      if (locationOfPage(destination->pageNr()) != locationOfPage(from->pageNr()))
04414                      {
04415                             if (locationOfPage(destination->pageNr()) == MiddlePage)
04416                             {
04417                                    destination->initialMargins.Right = from->initialMargins.Left;
04418                                    destination->initialMargins.Left = from->initialMargins.Left;
04419                             }
04420                             else
04421                             {
04422                                    destination->initialMargins.Right = from->initialMargins.Left;
04423                                    destination->initialMargins.Left = from->initialMargins.Right;
04424                             }
04425                      }
04426                      else
04427                      {
04428                             destination->initialMargins.Left = from->initialMargins.Left;
04429                             destination->initialMargins.Right = from->initialMargins.Right;
04430                      }
04431               }
04432               m_View->reformPages();
04433               uint oldItems = Items->count();
04434               m_Selection->clear();
04435               if (oldItems>0)
04436               {
04437                      QValueList<Layer>::iterator it;
04438                      if (Layers.count()!= 0)
04439                      {
04440                             int currActiveLayer = activeLayer();
04441                             for (it = Layers.begin(); it != Layers.end(); ++it)
04442                             {
04443                                    setActiveLayer((*it).LNr);
04444                                    for (uint ite = 0; ite < oldItems; ++ite)
04445                                    {
04446                                           PageItem *itemToCopy = Items->at(ite);
04447                                           if ((itemToCopy->OwnPage == static_cast<int>(from->pageNr())) && ((*it).LNr == itemToCopy->LayerNr))
04448                                                  m_Selection->addItem(itemToCopy, true);
04449                                    }
04450                                    if (m_Selection->count() != 0)
04451                                    {
04452                                           ScriXmlDoc *ss = new ScriXmlDoc();
04453                                           ss->ReadElem(ss->WriteElem(this, view(), m_Selection), prefsData.AvailFonts, this, destination->xOffset(), destination->yOffset(), false, true, prefsData.GFontSub, view());
04454                                           m_Selection->clear();
04455                                           delete ss;
04456                                    }
04457                             }
04458                             setActiveLayer(currActiveLayer);
04459                      }
04460               }
04461               from->guides.copy(&destination->guides);
04462               GroupCounter = GrMax + 1;
04463        }
04464        setUsesAutomaticTextFrames(autoText);
04465        addPageToSection(existingPage, whereToInsert, copyCount);
04466        if (lastDest != NULL)
04467               setCurrentPage(lastDest);
04468        else
04469               setCurrentPage(from);
04470        changed();
04471        undoManager->commit();
04472 }
04473 
04474 void ScribusDoc::setLocationBasedPageLRMargins(const uint pageIndex)
04475 {
04476        int setcol=pageSets[currentPageLayout].Columns;
04477        if (setcol==1)
04478        {
04479               Page* pageToAdjust=DocPages.at(pageIndex);
04480               pageToAdjust->Margins.Left = pageToAdjust->initialMargins.Left;
04481               pageToAdjust->Margins.Right = pageToAdjust->initialMargins.Right;
04482               return;
04483        }
04484 
04485        Page* pageToAdjust=DocPages.at(pageIndex);
04486        PageLocation pageLoc=locationOfPage(pageIndex);
04487        if (pageLoc==LeftPage) //Left hand page
04488        {
04489               pageToAdjust->Margins.Left = pageToAdjust->initialMargins.Right;
04490               pageToAdjust->Margins.Right = pageToAdjust->initialMargins.Left;
04491        }
04492        else if (pageLoc==RightPage) // Right hand page
04493        {
04494               pageToAdjust->Margins.Right = pageToAdjust->initialMargins.Right;
04495               pageToAdjust->Margins.Left = pageToAdjust->initialMargins.Left;
04496        }
04497        else //Middle pages
04498        {
04499               pageToAdjust->Margins.Left = pageToAdjust->initialMargins.Left;
04500               pageToAdjust->Margins.Right = pageToAdjust->initialMargins.Left;
04501        }
04502        /* Can also calc the X pos of the frame too, and Y pos, but thats not done yet
04503        int myRow=(pageIndex+pageSets[currentPageLayout].FirstPage)/setcol;
04504        double xOffset=ScratchLeft;
04505        double yOffset=ScratchTop;
04506        if (myRow==0)
04507        {
04508               if (pageIndex==0)
04509               {
04510                      for (int i=0; i<myCol; ++i)
04511                             xOffset+=pageWidth+pageSets[currentPageLayout].GapHorizontal;
04512               }
04513               else
04514               {
04515                      xOffset=DocPages.at(0)->xOffset();
04516                      for (int i=0; i<pageIndex; ++i)
04517                             xOffset+=DocPages.at(i)->width()+pageSets[currentPageLayout].GapHorizontal;
04518               }
04519        }
04520        if (myRow>0)
04521        {
04522               int firstPageOnRow=pageIndex-myCol;
04523               for (int i=firstPageOnRow; i<pageIndex; ++i)
04524                      xOffset+=DocPages.at(i)->width()+pageSets[currentPageLayout].GapHorizontal;
04525        }
04526        pageToAdjust->setXOffset(xOffset);
04527 
04528 
04529        if (myRow!=0)
04530        {
04531               for (int i=0;i<myRow;++i)
04532               {
04533                      double maxHeightOfRow=0.0;
04534                      yOffset+=DocPages.at(i)->width()+pageSets[currentPageLayout].GapHorizontal;
04535               }
04536 
04537               if (pageIndex==0)
04538               {
04539                      for (int i=0; i<myCol; ++i)
04540                             xOffset+=pageWidth+pageSets[currentPageLayout].GapHorizontal;
04541               }
04542               else
04543               {
04544                      xOffset=DocPages.at(0)->xOffset();
04545                      for (int i=0; i<pageIndex; ++i)
04546                             xOffset+=DocPages.at(i)->width()+pageSets[currentPageLayout].GapHorizontal;
04547               }
04548        }
04549        if (myRow>0)
04550        {
04551               int firstPageOnRow=pageIndex-myCol;
04552        int setcol=pageSets[currentPageLayout].Columns;
04553               for (int i=firstPageOnRow; i<pageIndex; ++i)
04554                      xOffset+=DocPages.at(i)->width()+pageSets[currentPageLayout].GapHorizontal;
04555        }
04556        pageToAdjust->setXOffset(xOffset);
04557        */
04558 }
04559 
04560 PageLocation ScribusDoc::locationOfPage(int pageIndex)
04561 {
04562        int setcol=pageSets[currentPageLayout].Columns;
04563        if (setcol==1)
04564               return LeftPage;
04565        int myCol = ((pageIndex % setcol)+pageSets[currentPageLayout].FirstPage)%setcol;
04566        if (myCol==0) //Left hand page
04567               return LeftPage;
04568        else if (myCol>= setcol-1) // Right hand page
04569               return RightPage;
04570        else //Middle pages
04571               return MiddlePage;
04572 }
04573 
04574 
04575 void ScribusDoc::updateAllItemQColors()
04576 {
04577        for (uint c=0; c<DocItems.count(); ++c)
04578        {
04579               PageItem *ite = DocItems.at(c);
04580               ite->setLineQColor();
04581               ite->setFillQColor();
04582        }
04583        for (uint c=0; c<MasterItems.count(); ++c)
04584        {
04585               PageItem *ite = MasterItems.at(c);
04586               ite->setLineQColor();
04587               ite->setFillQColor();
04588        }
04589        for (uint c=0; c<FrameItems.count(); ++c)
04590        {
04591               PageItem *ite = FrameItems.at(c);
04592               ite->setLineQColor();
04593               ite->setFillQColor();
04594        }
04595        QStringList patterns = docPatterns.keys();
04596        for (uint c = 0; c < patterns.count(); ++c)
04597        {
04598               ScPattern pa = docPatterns[patterns[c]];
04599               for (uint o = 0; o < pa.items.count(); o++)
04600               {
04601                      PageItem *ite = pa.items.at(o);
04602                      ite->setLineQColor();
04603                      ite->setFillQColor();
04604               }
04605        }
04606 }
04607 
04608 //CB Moved from view
04609 void ScribusDoc::RecalcPictures(ProfilesL *Pr, ProfilesL *PrCMYK, QProgressBar *dia)
04610 {
04611        uint docItemCount=Items->count();
04612        if ( docItemCount!= 0)
04613        {
04614               bool usingGUI=ScCore->usingGUI();
04615               int counter = 0;
04616               if (usingGUI && dia != NULL)
04617                      counter = dia->progress();
04618               PageItem* it;
04619               for (uint i=0; i < docItemCount; ++i)
04620               {
04621                      it = Items->at(i);
04622                      if ((it->itemType() == PageItem::ImageFrame) && (it->PicAvail))
04623                      {
04624                             if (it->pixm.imgInfo.colorspace == 1)
04625                             {
04626                                    if (!PrCMYK->contains(it->IProfile))
04627                                           it->IProfile = CMSSettings.DefaultImageCMYKProfile;
04628                             }
04629                             else
04630                             {
04631                                    if (!Pr->contains(it->IProfile))
04632                                           it->IProfile = CMSSettings.DefaultImageRGBProfile;
04633                             }
04634                             LoadPict(it->Pfile, i, true);
04635                      }
04636                      if (usingGUI)
04637                      {
04638                             ++counter;
04639                             if (dia != NULL)
04640                                    dia->setProgress(counter);
04641                      }
04642               }
04643        }
04644 }
04645 
04646 void ScribusDoc::insertColor(QString nam, double c, double m, double y, double k)
04647 {
04648        if (!PageColors.contains(nam))
04649        {
04650               ScColor tmp = ScColor(static_cast<int>(255 * c), static_cast<int>(255 * m),
04651                                         static_cast<int>(255 * y), static_cast<int>(255 * k));
04652               PageColors.insert(nam, tmp);
04653        }
04654 }
04655 
04656 bool ScribusDoc::sendItemSelectionToBack()
04657 {
04658        uint docSelectionCount=m_Selection->count();
04659        if ((Items->count() > 1) && (docSelectionCount != 0))
04660        {
04661               QMap<int, uint> ObjOrder;
04662               PageItem *currItem;
04663               for (uint c = 0; c < docSelectionCount; ++c)
04664               {
04665                      currItem = m_Selection->itemAt(c);
04666                      if (((currItem->isSingleSel) && (currItem->isGroupControl)) || ((currItem->isSingleSel) && (currItem->isTableItem)))
04667                             return false;
04668                      ObjOrder.insert(currItem->ItemNr, c);
04669                      int d = Items->findRef(currItem);
04670                      Items->take(d);
04671               }
04672               QValueList<uint> Oindex = ObjOrder.values();
04673               for (int c = static_cast<int>(Oindex.count()-1); c > -1; c--)
04674               {
04675                      Items->prepend(m_Selection->itemAt(Oindex[c]));
04676               }
04677               renumberItemsInListOrder();
04678               return true;
04679        }
04680        return false;
04681 }
04682 
04683 bool ScribusDoc::bringItemSelectionToFront()
04684 {
04685        uint docSelectionCount=m_Selection->count();
04686        if ((Items->count() > 1) && (docSelectionCount != 0))
04687        {
04688               QMap<int, uint> ObjOrder;
04689               PageItem *currItem;
04690               for (uint c = 0; c < docSelectionCount; ++c)
04691               {
04692                      currItem = m_Selection->itemAt(c);
04693                      if (((currItem->isSingleSel) && (currItem->isGroupControl)) || ((currItem->isSingleSel) && (currItem->isTableItem)))
04694                             return false;
04695                      ObjOrder.insert(currItem->ItemNr, c);
04696                      int d = Items->findRef(currItem);
04697                      Items->take(d);
04698               }
04699               QValueList<uint> Oindex = ObjOrder.values();
04700               for (int c = 0; c <static_cast<int>(Oindex.count()); ++c)
04701               {
04702                      Items->append(m_Selection->itemAt(Oindex[c]));
04703               }
04704               renumberItemsInListOrder();
04705               return true;
04706        }
04707        return false;
04708 }
04709 
04710 void ScribusDoc::ChLineWidth(double w)
04711 {
04712        uint selectedItemCount=m_Selection->count();
04713        if (selectedItemCount != 0)
04714        {
04715               if (selectedItemCount > 1)
04716                      undoManager->beginTransaction(Um::SelectionGroup,
04717                                                                         Um::IGroup, Um::LineWidth, "", Um::ILineStyle);
04718               for (uint a = 0; a < selectedItemCount; ++a)
04719               {
04720                      PageItem *currItem = m_Selection->itemAt(a);
04721                      //cb moved to setlinewidth
04722                      //currItem->Oldm_lineWidth = currItem->lineWidth();
04723                      currItem->setLineWidth(w);
04724                      if (currItem->asPolyLine())
04725                             currItem->setPolyClip(qRound(QMAX(currItem->lineWidth() / 2, 1)));
04726                      if (currItem->asLine())
04727                      {
04728                             int ph = static_cast<int>(QMAX(1.0, w / 2.0));
04729                             currItem->Clip.setPoints(4, -ph,-ph, static_cast<int>(currItem->width()+ph),-ph,
04730                                               static_cast<int>(currItem->width()+ph),static_cast<int>(currItem->height()+ph),
04731                                               -ph,static_cast<int>(currItem->height()+ph));
04732                      }
04733                      emit refreshItem(currItem);
04734               }
04735               if (selectedItemCount > 1)
04736                      undoManager->commit();
04737        }
04738        changed();
04739 }
04740 
04741 void ScribusDoc::ChLineArt(Qt::PenStyle w)
04742 {
04743        uint selectedItemCount=m_Selection->count();
04744        if (selectedItemCount != 0)
04745        {
04746               if (selectedItemCount > 1)
04747                      undoManager->beginTransaction(Um::SelectionGroup,
04748                                             Um::IGroup, Um::LineStyle, "", Um::ILineStyle);
04749               for (uint a = 0; a < selectedItemCount; ++a)
04750               {
04751                      m_Selection->itemAt(a)->setLineStyle(w);
04752                      emit refreshItem(m_Selection->itemAt(a));
04753               }
04754               if (selectedItemCount > 1)
04755                      undoManager->commit();
04756        }
04757        changed();
04758 }
04759 
04760 void ScribusDoc::ChLineJoin(Qt::PenJoinStyle w)
04761 {
04762        uint selectedItemCount=m_Selection->count();
04763        if (selectedItemCount != 0)
04764        {
04765               if (selectedItemCount > 1)
04766                      undoManager->beginTransaction(Um::SelectionGroup,
04767                                                                         Um::IGroup, Um::LineJoin, "", Um::ILineStyle);
04768               for (uint a = 0; a < selectedItemCount; ++a)
04769               {
04770                      m_Selection->itemAt(a)->setLineJoin(w);
04771                      emit refreshItem(m_Selection->itemAt(a));
04772               }
04773               if (selectedItemCount > 1)
04774                      undoManager->commit();
04775        }
04776        changed();
04777 }
04778 
04779 void ScribusDoc::ChLineEnd(Qt::PenCapStyle w)
04780 {
04781        uint selectedItemCount=m_Selection->count();
04782        if (selectedItemCount != 0)
04783        {
04784               if (selectedItemCount > 1)
04785                      undoManager->beginTransaction(Um::SelectionGroup,
04786                                                                         Um::IGroup, Um::LineEnd, "", Um::ILineStyle);
04787               for (uint a = 0; a < selectedItemCount; ++a)
04788               {
04789                      m_Selection->itemAt(a)->setLineEnd(w);
04790                      emit refreshItem(m_Selection->itemAt(a));
04791               }
04792               if (selectedItemCount > 1)
04793                      undoManager->commit();
04794        }
04795        changed();
04796 }
04797 
04798 void ScribusDoc::itemSelection_SetLineSpacing(double w, Selection* customSelection)
04799 {
04800        ParagraphStyle newStyle;
04801        newStyle.setLineSpacing(w);
04802        itemSelection_ApplyParagraphStyle(newStyle, customSelection);
04803 }
04804 
04805 void ScribusDoc::itemSelection_SetFont(QString fon, Selection* customSelection)
04806 {
04807        CharStyle newStyle;
04808        newStyle.setFont((*AllFonts)[fon]);
04809        itemSelection_ApplyCharStyle(newStyle, customSelection);
04810 }
04811 
04812 void ScribusDoc::itemSelection_SetNamedCharStyle(const QString& name, Selection* customSelection)
04813 {
04814        CharStyle newStyle;
04815        newStyle.setParent(name.isEmpty()? Style::INHERIT_PARENT : name);
04816        itemSelection_ApplyCharStyle(newStyle, customSelection);
04817 }
04818 
04819 void ScribusDoc::itemSelection_SetNamedParagraphStyle(const QString& name, Selection* customSelection)
04820 {
04821        ParagraphStyle newStyle;
04822        newStyle.setParent(name.isEmpty()? Style::INHERIT_PARENT : name);
04823        itemSelection_ApplyParagraphStyle(newStyle, customSelection);
04824 }
04825 
04826 void ScribusDoc::ItemPen(QString farbe)
04827 {
04828        uint selectedItemCount=m_Selection->count();
04829        if (selectedItemCount != 0)
04830        {
04831               if (farbe == CommonStrings::tr_NoneColor)
04832                      farbe = CommonStrings::None;
04833               if (selectedItemCount > 1)
04834                      undoManager->beginTransaction(Um::SelectionGroup,
04835                                                                         Um::IGroup, Um::SetLineColor, farbe, Um::IFill);
04836               PageItem *i;
04837               for (uint a = 0; a < selectedItemCount; ++a)
04838               {
04839                      i = m_Selection->itemAt(a);
04840                      if ((i->asLine()) && (farbe == CommonStrings::None))
04841                             continue;
04842 
04843                      i->setLineColor(farbe);
04844                      emit refreshItem(i);
04845               }
04846               if (selectedItemCount > 1)
04847                      undoManager->commit();
04848        }
04849        changed();
04850 }
04851 
04852 void ScribusDoc::itemSelection_SetFillColor(QString farbe, Selection* customSelection)
04853 {
04854        CharStyle newStyle;
04855        newStyle.setFillColor(farbe);
04856        itemSelection_ApplyCharStyle(newStyle, customSelection);
04857 }
04858 
04859 void ScribusDoc::itemSelection_SetFillShade(int sha, Selection* customSelection)
04860 {
04861        CharStyle newStyle;
04862        newStyle.setFillShade(sha);
04863        itemSelection_ApplyCharStyle(newStyle, customSelection);
04864 }
04865 
04866 void ScribusDoc::itemSelection_SetStrokeColor(QString farbe, Selection* customSelection)
04867 {
04868        if (farbe == CommonStrings::tr_NoneColor)
04869               farbe = CommonStrings::None;
04870        
04871        CharStyle newStyle;
04872        newStyle.setStrokeColor(farbe);
04873        itemSelection_ApplyCharStyle(newStyle, customSelection);
04874 }
04875 
04876 void ScribusDoc::itemSelection_SetStrokeShade(int sha, Selection* customSelection)
04877 {
04878        CharStyle newStyle;
04879        newStyle.setStrokeShade(sha);
04880        itemSelection_ApplyCharStyle(newStyle, customSelection);
04881 }
04882 
04883 void ScribusDoc::itemSelection_SetScaleV(int scale, Selection* customSelection)
04884 {
04885        CharStyle newStyle;
04886        newStyle.setScaleV(scale);
04887        itemSelection_ApplyCharStyle(newStyle, customSelection);
04888 }
04889 
04890 void ScribusDoc::itemSelection_SetScaleH(int scale, Selection* customSelection)
04891 {
04892        CharStyle newStyle;
04893        newStyle.setScaleH(scale);
04894        itemSelection_ApplyCharStyle(newStyle, customSelection);
04895 }
04896 
04897 void ScribusDoc::itemSelection_SetShadowOffsets(int shx, int shy, Selection* customSelection)
04898 {
04899        CharStyle newStyle;
04900        newStyle.setShadowXOffset(shx);
04901        newStyle.setShadowYOffset(shy);
04902        itemSelection_ApplyCharStyle(newStyle, customSelection);
04903 }
04904 
04905 void ScribusDoc::itemSelection_SetUnderline(int pos, int wid, Selection* customSelection)
04906 {
04907        CharStyle newStyle;
04908        newStyle.setUnderlineOffset(pos);
04909        newStyle.setUnderlineWidth(wid);
04910        itemSelection_ApplyCharStyle(newStyle, customSelection);
04911 }
04912 
04913 void ScribusDoc::itemSelection_SetStrikethru(int pos, int wid, Selection* customSelection)
04914 {
04915        CharStyle newStyle;
04916        newStyle.setStrikethruOffset(pos);
04917        newStyle.setStrikethruWidth(wid);
04918        itemSelection_ApplyCharStyle(newStyle, customSelection);
04919 }
04920 
04921 void ScribusDoc::itemSelection_SetBaselineOffset(int sha, Selection* customSelection)
04922 {
04923        CharStyle newStyle;
04924        newStyle.setBaselineOffset(sha);
04925        itemSelection_ApplyCharStyle(newStyle, customSelection);
04926 }
04927 
04928 void ScribusDoc::itemSelection_SetOutlineWidth(int wid, Selection* customSelection)
04929 {
04930        CharStyle newStyle;
04931        newStyle.setOutlineWidth(wid);
04932        itemSelection_ApplyCharStyle(newStyle, customSelection);
04933 }
04934 
04935 void ScribusDoc::ItemBrush(QString farbe)
04936 {
04937        if (farbe == CommonStrings::tr_NoneColor)
04938               farbe = CommonStrings::None;
04939        uint selectedItemCount=m_Selection->count();
04940        if (selectedItemCount != 0)
04941        {
04942               if (selectedItemCount > 1)
04943                      undoManager->beginTransaction(Um::SelectionGroup,
04944                                                                         Um::IGroup, Um::SetFill, farbe, Um::IFill);
04945               PageItem *currItem;
04946               for (uint a = 0; a < selectedItemCount; ++a)
04947               {
04948                      currItem = m_Selection->itemAt(a);
04949                      currItem->setFillColor(farbe);
04950                      emit refreshItem(currItem);
04951               }
04952               if (selectedItemCount > 1)
04953                      undoManager->commit();
04954               changed();
04955        }
04956 }
04957 
04958 void ScribusDoc::ItemBrushShade(int sha)
04959 {
04960        uint selectedItemCount=m_Selection->count();
04961        if (selectedItemCount != 0)
04962        {
04963               if (selectedItemCount > 1)
04964                      undoManager->beginTransaction(Um::SelectionGroup,
04965                                                                         Um::IGroup, Um::SetShade, QString("%1").arg(sha),
04966                                                                         Um::IShade);
04967               PageItem *currItem;
04968               for (uint a = 0; a < selectedItemCount; ++a)
04969               {
04970                      currItem = m_Selection->itemAt(a);
04971                      currItem->setFillShade(sha);
04972                      emit refreshItem(currItem);
04973               }
04974               if (selectedItemCount > 1)
04975                      undoManager->commit();
04976               changed();
04977        }
04978 }
04979 
04980 void ScribusDoc::ItemPenShade(int sha)
04981 {
04982        uint selectedItemCount=m_Selection->count();
04983        if (selectedItemCount != 0)
04984        {
04985               PageItem *currItem;
04986               if (selectedItemCount > 1)
04987                      undoManager->beginTransaction(Um::SelectionGroup,
04988                                                  Um::IGroup, Um::SetLineShade, QString("%1").arg(sha), Um::IShade);
04989               for (uint a = 0; a < selectedItemCount; ++a)
04990               {
04991                      currItem = m_Selection->itemAt(a);
04992                      currItem->setLineShade(sha);
04993                      emit refreshItem(currItem);
04994               }
04995               if (selectedItemCount > 1)
04996                      undoManager->commit();
04997               changed();
04998        }
04999 }
05000 
05001 void ScribusDoc::ItemGradFill(int typ)
05002 {
05003        uint selectedItemCount=m_Selection->count();
05004        if (selectedItemCount != 0)
05005        {
05006               PageItem *currItem;
05007               for (uint a = 0; a < selectedItemCount; ++a)
05008               {
05009                      currItem = m_Selection->itemAt(a);
05010                      currItem->GrType = typ;
05011                      switch (currItem->GrType)
05012                      {
05013                             case 0:
05014                             case 1:
05015                                    currItem->GrStartX = 0;
05016                                    currItem->GrStartY = currItem->height() / 2.0;
05017                                    currItem->GrEndX = currItem->width();
05018                                    currItem->GrEndY = currItem->height() / 2.0;
05019                                    break;
05020                             case 2:
05021                                    currItem->GrStartX = currItem->width() / 2.0;
05022                                    currItem->GrStartY = 0;
05023                                    currItem->GrEndX = currItem->width() / 2.0;
05024                                    currItem->GrEndY = currItem->height();
05025                                    break;
05026                             case 3:
05027                                    currItem->GrStartX = 0;
05028                                    currItem->GrStartY = 0;
05029                                    currItem->GrEndX = currItem->width();
05030                                    currItem->GrEndY = currItem->height();
05031                                    break;
05032                             case 4:
05033                                    currItem->GrStartX = 0;
05034                                    currItem->GrStartY = currItem->height();
05035                                    currItem->GrEndX = currItem->width();
05036                                    currItem->GrEndY = 0;
05037                                    break;
05038                             case 5:
05039                                    currItem->GrStartX = currItem->width() / 2.0;
05040                                    currItem->GrStartY = currItem->height() / 2.0;
05041                                    if (currItem->width() >= currItem->height())
05042                                    {
05043                                           currItem->GrEndX = currItem->width();
05044                                           currItem->GrEndY = currItem->height() / 2.0;
05045                                    }
05046                                    else
05047                                    {
05048                                           currItem->GrEndX = currItem->width() / 2.0;
05049                                           currItem->GrEndY = currItem->height();
05050                                    }
05051                                    break;
05052                             default:
05053                                    break;
05054                      }
05055                      if (typ != 8)
05056                             currItem->updateGradientVectors();
05057                      emit refreshItem(currItem);
05058               }
05059               changed();
05060        }
05061 }
05062 
05063 void ScribusDoc::ItemPatternFill(QString pattern)
05064 {
05065        uint selectedItemCount=m_Selection->count();
05066        if (selectedItemCount != 0)
05067        {
05068               PageItem *currItem;
05069               for (uint a = 0; a < selectedItemCount; ++a)
05070               {
05071                      currItem = m_Selection->itemAt(a);
05072                      currItem->setPattern(pattern);
05073                      emit refreshItem(currItem);
05074               }
05075               changed();
05076        }
05077 }
05078 
05079 void ScribusDoc::ItemPatternProps(double scaleX, double scaleY, double offsetX, double offsetY, double rotation)
05080 {
05081        uint selectedItemCount=m_Selection->count();
05082        if (selectedItemCount != 0)
05083        {
05084               PageItem *currItem;
05085               for (uint a = 0; a < selectedItemCount; ++a)
05086               {
05087                      currItem = m_Selection->itemAt(a);
05088                      currItem->setPatternTransform(scaleX, scaleY, offsetX, offsetY, rotation);
05089                      emit refreshItem(currItem);
05090               }
05091               changed();
05092        }
05093 }
05094 
05095 void ScribusDoc::itemSelection_SetEffects(int s, Selection* customSelection)
05096 {
05097        CharStyle newStyle;
05098        newStyle.setFeatures(static_cast<StyleFlag>(s).featureList());
05099        itemSelection_ApplyCharStyle(newStyle, customSelection);
05100        return;
05101        
05102        uint selectedItemCount=m_Selection->count();
05103        if (selectedItemCount != 0 && s != ScStyle_None)
05104        {
05105               if (selectedItemCount > 1)
05106                      undoManager->beginTransaction(Um::SelectionGroup, Um::IGroup, Um::SetFontEffect, "", Um::IFont);
05107               for (uint aa = 0; aa < selectedItemCount; ++aa)
05108               {
05109                      PageItem *currItem = m_Selection->itemAt(aa);
05110 //                   if (appMode != modeEdit)
05111 //                          currItem->setFontEffects(s);
05112                      if (currItem->itemText.length() != 0)
05113                      {
05114 #ifndef NLS_PROTO
05115                             if (appMode == modeEdit)
05116                             {
05117                                    for (int a = 0; a < currItem->itemText.length(); ++a)
05118                                    {
05119                                           if (currItem->itemText.selected(a))
05120                                           {
05121                                                  StyleFlag fl = currItem->itemText.item(a)->effects();
05122                                                  fl &= static_cast<StyleFlag>(~1919); // 0x11101111111
05123                                                  fl |= static_cast<StyleFlag>(s & 1919);
05124                                                  currItem->itemText.item(a)->setFeatures(fl.featureList());
05125                                           }
05126                                    }
05127                             }
05128                             else
05129                             {
05130                                    for (int a = 0; a < currItem->itemText.length(); ++a)
05131                                    {
05132                                           StyleFlag fl = currItem->itemText.item(a)->effects();
05133                                           fl &= static_cast<StyleFlag>(~1919); // 1024+512+256+64+32+16+8+4+2+1
05134                                           fl |= static_cast<StyleFlag>(s & 1919);
05135                                           currItem->itemText.item(a)->setFeatures(fl.featureList());
05136                                    }
05137                             }
05138 #endif
05139                             emit refreshItem(currItem);
05140                      }
05141               }
05142               if (selectedItemCount > 1)
05143                      undoManager->commit();
05144               changed();
05145        }
05146 }
05147 
05148 void ScribusDoc::itemSelection_SetOpticalMargins(int i, Selection* customSelection)
05149 {
05150        ParagraphStyle newStyle;
05151        newStyle.setOpticalMargins(i);
05152        itemSelection_ApplyParagraphStyle(newStyle, customSelection);
05153 }
05154 
05155 void ScribusDoc::itemSelection_SetTracking(int kern, Selection* customSelection)
05156 {
05157        CharStyle newStyle;
05158        newStyle.setTracking(kern);
05159        itemSelection_ApplyCharStyle(newStyle, customSelection);
05160 }
05161 
05162 void ScribusDoc::itemSelection_SetLineSpacingMode(int m, Selection* customSelection)
05163 {
05164        ParagraphStyle newStyle;
05165        newStyle.setLineSpacingMode(static_cast<ParagraphStyle::LineSpacingMode>(m));
05166        itemSelection_ApplyParagraphStyle(newStyle, customSelection);
05167 }
05168 
05169 void ScribusDoc::itemSelection_SetFontSize(int size, Selection* customSelection)
05170 {
05171        if (true || appMode == modeEdit) 
05172        {
05173               CharStyle newStyle;
05174               newStyle.setFontSize(size);
05175               itemSelection_ApplyCharStyle(newStyle, customSelection);
05176        }
05177        else
05178        {
05179               ParagraphStyle storyStyle;
05180               storyStyle.charStyle().setFontSize(size);
05181               if (storyStyle.lineSpacingMode() == 0)
05182               {
05183                      storyStyle.setLineSpacing(((size / 10.0) * static_cast<double>(typographicSettings.autoLineSpacing) / 100) + (size / 10.0));
05184               }
05185               else if (storyStyle.lineSpacingMode() == 1)
05186               {
05187                      storyStyle.setLineSpacing(storyStyle.charStyle().font().height(size));
05188               }
05189               else
05190               {
05191                      storyStyle.setLineSpacing(typographicSettings.valueBaseGrid-1);
05192               }
05193               itemSelection_ApplyParagraphStyle(storyStyle, customSelection);
05194        }
05195 }
05196 
05197 void ScribusDoc::itemSelection_SetParagraphStyle(const ParagraphStyle & newStyle, Selection* customSelection)
05198 {
05199        Selection* itemSelection = (customSelection!=0) ? customSelection : m_Selection;
05200        assert(itemSelection!=0);
05201        uint selectedItemCount=itemSelection->count();
05202        if (selectedItemCount == 0)
05203               return;
05204        if (selectedItemCount > 1)
05205               undoManager->beginTransaction(Um::SelectionGroup, Um::IGroup, Um::ApplyTextStyle, newStyle.displayName(), Um::IFont);
05206        for (uint aa = 0; aa < selectedItemCount; ++aa)
05207        {
05208               PageItem *currItem = itemSelection->itemAt(aa);
05209               int currItemTextCount = currItem->lastInFrame() + 1 - currItem->firstInFrame();
05210               if (currItemTextCount > 0 && ( appMode == modeEdit || !FRAMESELECTION_EDITS_DEFAULTSTYLE))
05211               {
05212                      int start = currItem->itemText.startOfItem(currItem->firstInFrame());
05213                      int stop = currItem->itemText.endOfItem(currItem->lastInFrame());
05214                      if (appMode == modeEdit)
05215                      {
05216                             start = currItem->itemText.startOfSelection();
05217                             stop = currItem->itemText.endOfSelection();
05218                             if (start >= stop)
05219                                    start = stop = QMAX(0, QMIN(currItem->itemText.length(), currItem->CPos));
05220                      }
05221                      for (int pos=start; pos < stop; ++pos)
05222                      {
05223                             if (currItem->itemText.text(pos) == SpecialChars::PARSEP)
05224                             {
05225                                    currItem->itemText.setStyle(pos, newStyle);
05226                             }
05227                      }
05228                      currItem->itemText.setStyle(stop, newStyle);
05229                      currItem->invalid = true;
05230               }
05231               else
05232               {
05233                      currItem->itemText.setDefaultStyle(newStyle);
05234               }
05235               if (currItem->asPathText())
05236                      currItem->updatePolyClip();
05237        }
05238        if (selectedItemCount > 1)
05239               undoManager->commit();
05240        changed();
05241        emit updateContents();
05242 }
05243 
05244 
05245 
05246 void ScribusDoc::itemSelection_EraseParagraphStyle(Selection* customSelection)
05247 {
05248        Selection* itemSelection = (customSelection!=0) ? customSelection : m_Selection;
05249        assert(itemSelection!=0);
05250        uint selectedItemCount=itemSelection->count();
05251        if (selectedItemCount == 0)
05252               return;
05253        if (selectedItemCount > 1)
05254               undoManager->beginTransaction(Um::SelectionGroup, Um::IGroup, Um::ApplyTextStyle, tr( "remove direct paragraph formatting" ), Um::IFont);
05255        for (uint aa = 0; aa < selectedItemCount; ++aa)
05256        {
05257               PageItem *currItem = itemSelection->itemAt(aa);
05258               int currItemTextCount = currItem->lastInFrame() + 1 - currItem->firstInFrame();
05259               if (currItemTextCount > 0 && ( appMode == modeEdit || !FRAMESELECTION_EDITS_DEFAULTSTYLE))
05260               {
05261                      int start = currItem->itemText.startOfItem(currItem->firstInFrame());
05262                      int stop = currItem->itemText.endOfItem(currItem->lastInFrame());
05263                      if (appMode == modeEdit)
05264                      {
05265                             start = currItem->itemText.startOfSelection();
05266                             stop = currItem->itemText.endOfSelection();
05267                             if (start >= stop)
05268                                    start = stop = QMAX(0, QMIN(currItem->itemText.length(), currItem->CPos));
05269                      }
05270                      for (int pos=start; pos < stop; ++pos)
05271                      {
05272                             if (currItem->itemText.text(pos) == SpecialChars::PARSEP)
05273                             {
05274                                    ParagraphStyle newStyle;
05275                                    newStyle.setParent(currItem->itemText.paragraphStyle(pos).parent());
05276                                    currItem->itemText.setStyle(pos, newStyle);
05277                             }
05278                      }
05279                      ParagraphStyle newStyle2;
05280                      newStyle2.setParent(currItem->itemText.paragraphStyle(stop).parent());
05281                      currItem->itemText.setStyle(stop, newStyle2);
05282               }
05283               else
05284               {
05285                      ParagraphStyle newStyle;
05286                      newStyle.setParent(currItem->itemText.defaultStyle().parent());
05287                      currItem->itemText.setDefaultStyle(newStyle);
05288               }
05289               currItem->invalid = true;
05290               if (currItem->asPathText())
05291                      currItem->updatePolyClip();
05292        }
05293        if (selectedItemCount > 1)
05294               undoManager->commit();
05295        changed();
05296        emit updateContents();
05297 }
05298 
05299 
05300 
05301 void ScribusDoc::itemSelection_ApplyParagraphStyle(const ParagraphStyle & newStyle, Selection* customSelection)
05302 {
05303        Selection* itemSelection = (customSelection!=0) ? customSelection : m_Selection;
05304        assert(itemSelection!=0);
05305        uint selectedItemCount=itemSelection->count();
05306        if (selectedItemCount == 0)
05307               return;
05308        if (selectedItemCount > 1)
05309               undoManager->beginTransaction(Um::SelectionGroup, Um::IGroup, Um::ApplyTextStyle, newStyle.displayName(), Um::IFont);
05310        for (uint aa = 0; aa < selectedItemCount; ++aa)
05311        {
05312               PageItem *currItem = itemSelection->itemAt(aa);
05313               int currItemTextCount = currItem->lastInFrame() + 1 - currItem->firstInFrame();
05314               if (currItemTextCount > 0 && ( appMode == modeEdit || !FRAMESELECTION_EDITS_DEFAULTSTYLE))
05315               {
05316                      int start = currItem->itemText.startOfItem(currItem->firstInFrame());
05317                      int stop = currItem->itemText.endOfItem(currItem->lastInFrame());
05318                      if (appMode == modeEdit)
05319                      {
05320                             start = currItem->itemText.startOfSelection();
05321                             stop = currItem->itemText.endOfSelection();
05322                             if (start >= stop)
05323                                    start = stop = QMAX(0, QMIN(currItem->itemText.length(), currItem->CPos));
05324                      }
05325                      for (int pos=start; pos < stop; ++pos)
05326                      {
05327                             if (currItem->itemText.text(pos) == SpecialChars::PARSEP)
05328                             {
05329                                    currItem->itemText.applyStyle(pos, newStyle);
05330                             }
05331                      }
05332                      currItem->itemText.applyStyle(stop, newStyle);
05333                      currItem->invalid = true;
05334               }
05335               else
05336               {
05337                      ParagraphStyle dstyle(currItem->itemText.defaultStyle());
05338                      dstyle.applyStyle(newStyle);
05339                      currItem->itemText.setDefaultStyle(dstyle);
05340                      if (currItem->asPathText())
05341                      {
05342                             for (int pos=0; pos < currItem->itemText.length(); ++pos)
05343                             {
05344                                    if (currItem->itemText.text(pos) == SpecialChars::PARSEP)
05345                                    {
05346                                           currItem->itemText.applyStyle(pos, newStyle);
05347                                    }
05348                             }
05349                             currItem->itemText.applyStyle(currItem->itemText.length(), newStyle);
05350                      }
05351               }
05352               if (currItem->asPathText())
05353                      currItem->updatePolyClip();
05354        }
05355        if (selectedItemCount > 1)
05356               undoManager->commit();
05357        changed();
05358        emit updateContents();
05359 }
05360 
05361 void ScribusDoc::itemSelection_ApplyCharStyle(const CharStyle & newStyle, Selection* customSelection)
05362 {
05363        Selection* itemSelection = (customSelection!=0) ? customSelection : m_Selection;
05364        assert(itemSelection!=0);
05365        uint selectedItemCount=itemSelection->count();
05366        if (selectedItemCount == 0)
05367               return;
05368        if (selectedItemCount > 1)
05369               undoManager->beginTransaction(Um::SelectionGroup, Um::IGroup, Um::ApplyTextStyle, newStyle.asString(), Um::IFont);
05370        for (uint aa = 0; aa < selectedItemCount; ++aa)
05371        {
05372               PageItem *currItem = itemSelection->itemAt(aa);
05373               int currItemTextCount = currItem->lastInFrame() + 1 - currItem->firstInFrame();
05374               if (currItemTextCount > 0 && ( appMode == modeEdit || !FRAMESELECTION_EDITS_DEFAULTSTYLE))
05375               {
05376                      int start = currItem->itemText.startOfItem(currItem->firstInFrame());
05377                      int length = currItem->itemText.endOfItem(currItem->lastInFrame()) - start;
05378                      if (appMode == modeEdit)
05379                      {
05380                             if (currItem->itemText.lengthOfSelection() > 0)
05381                             {
05382                                    start = currItem->itemText.startOfSelection();
05383                                    length = currItem->itemText.endOfSelection() - start;
05384                             }
05385                             else
05386                             {
05387                                    start = QMAX(currItem->firstInFrame(), currItem->CPos);
05388                                    length = start + 1 < currItem->itemText.length()? 1 : 0;
05389                             }
05390                      }
05391                      currItem->itemText.applyCharStyle(start, QMAX(0, length), newStyle);
05392                      currItem->invalid = true;
05393               }
05394               else
05395               {
05396                      ParagraphStyle dstyle(currItem->itemText.defaultStyle());
05397                      dstyle.charStyle().applyCharStyle(newStyle);
05398                      currItem->itemText.setDefaultStyle(dstyle);
05399                      if (currItem->asPathText())
05400                             currItem->itemText.applyCharStyle(0, currItem->itemText.length(), newStyle);
05401               }
05402               if (currItem->asPathText())
05403                      currItem->updatePolyClip();
05404        }
05405        if (selectedItemCount > 1)
05406               undoManager->commit();
05407        changed();
05408        emit updateContents();
05409 }
05410 
05411 
05412 
05413 void ScribusDoc::itemSelection_SetCharStyle(const CharStyle & newStyle, Selection* customSelection)
05414 {
05415        Selection* itemSelection = (customSelection!=0) ? customSelection : m_Selection;
05416        assert(itemSelection!=0);
05417        uint selectedItemCount=itemSelection->count();
05418        if (selectedItemCount == 0)
05419               return;
05420        if (selectedItemCount > 1)
05421               undoManager->beginTransaction(Um::SelectionGroup, Um::IGroup, Um::ApplyTextStyle, newStyle.asString(), Um::IFont);
05422        for (uint aa = 0; aa < selectedItemCount; ++aa)
05423        {
05424               PageItem *currItem = itemSelection->itemAt(aa);
05425               int currItemTextCount = currItem->lastInFrame() + 1 - currItem->firstInFrame();
05426               if (currItemTextCount > 0 && ( appMode == modeEdit || !FRAMESELECTION_EDITS_DEFAULTSTYLE))
05427               {
05428                      int start = currItem->itemText.startOfItem(currItem->firstInFrame());
05429                      int length = currItem->itemText.endOfItem(currItem->lastInFrame()) - start;
05430                      if (appMode == modeEdit)
05431                      {
05432                             if (currItem->itemText.lengthOfSelection() > 0)
05433                             {
05434                                    start = currItem->itemText.startOfSelection();
05435                                    length = currItem->itemText.endOfSelection() - start;
05436                             }
05437                             else
05438                             {
05439                                    start = QMAX(currItem->firstInFrame(), currItem->CPos);
05440                                    length = start + 1 < currItem->itemText.length()? 1 : 0;
05441                             }
05442                      }
05443                      currItem->itemText.setCharStyle(start, length, newStyle);
05444                      currItem->invalid = true;
05445               }
05446               else
05447               {
05448                      ParagraphStyle dstyle(currItem->itemText.defaultStyle());
05449                      dstyle.charStyle().setStyle(newStyle);
05450                      currItem->itemText.setDefaultStyle(dstyle);
05451                      if (currItem->asPathText())
05452                             currItem->itemText.setCharStyle(0, currItem->itemText.length(), newStyle);
05453               }
05454               if (currItem->asPathText())
05455                      currItem->updatePolyClip();
05456        }
05457        if (selectedItemCount > 1)
05458               undoManager->commit();
05459        changed();
05460        emit updateContents();
05461 }
05462 
05463 
05464 void ScribusDoc::itemSelection_EraseCharStyle(Selection* customSelection)
05465 {
05466        Selection* itemSelection = (customSelection!=0) ? customSelection : m_Selection;
05467        assert(itemSelection!=0);
05468        uint selectedItemCount=itemSelection->count();
05469        if (selectedItemCount == 0)
05470               return;
05471        if (selectedItemCount > 1)
05472               undoManager->beginTransaction(Um::SelectionGroup, Um::IGroup, Um::ApplyTextStyle, tr( "remove direct char formatting" ), Um::IFont);
05473        for (uint aa = 0; aa < selectedItemCount; ++aa)
05474        {
05475               PageItem *currItem = itemSelection->itemAt(aa);
05476               int currItemTextCount = currItem->lastInFrame() + 1 - currItem->firstInFrame();
05477               if (currItemTextCount > 0 && ( appMode == modeEdit || !FRAMESELECTION_EDITS_DEFAULTSTYLE))
05478               {
05479                      int start = currItem->itemText.startOfItem(currItem->firstInFrame());
05480                      int length = currItem->itemText.endOfItem(currItem->lastInFrame()) - start;
05481                      if (appMode == modeEdit)
05482                      {
05483                             if (currItem->itemText.lengthOfSelection() > 0)
05484                             {
05485                                    start = currItem->itemText.startOfSelection();
05486                                    length = currItem->itemText.endOfSelection() - start;
05487                             }
05488                             else
05489                             {
05490                                    start = QMAX(currItem->firstInFrame(), currItem->CPos);
05491                                    length = (start + 1) < currItem->itemText.length()? 1 : 0;
05492                             }
05493                      }
05494                      QString lastParent;
05495                      int stop = start+length;
05496                      int lastPos = start;
05497                      for (int i=start; i < stop; ++i)
05498                      {
05499                             const QString& curParent(currItem->itemText.charStyle(i).parent());
05500                             if (curParent != lastParent)
05501                             {
05502                                    if ( i-lastPos > 0)
05503                                    {
05504                                           CharStyle newStyle;
05505                                           newStyle.setParent(lastParent);
05506                                           currItem->itemText.setCharStyle(lastPos, i-lastPos, newStyle);
05507                                           lastPos = i;
05508                                    }
05509                                    lastParent = curParent;
05510                             }
05511                      }
05512                      if (lastPos < stop)
05513                      {
05514                             CharStyle newStyle2;
05515                             newStyle2.setParent(lastParent);
05516                             currItem->itemText.setCharStyle(lastPos, stop-lastPos, newStyle2);
05517                      }
05518               }
05519               else {
05520                      ParagraphStyle defStyle = currItem->itemText.defaultStyle();
05521                      CharStyle newStyle;
05522                      newStyle.setParent(defStyle.charStyle().parent());
05523                      defStyle.charStyle() = newStyle;
05524                      currItem->itemText.setDefaultStyle(defStyle);
05525               }
05526               currItem->invalid = true;
05527               if (currItem->asPathText())
05528                      currItem->updatePolyClip();
05529        }
05530        if (selectedItemCount > 1)
05531               undoManager->commit();
05532        changed();
05533        emit updateContents();
05534 }
05535 
05536 
05537 /*
05538 template<typename Arg, void (PageItem::*Fun)(Arg)>
05539 void ScribusDoc::itemSelection_forall(Arg newVal)
05540 {
05541        uint docSelectionCount=m_Selection->count();
05542        if (docSelectionCount != 0)
05543        {
05544               if (docSelectionCount > 1)
05545                      undoManager->beginTransaction(Um::SelectionGroup, Um::IGroup, Um::ApplyTextStyle,
05546                                                                         newStyle.asString(), Um::IFont);
05547               for (uint aa = 0; aa < docSelectionCount; ++aa)
05548               {
05549                      PageItem *currItem = m_Selection->itemAt(aa);
05550                      currItem->Fun(newVal);
05551               }
05552        }
05553        if (docSelectionCount > 1)
05554               undoManager->commit();
05555        emit updateContents();
05556 }
05557 */
05558 
05559 
05560 
05561 
05562 /* CB Dont delete, backups
05563 void ScribusDoc::FlipImageH()
05564 {
05565        uint docSelectionCount=m_Selection->count();
05566        if (docSelectionCount != 0)
05567        {
05568               if (docSelectionCount > 1)
05569                      undoManager->beginTransaction(Um::SelectionGroup, Um::IGroup,
05570                                                                         Um::FlipH, 0, Um::IFlipH);
05571               for (uint a = 0; a < docSelectionCount; ++a)
05572               {
05573                      m_Selection->itemAt(a)->flipImageH();
05574                      emit refreshItem(m_Selection->itemAt(a));
05575               }
05576               changed();
05577               if (docSelectionCount > 1)
05578                      undoManager->commit();
05579        }
05580 }
05581 
05582 void ScribusDoc::FlipImageV()
05583 {
05584        uint docSelectionCount=m_Selection->count();
05585        if (docSelectionCount != 0)
05586        {
05587               if (docSelectionCount > 1)
05588                      undoManager->beginTransaction(Um::SelectionGroup, Um::IGroup,
05589                                                                         Um::FlipV, 0, Um::IFlipV);
05590               for (uint a = 0; a < docSelectionCount; ++a)
05591               {
05592                      m_Selection->itemAt(a)->flipImageV();
05593                      emit refreshItem(m_Selection->itemAt(a));
05594               }
05595               changed();
05596               if (docSelectionCount > 1)
05597                      undoManager->commit();
05598        }
05599 }
05600 
05601 */
05602 
05603 //CB removed looping, called by itemSelection_FlipH
05604 void ScribusDoc::MirrorPolyH(PageItem* currItem)
05605 {
05606        currItem->ClipEdited = true;
05607        QWMatrix ma;
05608        if (view()->EditContour)
05609        {
05610               if (UndoManager::undoEnabled())
05611               {
05612                      SimpleState *ss = new SimpleState(Um::FlipH, "", Um::IFlipH);
05613                      ss->set("MIRROR_PATH_H", "mirror_path_h");
05614                      ss->set("IS_CONTOUR", true);
05615                      undoManager->action(currItem, ss, Um::IBorder);
05616               }
05617               FPoint tp2(getMinClipF(&currItem->ContourLine));
05618               FPoint tp(getMaxClipF(&currItem->ContourLine));
05619               ma.translate(qRound(tp.x()), 0);
05620               ma.scale(-1, 1);
05621               currItem->ContourLine.map(ma);
05622               emit updateContents();
05623 //            currItem->Tinput = true;
05624               currItem->FrameOnly = true;
05625               currItem->paintObj();
05626               currItem->FrameOnly = false;
05627               m_View->MarkClip(currItem, currItem->ContourLine, true);
05628               changed();
05629               return;
05630        }
05631        ma.scale(-1, 1);
05632        currItem->PoLine.map(ma);
05633        currItem->PoLine.translate(currItem->width(), 0);
05634        if (currItem->asPathText())
05635               currItem->updatePolyClip();
05636        else
05637               currItem->Clip = FlattenPath(currItem->PoLine, currItem->Segments);
05638        setRedrawBounding(currItem);
05639        emit refreshItem(currItem);
05640        if (UndoManager::undoEnabled())
05641        {
05642               SimpleState *ss = new SimpleState(Um::FlipH, "", Um::IFlipH);
05643               ss->set("MIRROR_PATH_H", "mirror_path_h");
05644               ss->set("IS_CONTOUR", false);
05645               undoManager->action(currItem, ss, Um::IBorder);
05646        }
05647        changed();
05648 }
05649 
05650 //CB removed looping, called by itemSelection_FlipV
05651 void ScribusDoc::MirrorPolyV(PageItem* currItem)
05652 {
05653        currItem->ClipEdited = true;
05654        QWMatrix ma;
05655        if (view()->EditContour)
05656        {
05657               if (UndoManager::undoEnabled())
05658               {
05659                      SimpleState *ss = new SimpleState(Um::FlipV, "", Um::IFlipV);
05660                      ss->set("MIRROR_PATH_V", "mirror_path_v");
05661                      ss->set("IS_CONTOUR", true);
05662                      undoManager->action(currItem, ss, Um::IBorder);
05663               }
05664               FPoint tp2(getMinClipF(&currItem->ContourLine));
05665               FPoint tp(getMaxClipF(&currItem->ContourLine));
05666               ma.translate(0, qRound(tp.y()));
05667               ma.scale(1, -1);
05668               currItem->ContourLine.map(ma);
05669               emit updateContents();
05670 //            currItem->Tinput = true;
05671               currItem->FrameOnly = true;
05672               currItem->paintObj();
05673               currItem->FrameOnly = false;
05674               m_View->MarkClip(currItem, currItem->ContourLine, true);
05675               changed();
05676               return;
05677        }
05678        ma.scale(1, -1);
05679        currItem->PoLine.map(ma);
05680        currItem->PoLine.translate(0, currItem->height());
05681        if (currItem->asPathText())
05682               currItem->updatePolyClip();
05683        else
05684               currItem->Clip = FlattenPath(currItem->PoLine, currItem->Segments);
05685        setRedrawBounding(currItem);
05686        emit refreshItem(currItem);
05687        if (UndoManager::undoEnabled())
05688        {
05689               SimpleState *ss = new SimpleState(Um::FlipV, "", Um::IFlipV);
05690               ss->set("MIRROR_PATH_V", "mirror_path_v");
05691               ss->set("IS_CONTOUR", false);
05692               undoManager->action(currItem, ss, Um::IBorder);
05693        }
05694        changed();
05695 }
05696 
05697 void ScribusDoc::setRedrawBounding(PageItem *currItem)
05698 {
05699        currItem->setRedrawBounding();
05700        FPoint maxSize(currItem->BoundingX+currItem->BoundingW+scratch.Right, currItem->BoundingY+currItem->BoundingH+scratch.Bottom);
05701        FPoint minSize(currItem->BoundingX-scratch.Left, currItem->BoundingY-scratch.Top);
05702        adjustCanvas(minSize, maxSize);
05703 }
05704 
05705 void ScribusDoc::adjustCanvas(FPoint minPos, FPoint maxPos, bool absolute)
05706 {
05707        double newMaxX, newMaxY, newMinX, newMinY;
05708        if (absolute)
05709        {
05710               newMaxX = maxPos.x();
05711               newMaxY = maxPos.y();
05712               newMinX = minPos.x();
05713               newMinY = minPos.y();
05714        }
05715        else
05716        {
05717               newMaxX = QMAX(maxCanvasCoordinate.x(), maxPos.x());
05718               newMaxY = QMAX(maxCanvasCoordinate.y(), maxPos.y());
05719               newMinX = QMIN(minCanvasCoordinate.x(), minPos.x());
05720               newMinY = QMIN(minCanvasCoordinate.y(), minPos.y());
05721        }
05722        if ((newMaxX != maxCanvasCoordinate.x()) || (newMaxY != maxCanvasCoordinate.y())
05723        || (newMinX != minCanvasCoordinate.x()) || (newMinY != minCanvasCoordinate.y()))
05724        {
05725               //CB TODO Make a list of views we belong to and make this the doc's active view via an internal*
05726               if (ScCore->usingGUI() && !m_View->operItemMoving)
05727               {
05728                      //Save the old values for the emit, but update now to ensure we are all ready
05729                      double oldMinX=minCanvasCoordinate.x();
05730                      double oldMinY=minCanvasCoordinate.y();
05731                      maxCanvasCoordinate = FPoint(newMaxX, newMaxY);
05732                      minCanvasCoordinate = FPoint(newMinX, newMinY);
05733                      // Why using a signal here ? much slower than a direct call
05734 //                   emit canvasAdjusted(newMaxX - newMinX, newMaxY - newMinY, oldMinX - newMinX, oldMinY - newMinY);
05735                      m_View->adjustCanvas(newMaxX - newMinX, newMaxY - newMinY, oldMinX - newMinX, oldMinY - newMinY);
05736               }
05737        }
05738 }
05739 
05740 void ScribusDoc::connectDocSignals()
05741 {
05742        if (ScCore->usingGUI())
05743        {
05744               connect(this, SIGNAL(setApplicationMode(int)), m_ScMW, SLOT(setAppMode(int)));
05745               connect(this, SIGNAL(docChanged()), m_ScMW, SLOT(slotDocCh()));
05746               connect(this, SIGNAL(firstSelectedItemType(int)), m_ScMW, SLOT(HaveNewSel(int)));
05747               connect(autoSaveTimer, SIGNAL(timeout()), WinHan, SLOT(slotAutoSave()));
05748               connect(this, SIGNAL(refreshItem(PageItem*)), view(), SLOT(RefreshItem(PageItem*)));
05749               connect(this, SIGNAL(updateContents()), view(), SLOT(slotUpdateContents()));
05750               connect(this, SIGNAL(updateContents(const QRect&)), view(), SLOT(slotUpdateContents(const QRect&)));
05751 //            connect(this, SIGNAL(canvasAdjusted(double, double, double, double)), view(), SLOT(adjustCanvas(double, double, double, double)));
05752        }
05753 }
05754 
05755 //CB Same as RecalcPicturesRes apart from the name checking, which should be able to be removed
05756 void ScribusDoc::updatePict(QString name)
05757 {
05758        for (uint a = 0; a < DocItems.count(); ++a)
05759        {
05760               PageItem *currItem = DocItems.at(a);
05761               if ((currItem->PicAvail) && (currItem->Pfile == name))
05762               {
05763                      bool fho = currItem->imageFlippedH();
05764                      bool fvo = currItem->imageFlippedV();
05765                      loadPict(currItem->Pfile, currItem, true);
05766                      currItem->setImageFlippedH(fho);
05767                      currItem->setImageFlippedV(fvo);
05768                      currItem->AdjustPictScale();
05769               }
05770        }
05771        for (uint a = 0; a < MasterItems.count(); ++a)
05772        {
05773               PageItem *currItem = MasterItems.at(a);
05774               if ((currItem->PicAvail) && (currItem->Pfile == name))
05775               {
05776                      bool fho = currItem->imageFlippedH();
05777                      bool fvo = currItem->imageFlippedV();
05778                      loadPict(currItem->Pfile, currItem, true);
05779                      currItem->setImageFlippedH(fho);
05780                      currItem->setImageFlippedV(fvo);
05781                      currItem->AdjustPictScale();
05782               }
05783        }
05784        for (uint a = 0; a <FrameItems.count(); ++a)
05785        {
05786               PageItem *currItem = FrameItems.at(a);
05787               if ((currItem->PicAvail) && (currItem->Pfile == name))
05788               {
05789                      bool fho = currItem->imageFlippedH();
05790                      bool fvo = currItem->imageFlippedV();
05791                      loadPict(currItem->Pfile, currItem, true);
05792                      currItem->setImageFlippedH(fho);
05793                      currItem->setImageFlippedV(fvo);
05794                      currItem->AdjustPictScale();
05795               }
05796        }
05797        QStringList patterns = docPatterns.keys();
05798        for (uint c = 0; c < patterns.count(); ++c)
05799        {
05800               ScPattern pa = docPatterns[patterns[c]];
05801               for (uint o = 0; o < pa.items.count(); o++)
05802               {
05803                      PageItem *currItem = pa.items.at(o);
05804                      if ((currItem->PicAvail) && (currItem->Pfile == name))
05805                      {
05806                             bool fho = currItem->imageFlippedH();
05807                             bool fvo = currItem->imageFlippedV();
05808                             loadPict(currItem->Pfile, currItem, true);
05809                             currItem->setImageFlippedH(fho);
05810                             currItem->setImageFlippedV(fvo);
05811                             currItem->AdjustPictScale();
05812                      }
05813               }
05814               PageItem *ite = pa.items.at(0);
05815               docPatterns[patterns[c]].pattern = ite->DrawObj_toImage(pa.items);
05816        }
05817        emit updateContents();
05818        changed();
05819 }
05820 
05821 //CB Same as updatePict apart from the name checking, this should be able to be removed
05822 void ScribusDoc::recalcPicturesRes(bool applyNewRes)
05823 {
05824        int cc = 0;
05825        int ca = 0;
05826        m_ScMW->mainWindowProgressBar->reset();
05827        for (uint a = 0; a < DocItems.count(); ++a)
05828        {
05829               PageItem *currItem = DocItems.at(a);
05830               if (currItem->PicAvail)
05831                 cc++;
05832        }
05833        for (uint a = 0; a < MasterItems.count(); ++a)
05834        {
05835               PageItem *currItem = MasterItems.at(a);
05836               if (currItem->PicAvail)
05837                      cc++;
05838        }
05839        for (uint a = 0; a < FrameItems.count(); ++a)
05840        {
05841               PageItem *currItem = FrameItems.at(a);
05842               if (currItem->PicAvail)
05843                      cc++;
05844        }
05845        QStringList patterns = docPatterns.keys();
05846        for (uint c = 0; c < patterns.count(); ++c)
05847        {
05848               ScPattern pa = docPatterns[patterns[c]];
05849               for (uint o = 0; o < pa.items.count(); o++)
05850               {
05851                      PageItem *currItem = pa.items.at(o);
05852                      if (currItem->PicAvail)
05853                             cc++;
05854               }
05855        }
05856        m_ScMW->mainWindowProgressBar->setTotalSteps(cc);
05857        for (uint a = 0; a < DocItems.count(); ++a)
05858        {
05859               PageItem *currItem = DocItems.at(a);
05860               if (currItem->PicAvail)
05861               {
05862                      bool fho = currItem->imageFlippedH();
05863                      bool fvo = currItem->imageFlippedV();
05864                      if (applyNewRes)
05865                             currItem->pixm.imgInfo.lowResType = toolSettings.lowResType;
05866                      loadPict(currItem->Pfile, currItem, true);
05867                      currItem->setImageFlippedH(fho);
05868                      currItem->setImageFlippedV(fvo);
05869                      currItem->AdjustPictScale();
05870                      ca++;
05871                      m_ScMW->mainWindowProgressBar->setProgress(ca);
05872                      qApp->eventLoop()->processEvents(QEventLoop::ExcludeUserInput);
05873               }
05874        }
05875        for (uint a = 0; a < MasterItems.count(); ++a)
05876        {
05877               PageItem *currItem = MasterItems.at(a);
05878               if (currItem->PicAvail)
05879               {
05880                      bool fho = currItem->imageFlippedH();
05881                      bool fvo = currItem->imageFlippedV();
05882                      if (applyNewRes)
05883                             currItem->pixm.imgInfo.lowResType = toolSettings.lowResType;
05884                      loadPict(currItem->Pfile, currItem, true);
05885                      currItem->setImageFlippedH(fho);
05886                      currItem->setImageFlippedV(fvo);
05887                      currItem->AdjustPictScale();
05888                      ca++;
05889                      m_ScMW->mainWindowProgressBar->setProgress(ca);
05890                      qApp->eventLoop()->processEvents(QEventLoop::ExcludeUserInput);
05891               }
05892        }
05893        for (uint a = 0; a < FrameItems.count(); ++a)
05894        {
05895               PageItem *currItem = FrameItems.at(a);
05896               if (currItem->PicAvail)
05897               {
05898                      bool fho = currItem->imageFlippedH();
05899                      bool fvo = currItem->imageFlippedV();
05900                      if (applyNewRes)
05901                             currItem->pixm.imgInfo.lowResType = toolSettings.lowResType;
05902                      loadPict(currItem->Pfile, currItem, true);
05903                      currItem->setImageFlippedH(fho);
05904                      currItem->setImageFlippedV(fvo);
05905                      currItem->AdjustPictScale();
05906                      ca++;
05907                      m_ScMW->mainWindowProgressBar->setProgress(ca);
05908                      qApp->eventLoop()->processEvents(QEventLoop::ExcludeUserInput);
05909               }
05910        }
05911        for (uint c = 0; c < patterns.count(); ++c)
05912        {
05913               ScPattern pa = docPatterns[patterns[c]];
05914               for (uint o = 0; o < pa.items.count(); o++)
05915               {
05916                      PageItem *currItem = pa.items.at(o);
05917                      if (currItem->PicAvail)
05918                      {
05919                             bool fho = currItem->imageFlippedH();
05920                             bool fvo = currItem->imageFlippedV();
05921                             if (applyNewRes)
05922                                    currItem->pixm.imgInfo.lowResType = toolSettings.lowResType;
05923                             loadPict(currItem->Pfile, currItem, true);
05924                             currItem->setImageFlippedH(fho);
05925                             currItem->setImageFlippedV(fvo);
05926                             currItem->AdjustPictScale();
05927                             ca++;
05928                             m_ScMW->mainWindowProgressBar->setProgress(ca);
05929                             qApp->eventLoop()->processEvents(QEventLoop::ExcludeUserInput);
05930                      }
05931               }
05932               PageItem *ite = pa.items.at(0);
05933               docPatterns[patterns[c]].pattern = ite->DrawObj_toImage(pa.items);
05934        }
05935        emit updateContents();
05936        changed();
05937        m_ScMW->mainWindowProgressBar->reset();
05938 }
05939 
05940 void ScribusDoc::removePict(QString name)
05941 {
05942        for (uint a = 0; a < DocItems.count(); ++a)
05943        {
05944               PageItem *currItem = DocItems.at(a);
05945               if ((currItem->PicAvail) && (currItem->Pfile == name))
05946               {
05947                      currItem->PicAvail = false;
05948                      currItem->pixm = ScImage();
05949               }
05950        }
05951        for (uint a = 0; a < MasterItems.count(); ++a)
05952        {
05953               PageItem *currItem = MasterItems.at(a);
05954               if ((currItem->PicAvail) && (currItem->Pfile == name))
05955               {
05956                      currItem->PicAvail = false;
05957                      currItem->pixm = ScImage();
05958               }
05959        }
05960        for (uint a = 0; a < FrameItems.count(); ++a)
05961        {
05962               PageItem *currItem = FrameItems.at(a);
05963               if ((currItem->PicAvail) && (currItem->Pfile == name))
05964               {
05965                      currItem->PicAvail = false;
05966                      currItem->pixm = ScImage();
05967               }
05968        }
05969        QStringList patterns = docPatterns.keys();
05970        for (uint c = 0; c < patterns.count(); ++c)
05971        {
05972               ScPattern pa = docPatterns[patterns[c]];
05973               for (uint o = 0; o < pa.items.count(); o++)
05974               {
05975                      PageItem *currItem = pa.items.at(o);
05976                      if ((currItem->PicAvail) && (currItem->Pfile == name))
05977                      {
05978                             currItem->PicAvail = false;
05979                             currItem->pixm = ScImage();
05980                      }
05981               }
05982               PageItem *ite = pa.items.at(0);
05983               docPatterns[patterns[c]].pattern = ite->DrawObj_toImage(pa.items);
05984        }
05985        emit updateContents();
05986        changed();
05987 }
05988 
05989 void ScribusDoc::updatePic()
05990 {
05991        uint docSelectionCount=m_Selection->count();
05992        if (docSelectionCount > 0)
05993        {
05994               bool toUpdate=false;
05995               for (uint i = 0; i < docSelectionCount; ++i)
05996               {
05997                      if (m_Selection->itemAt(i)!=NULL)
05998                             if (m_Selection->itemAt(i)->asImageFrame())
05999                             {
06000                                    PageItem *currItem = m_Selection->itemAt(i);
06001                                    if (currItem->PicAvail)
06002                                    {
06003                                           int fho = currItem->imageFlippedH();
06004                                           int fvo = currItem->imageFlippedV();
06005                                           loadPict(currItem->Pfile, currItem, true);
06006                                           currItem->setImageFlippedH(fho);
06007                                           currItem->setImageFlippedV(fvo);
06008                                           currItem->AdjustPictScale();
06009                                           toUpdate=true;
06010                                    }
06011                             }
06012               }
06013               if (toUpdate)
06014                      emit updateContents();
06015        }
06016 }
06017 
06018 //TODO replace with the ScribusDoc::deleteTaggedItems
06019 void ScribusDoc::removeLayer(int l, bool dl)
06020 {
06021        m_View->Deselect();
06022        for (uint b = 0; b < MasterItems.count(); ++b)
06023        {
06024               if (MasterItems.at(b)->LayerNr == l)
06025               {
06026                      if (dl)
06027                      {
06028                             m_Selection->addItem(MasterItems.at(b));
06029                             DocItems.at(b)->setLocked(false);
06030                      }
06031                      else
06032                             MasterItems.at(b)->setLayer(0);
06033               }
06034        }
06035        if (m_Selection->count() != 0)
06036               itemSelection_DeleteItem();
06037        m_Selection->clear();
06038        for (uint b = 0; b < DocItems.count(); ++b)
06039        {
06040               if (DocItems.at(b)->LayerNr == l)
06041               {
06042                      if (dl)
06043                      {
06044                             m_Selection->addItem(DocItems.at(b));
06045                             DocItems.at(b)->setLocked(false);
06046                      }
06047                      else
06048                             DocItems.at(b)->setLayer(0);
06049               }
06050        }
06051        if (m_Selection->count() != 0)
06052               itemSelection_DeleteItem();
06053        //FIXME signal these
06054        m_ScMW->rebuildLayersList();
06055        m_View->updateLayerMenu();
06056 }
06057 
06058 void ScribusDoc::itemSelection_ToggleLock( )
06059 {
06060        uint docSelectionCount=m_Selection->count();
06061        if (docSelectionCount != 0)
06062        {
06063               if (docSelectionCount > 1)
06064               {
06065                      if (m_Selection->itemAt(0)->locked())
06066                             undoManager->beginTransaction(Um::SelectionGroup, Um::IGroup, Um::UnLock, 0, Um::IUnLock);
06067                      else
06068                             undoManager->beginTransaction(Um::SelectionGroup, Um::IGroup, Um::Lock, 0, Um::ILock);
06069               }
06070               for ( uint a = 0; a < docSelectionCount; ++a)
06071               {
06072                      m_Selection->itemAt(a)->toggleLock();
06073                      emit refreshItem(m_Selection->itemAt(a));
06074               }
06075               if (docSelectionCount > 1)
06076                      undoManager->commit();
06077               changed();
06078               emit firstSelectedItemType(m_Selection->itemAt(0)->itemType());
06079        }
06080 }
06081 
06082 void ScribusDoc::itemSelection_ToggleSizeLock( )
06083 {
06084        uint selectedItemCount=m_Selection->count();
06085        if (selectedItemCount != 0)
06086        {
06087               if (selectedItemCount > 1)
06088               {
06089                      if (m_Selection->itemAt(0)->sizeLocked())
06090                             undoManager->beginTransaction(Um::SelectionGroup, Um::IGroup, Um::SizeUnLock, 0, Um::IUnLock);
06091                      else
06092                             undoManager->beginTransaction(Um::SelectionGroup, Um::IGroup, Um::SizeLock, 0, Um::ILock);
06093               }
06094               for ( uint a = 0; a < selectedItemCount; ++a)
06095               {
06096                      m_Selection->itemAt(a)->toggleSizeLock();
06097                      emit refreshItem(m_Selection->itemAt(a));
06098               }
06099               if (selectedItemCount > 1)
06100                      undoManager->commit();
06101               changed();
06102               emit firstSelectedItemType(m_Selection->itemAt(0)->itemType());
06103        }
06104 }
06105 
06106 
06107 void ScribusDoc::itemSelection_ToggleImageShown()
06108 {
06109        if (m_Selection->count() != 0)
06110        {
06111               for (uint a = 0; a < m_Selection->count(); ++a)
06112               {
06113                      PageItem_ImageFrame* imageItem=m_Selection->itemAt(a)->asImageFrame();
06114                      if (imageItem==NULL)
06115                             continue;
06116                      imageItem->setImageShown(!imageItem->imageShown());
06117                      emit refreshItem(imageItem);
06118               }
06119               changed();
06120               //Return to normal mode if in edit mode. We should not allow dragging of
06121               //an image in a frame if its not shown.
06122               if (appMode == modeEdit)
06123                      emit setApplicationMode(modeNormal);
06124        }
06125 }
06126 
06127 void ScribusDoc::itemSelection_TogglePrintEnabled( )
06128 {
06129        uint docSelectionCount=m_Selection->count();
06130        if (docSelectionCount != 0)
06131        {
06132               if (docSelectionCount > 1)
06133               {
06134                      if (m_Selection->itemAt(0)->printEnabled())
06135                             undoManager->beginTransaction(Um::SelectionGroup, Um::IGroup, Um::DisablePrint, 0, Um::IDisablePrint);
06136                      else
06137                             undoManager->beginTransaction(Um::SelectionGroup, Um::IGroup, Um::EnablePrint, 0, Um::IEnablePrint);
06138               }
06139               for ( uint a = 0; a < docSelectionCount; ++a)
06140               {
06141                      m_Selection->itemAt(a)->togglePrintEnabled();
06142                      emit refreshItem(m_Selection->itemAt(a));
06143               }
06144               if (docSelectionCount > 1)
06145                      undoManager->commit();
06146               changed();
06147               emit firstSelectedItemType(m_Selection->itemAt(0)->itemType());
06148        }
06149 }
06150 
06151 void ScribusDoc::itemSelection_FlipH()
06152 {
06153        uint docSelectionCount=m_Selection->count();
06154        if (docSelectionCount != 0)
06155        {
06156               if (docSelectionCount > 1)
06157               {
06158                      undoManager->beginTransaction(Um::SelectionGroup, Um::IGroup, Um::FlipH, 0, Um::IFlipH);
06159                      double gx, gy, gh, gw, ix, iy, iw, ih;
06160                      m_Selection->getGroupRect(&gx, &gy, &gw, &gh);
06161                      for (uint a = 0; a < docSelectionCount; ++a)
06162                      {
06163                             PageItem* currItem=m_Selection->itemAt(a);
06164                             currItem->getBoundingRect(&ix, &iy, &iw, &ih);
06165                             double dx =  ((gw / 2.0) -  ((ix - gx) + (iw - ix) / 2.0)) * 2.0;
06166                             if (currItem->rotation() != 0.0)
06167                             {
06168                                    double ix2, iy2, iw2, ih2;
06169                                    currItem->rotateBy(currItem->rotation() * -2.0);
06170                                    currItem->setRedrawBounding();
06171                                    currItem->getBoundingRect(&ix2, &iy2, &iw2, &ih2);
06172                                    currItem->moveBy(ix-ix2, iy-iy2, true);
06173                                    currItem->setRedrawBounding();
06174                             }
06175                             if ((currItem->itemType() == PageItem::ImageFrame) || (currItem->itemType() == PageItem::TextFrame))
06176                                    currItem->flipImageH();
06177                             if (currItem->itemType() != PageItem::Line)
06178                                    MirrorPolyH(currItem);
06179                             currItem->moveBy(dx, 0, true);
06180                             currItem->setRedrawBounding();
06181                             currItem->GrStartX = currItem->width() - currItem->GrStartX;
06182                             currItem->GrEndX = currItem->width() - currItem->GrEndX;
06183                             undoManager->commit();
06184                      }
06185               }
06186               else
06187               {
06188                      for (uint a = 0; a < docSelectionCount; ++a)
06189                      {
06190                             PageItem* currItem=m_Selection->itemAt(a);
06191                             if ((currItem->itemType() == PageItem::ImageFrame) || (currItem->itemType() == PageItem::TextFrame))
06192                                    currItem->flipImageH();
06193                             if (currItem->itemType() != PageItem::Line)
06194                                    MirrorPolyH(currItem);
06195                             else
06196                             {
06197                                    double ix2, iy2, iw2, ih2, ix, iy, iw, ih;
06198                                    currItem->getBoundingRect(&ix, &iy, &iw, &ih);
06199                                    currItem->rotateBy(currItem->rotation() * -2.0);
06200                                    currItem->setRedrawBounding();
06201                                    currItem->getBoundingRect(&ix2, &iy2, &iw2, &ih2);
06202                                    currItem->moveBy(ix-ix2, iy-iy2, true);
06203                                    currItem->setRedrawBounding();
06204                             }
06205                             currItem->GrStartX = currItem->width() - currItem->GrStartX;
06206                             currItem->GrEndX = currItem->width() - currItem->GrEndX;
06207                      }
06208               }
06209               emit updateContents();
06210               changed();
06211               emit firstSelectedItemType(m_Selection->itemAt(0)->itemType());
06212        }
06213 }
06214 
06215 void ScribusDoc::itemSelection_FlipV()
06216 {
06217        uint docSelectionCount=m_Selection->count();
06218        if (docSelectionCount != 0)
06219        {
06220               if (docSelectionCount > 1)
06221               {
06222                      undoManager->beginTransaction(Um::SelectionGroup, Um::IGroup, Um::FlipV, 0, Um::IFlipV);
06223                      double gx, gy, gh, gw, ix, iy, iw, ih;
06224                      m_Selection->getGroupRect(&gx, &gy, &gw, &gh);
06225                      for (uint a = 0; a < docSelectionCount; ++a)
06226                      {
06227                             PageItem* currItem=m_Selection->itemAt(a);
06228                             currItem->getBoundingRect(&ix, &iy, &iw, &ih);
06229                             double dx =  ((gh / 2.0) -  ((iy - gy) + (ih - iy) / 2.0)) * 2.0;
06230                             if (currItem->rotation() != 0.0)
06231                             {
06232                                    double ix2, iy2, iw2, ih2;
06233                                    currItem->rotateBy(currItem->rotation() * -2.0);
06234                                    currItem->setRedrawBounding();
06235                                    currItem->getBoundingRect(&ix2, &iy2, &iw2, &ih2);
06236                                    currItem->moveBy(ix-ix2, iy-iy2, true);
06237                                    currItem->setRedrawBounding();
06238                             }
06239                             if ((currItem->itemType() == PageItem::ImageFrame) || (currItem->itemType() == PageItem::TextFrame))
06240                                    currItem->flipImageV();
06241                             if (currItem->itemType() != PageItem::Line)
06242                                    MirrorPolyV(currItem);
06243                             currItem->moveBy(0, dx, true);
06244                             currItem->setRedrawBounding();
06245                             currItem->GrStartY = currItem->height() - currItem->GrStartY;
06246                             currItem->GrEndY = currItem->height() - currItem->GrEndY;
06247                      }
06248                      emit updateContents();
06249                      undoManager->commit();
06250               }
06251               else
06252               {
06253                      for (uint a = 0; a < docSelectionCount; ++a)
06254                      {
06255                             PageItem* currItem=m_Selection->itemAt(a);
06256                             if ((currItem->itemType() == PageItem::ImageFrame) || (currItem->itemType() == PageItem::TextFrame))
06257                                    currItem->flipImageV();
06258                             if (currItem->itemType() != PageItem::Line)
06259                                    MirrorPolyV(currItem);
06260                             else
06261                             {
06262                                    double ix2, iy2, iw2, ih2, ix, iy, iw, ih;
06263                                    currItem->getBoundingRect(&ix, &iy, &iw, &ih);
06264                                    currItem->rotateBy(currItem->rotation() * -2.0);
06265                                    currItem->setRedrawBounding();
06266                                    currItem->getBoundingRect(&ix2, &iy2, &iw2, &ih2);
06267                                    currItem->moveBy(ix-ix2, iy-iy2, true);
06268                                    currItem->setRedrawBounding();
06269                             }
06270                             currItem->GrStartY = currItem->height() - currItem->GrStartY;
06271                             currItem->GrEndY = currItem->height() - currItem->GrEndY;
06272                      }
06273                      emit updateContents();
06274               }
06275               changed();
06276               emit firstSelectedItemType(m_Selection->itemAt(0)->itemType());
06277        }
06278 }
06279 
06280 void ScribusDoc::itemSelection_ChangePreviewResolution(int id)
06281 {
06282        uint selectedItemCount=m_Selection->count();
06283        if (selectedItemCount != 0)
06284        {
06285               PageItem *currItem;
06286               bool found=false;
06287               for (uint i = 0; i < selectedItemCount; ++i)
06288               {
06289                      currItem = m_Selection->itemAt(i);
06290                      if (currItem!=NULL)
06291                             if (currItem->asImageFrame())
06292                             {
06293                                    currItem->pixm.imgInfo.lowResType = id;
06294                                    if (!found)
06295                                           found=true;
06296                             }
06297               }
06298               if (!found) //No image frames in the current selection!
06299                      return;
06300               updatePic();
06301               disconnect( m_ScMW->scrActions["itemPreviewLow"], SIGNAL(activatedData(int)) , 0, 0 );
06302               disconnect( m_ScMW->scrActions["itemPreviewNormal"], SIGNAL(activatedData(int)) , 0, 0 );
06303               disconnect( m_ScMW->scrActions["itemPreviewFull"], SIGNAL(activatedData(int)) , 0, 0 );
06304               m_ScMW->scrActions["itemPreviewLow"]->setOn(id==m_ScMW->scrActions["itemPreviewLow"]->actionInt());
06305               m_ScMW->scrActions["itemPreviewNormal"]->setOn(id==m_ScMW->scrActions["itemPreviewNormal"]->actionInt());
06306               m_ScMW->scrActions["itemPreviewFull"]->setOn(id==m_ScMW->scrActions["itemPreviewFull"]->actionInt());
06307               connect( m_ScMW->scrActions["itemPreviewLow"], SIGNAL(activatedData(int)), this, SLOT(itemSelection_ChangePreviewResolution(int)) );
06308               connect( m_ScMW->scrActions["itemPreviewNormal"], SIGNAL(activatedData(int)), this, SLOT(itemSelection_ChangePreviewResolution(int)) );
06309               connect( m_ScMW->scrActions["itemPreviewFull"], SIGNAL(activatedData(int)), this, SLOT(itemSelection_ChangePreviewResolution(int)) );
06310        }
06311 }
06312 
06313 void ScribusDoc::itemSelection_ClearItem(Selection* customSelection)
06314 {
06315        Selection* itemSelection = (customSelection!=0) ? customSelection : m_Selection;
06316        assert(itemSelection!=0);
06317        uint selectedItemCount=itemSelection->count();
06318        if (selectedItemCount != 0)
06319        {
06320               PageItem *currItem;
06321               for (uint i = 0; i < selectedItemCount; ++i)
06322               {
06323                      currItem = itemSelection->itemAt(i);
06324                      if (currItem->asImageFrame())
06325                      {
06326                             if ((ScCore->fileWatcher->files().contains(currItem->Pfile) != 0) && (currItem->PicAvail))
06327                                    ScCore->fileWatcher->removeFile(currItem->Pfile);
06328                      }
06329                      else
06330                      if (currItem->asTextFrame() && ScCore->usingGUI())
06331                      {
06332                             if (currItem->itemText.length() != 0 && (currItem->nextInChain() == 0 || currItem->prevInChain() == 0))
06333                             {
06334                                    int t = ScMessageBox::warning(m_ScMW, CommonStrings::trWarning,
06335                                                                       tr("Do you really want to clear all your text?"),
06336                                                                       QMessageBox::Yes, QMessageBox::No | QMessageBox::Default);
06337                                    if (t == QMessageBox::No)
06338                                           continue;
06339                             }
06340                      }
06341                      currItem->clearContents();
06342               }
06343               updateFrameItems();
06344               emit updateContents();
06345               changed();
06346        }
06347 }
06348 
06349 void ScribusDoc::itemSelection_DeleteItem(Selection* customSelection, bool forceDeletion)
06350 {
06351        if (EditClip)
06352               return;
06353        Selection* itemSelection = (customSelection!=0) ? customSelection : m_Selection;
06354        assert(itemSelection!=0);
06355        uint selectedItemCount=itemSelection->count();
06356        if (selectedItemCount == 0)
06357               return;
06358        QPtrList<PageItem> delItems;
06359        PageItem *currItem;
06360        uint offs = 0;
06361        QString tooltip = Um::ItemsInvolved + "\n";
06362        for (uint de = 0; de < selectedItemCount; ++de)
06363        {
06364               currItem = itemSelection->itemAt(offs);
06365               if ((((currItem->isSingleSel) && (currItem->isGroupControl)) || ((currItem->isSingleSel) && (currItem->isTableItem))) || (currItem->locked()))
06366               {
06367                      offs++;
06368                      continue;
06369               }
06370               //CB FIXME remove this and include of story.h too
06371               if ((currItem->asTextFrame() || currItem->asPathText()) && currItem==m_ScMW->storyEditor->currentItem() && this==m_ScMW->storyEditor->currentDocument())
06372               {
06373                      if (forceDeletion)
06374                             m_ScMW->storyEditor->setCurrentDocumentAndItem(this, NULL);
06375                      else
06376                      {
06377                             QMessageBox::critical(m_ScMW, tr("Cannot Delete In-Use Item"), tr("The item %1 is currently being edited by Story Editor. The delete operation will be cancelled").arg(currItem->itemName()), QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton);
06378                             return;
06379                      }
06380               }
06381               tooltip += "\t" + currItem->getUName() + "\n";
06382               delItems.append(itemSelection->takeItem(offs));
06383        }
06384        if (delItems.count() == 0)
06385               return;
06386        selectedItemCount = delItems.count();
06387 
06388        if (selectedItemCount > 1)
06389               undoManager->beginTransaction(Um::Group + "/" + Um::Selection, Um::IGroup,
06390                                                                       Um::Delete, tooltip, Um::IDelete);
06391 
06392        for (uint de = 0; de < selectedItemCount; ++de)
06393        {
06394               currItem = delItems.last();
06395               if ((currItem->asImageFrame()) && ((ScCore->fileWatcher->files().contains(currItem->Pfile) != 0) && (currItem->PicAvail)))
06396                      ScCore->fileWatcher->removeFile(currItem->Pfile);
06397               if (currItem->asTextFrame())
06398               {
06399                      currItem->dropLinks();
06400                      
06401                      /* this code will instead remove the contained text
06402                      // unlink after
06403                      currItem->unlink();
06404                      if (before != 0)
06405                      {
06406                             // unlink before
06407                             before->unlink();
06408                             // repair link
06409                             if (after != 0)
06410                             {
06411                                    before->link(after);
06412                             }
06413                      }
06414                      */
06415               }
06416               if (currItem->isBookmark)
06417                      //CB From view   emit DelBM(currItem);
06418                      m_ScMW->DelBookMark(currItem);
06419               Items->remove(currItem);
06420               delItems.removeLast();
06421               // send the undo action to the UndoManager
06422               if (UndoManager::undoEnabled())
06423               {
06424                      ItemState<PageItem*> *is = new ItemState<PageItem*>(Um::Delete + " " + currItem->getUName(), "", Um::IDelete);
06425                      is->setItem(currItem);
06426                      is->set("DELETE_ITEM", "delete_item");
06427                      UndoObject *target;
06428                      if (currItem->OwnPage > -1)
06429                             target = Pages->at(currItem->OwnPage);
06430                      else
06431                             target = Pages->at(0);
06432                      undoManager->action(target, is, currItem->getUPixmap());
06433               }
06434        }
06435        updateFrameItems();
06436        renumberItemsInListOrder();
06437        if (selectedItemCount > 1)
06438               undoManager->commit();
06439        // JG resetting ElemToLink fixes #5629
06440        ElemToLink = NULL;
06441        emit updateContents();
06442        qApp->setOverrideCursor(QCursor(ArrowCursor), true);
06443        //CB FIXME remove this and tree.h too
06444 //     m_ScMW->outlinePalette->BuildTree();
06445 
06446        if (itemSelection->isGUISelection())
06447        {
06448               if (itemSelection->count() == 0)
06449                      emit firstSelectedItemType(-1);
06450               else
06451               {
06452                      //emit HaveSel(Doc->m_Selection->itemAt(0)->itemType());
06453                      itemSelection->itemAt(0)->emitAllToGUI();
06454               }
06455        }
06456        changed();
06457 }
06458 
06459 
06460 void ScribusDoc::itemSelection_SetItemFillTransparency(double t)
06461 {
06462        uint selectedItemCount=m_Selection->count();
06463        if (selectedItemCount != 0)
06464        {
06465               for (uint i = 0; i < selectedItemCount; ++i)
06466               {
06467                      PageItem *currItem = m_Selection->itemAt(i);
06468                      if (currItem->isGroupControl)
06469                             continue;
06470                      currItem->setFillTransparency(t);
06471               }
06472               emit updateContents();
06473               changed();
06474        }
06475 }
06476 
06477 void ScribusDoc::itemSelection_SetItemLineTransparency(double t)
06478 {
06479        uint selectedItemCount=m_Selection->count();
06480        if (selectedItemCount != 0)
06481        {
06482               for (uint i = 0; i < selectedItemCount; ++i)
06483               {
06484                      PageItem *currItem = m_Selection->itemAt(i);
06485                      currItem->setLineTransparency(t);
06486               }
06487               emit updateContents();
06488               changed();
06489        }
06490 }
06491 void ScribusDoc::itemSelection_SetItemFillBlend(int t)
06492 {
06493        uint selectedItemCount=m_Selection->count();
06494        if (selectedItemCount != 0)
06495        {
06496               for (uint i = 0; i < selectedItemCount; ++i)
06497               {
06498                      PageItem *currItem = m_Selection->itemAt(i);
06499                      if (currItem->isGroupControl)
06500                             continue;
06501                      currItem->setFillBlendmode(t);
06502               }
06503               emit updateContents();
06504               changed();
06505        }
06506 }
06507 
06508 void ScribusDoc::itemSelection_SetItemLineBlend(int t)
06509 {
06510        uint selectedItemCount=m_Selection->count();
06511        if (selectedItemCount != 0)
06512        {
06513               for (uint i = 0; i < selectedItemCount; ++i)
06514               {
06515                      PageItem *currItem = m_Selection->itemAt(i);
06516                      currItem->setLineBlendmode(t);
06517               }
06518               emit updateContents();
06519               changed();
06520        }
06521 }
06522 
06523 void ScribusDoc::itemSelection_SetLineGradient(VGradient& newGradient, Selection* customSelection)
06524 {
06525        Selection* itemSelection = (customSelection!=0) ? customSelection : m_Selection;
06526        assert(itemSelection!=0);
06527        uint selectedItemCount=itemSelection->count();
06528        if (selectedItemCount == 0)
06529               return;
06530 //Teaser for jghali
06531 }
06532 
06533 void ScribusDoc::itemSelection_SetFillGradient(VGradient& newGradient, Selection* customSelection)
06534 {
06535        Selection* itemSelection = (customSelection!=0) ? customSelection : m_Selection;
06536        assert(itemSelection!=0);
06537        uint selectedItemCount=itemSelection->count();
06538        if (selectedItemCount == 0)
06539               return;
06540        for (uint i = 0; i < selectedItemCount; ++i)
06541        {
06542               PageItem *currItem;
06543               currItem = itemSelection->itemAt(i);
06544               currItem->fill_gradient = newGradient;
06545               if (selectedItemCount==1)
06546                      emit refreshItem(currItem);
06547        }
06548        if (selectedItemCount>1)
06549               emit updateContents();
06550        changed();
06551 }
06552 
06553 void ScribusDoc::itemSelection_DoHyphenate()
06554 {
06555        uint selectedItemCount=m_Selection->count();
06556        if (selectedItemCount != 0)
06557        {
06558               for (uint i = 0; i < selectedItemCount; ++i)
06559               {
06560                      PageItem *currItem = m_Selection->itemAt(i);
06561                      docHyphenator->slotHyphenate(currItem);
06562               }
06563               m_View->DrawNew(); //CB draw new until NLS for redraw through text chains
06564               changed();
06565        }
06566 }
06567 
06568 void ScribusDoc::itemSelection_DoDeHyphenate()
06569 {
06570        uint selectedItemCount=m_Selection->count();
06571        if (selectedItemCount != 0)
06572        {
06573               for (uint i = 0; i < selectedItemCount; ++i)
06574               {
06575                      PageItem *currItem = m_Selection->itemAt(i);
06576                      docHyphenator->slotDeHyphenate(currItem);
06577               }
06578               m_View->DrawNew(); //CB draw new until NLS for redraw through text chains
06579               changed();
06580        }
06581 }
06582 
06583 
06584 void ScribusDoc::itemSelection_SendToLayer(int layerNumber)
06585 {
06586        uint selectedItemCount=m_Selection->count();
06587        if (selectedItemCount != 0)
06588        {
06589               if (UndoManager::undoEnabled() && selectedItemCount > 1)
06590                      undoManager->beginTransaction();
06591               QString tooltip = Um::ItemsInvolved + "\n";
06592               for (uint a = 0; a < selectedItemCount; ++a)
06593               {
06594                      PageItem *currItem = m_Selection->itemAt(a);
06595                      currItem->setLayer(layerNumber);
06596                      tooltip += "\t" + currItem->getUName() + "\n";
06597               }
06598               if (UndoManager::undoEnabled() && selectedItemCount > 1)
06599                      undoManager->commit(Um::Selection,
06600                                                         Um::IGroup,
06601                                                         Um::SendToLayer,
06602                                                         tooltip,
06603                                                         Um::ILayerAction);
06604        }
06605 
06606        //CB why not just the following as we are calling for updatecontents anyway and we arent reflowing text
06607        //Doc->m_Selection->clear();
06608        m_View->Deselect(true);
06609        emit updateContents();
06610        changed();
06611 }
06612 
06613 
06614 void ScribusDoc::itemSelection_SetAlignment(int s, Selection* customSelection)
06615 {
06616        ParagraphStyle newStyle;
06617        newStyle.setAlignment(static_cast<ParagraphStyle::AlignmentType>(s));
06618        itemSelection_ApplyParagraphStyle(newStyle, customSelection);
06619 }
06620 
06621 
06622 void ScribusDoc::itemSelection_SetImageOffset(double x, double y, Selection* customSelection)
06623 {
06624        Selection* itemSelection = (customSelection!=0) ? customSelection : m_Selection;
06625        assert(itemSelection!=0);
06626        uint selectedItemCount=itemSelection->count();
06627        if (selectedItemCount != 0)
06628        {
06629               if (UndoManager::undoEnabled() && selectedItemCount > 1)
06630                      undoManager->beginTransaction();
06631               QString tooltip = Um::ItemsInvolved + "\n";
06632               for (uint a = 0; a < selectedItemCount; ++a)
06633               {
06634                      PageItem *currItem = itemSelection->itemAt(a);
06635                      currItem->setImageXYOffset(x, y);
06636                      if (currItem->imageClip.size() != 0)
06637                      {
06638                             currItem->imageClip = currItem->pixm.imgInfo.PDSpathData[currItem->pixm.imgInfo.usedPath].copy();
06639                             QWMatrix cl;
06640                             cl.translate(currItem->imageXOffset()*currItem->imageXScale(), currItem->imageYOffset()*currItem->imageYScale());
06641                             cl.scale(currItem->imageXScale(), currItem->imageYScale());
06642                             currItem->imageClip.map(cl);
06643                      }
06644                      tooltip += "\t" + currItem->getUName() + "\n";
06645                      emit refreshItem(currItem);
06646               }
06647               if (UndoManager::undoEnabled() && selectedItemCount > 1)
06648                      undoManager->commit(Um::Selection,
06649                                                         Um::IGroup,
06650                                                         Um::ImageOffset,
06651                                                         tooltip,
06652                                                         Um::IImageScaling);
06653               changed();
06654        }
06655 }
06656 
06657 void ScribusDoc::itemSelection_SetImageScale(double x, double y, Selection* customSelection)
06658 {
06659        Selection* itemSelection = (customSelection!=0) ? customSelection : m_Selection;
06660        assert(itemSelection!=0);
06661        uint selectedItemCount=itemSelection->count();
06662        if (selectedItemCount != 0)
06663        {
06664               if (UndoManager::undoEnabled() && selectedItemCount > 1)
06665                      undoManager->beginTransaction();
06666               QString tooltip = Um::ItemsInvolved + "\n";
06667               for (uint a = 0; a < selectedItemCount; ++a)
06668               {
06669                      PageItem *currItem = itemSelection->itemAt(a);
06670                      currItem->setImageXYScale(x, y);
06671                      if (currItem->imageClip.size() != 0)
06672                      {
06673                             currItem->imageClip = currItem->pixm.imgInfo.PDSpathData[currItem->pixm.imgInfo.usedPath].copy();
06674                             QWMatrix cl;
06675                             cl.translate(currItem->imageXOffset()*currItem->imageXScale(), currItem->imageYOffset()*currItem->imageYScale());
06676                             cl.scale(currItem->imageXScale(), currItem->imageYScale());
06677                             currItem->imageClip.map(cl);
06678                      }
06679                      tooltip += "\t" + currItem->getUName() + "\n";
06680                      emit refreshItem(currItem);
06681               }
06682               if (UndoManager::undoEnabled() && selectedItemCount > 1)
06683                      undoManager->commit(Um::Selection,
06684                                                         Um::IGroup,
06685                                                         Um::ImageScale,
06686                                                         tooltip,
06687                                                         Um::IImageScaling);
06688               changed();
06689        }
06690 }
06691 
06692 void ScribusDoc::itemSelection_SetImageScaleAndOffset(double sx, double sy, double ox, double oy, Selection* customSelection)
06693 {
06694        Selection* itemSelection = (customSelection!=0) ? customSelection : m_Selection;
06695        assert(itemSelection!=0);
06696        uint selectedItemCount=itemSelection->count();
06697        if (selectedItemCount == 0)
06698               return;
06699        
06700        if (UndoManager::undoEnabled() && selectedItemCount > 1)
06701               undoManager->beginTransaction();
06702        QString tooltip = Um::ItemsInvolved + "\n";
06703        for (uint a = 0; a < selectedItemCount; ++a)
06704        {
06705               PageItem *currItem = itemSelection->itemAt(a);
06706               if (UndoManager::undoEnabled())
06707                      undoManager->beginTransaction();
06708               currItem->setImageXYScale(sx, sy);
06709               currItem->setImageXYOffset(ox/sx, oy/sy);
06710               if (currItem->imageClip.size() != 0)
06711               {
06712                      currItem->imageClip = currItem->pixm.imgInfo.PDSpathData[currItem->pixm.imgInfo.usedPath].copy();
06713                      QWMatrix cl;
06714                      cl.translate(currItem->imageXOffset()*currItem->imageXScale(), currItem->imageYOffset()*currItem->imageYScale());
06715                      cl.scale(currItem->imageXScale(), currItem->imageYScale());
06716                      currItem->imageClip.map(cl);
06717               }
06718               tooltip += "\t" + currItem->getUName() + "\n";
06719               if (UndoManager::undoEnabled())
06720               undoManager->commit(Um::Selection,
06721                                                  Um::IImageFrame,
06722                                                  Um::ImageScale,
06723                                                  tooltip,
06724                                                  Um::IImageScaling);
06725               emit refreshItem(currItem);
06726        }
06727        if (UndoManager::undoEnabled() && selectedItemCount > 1)
06728               undoManager->commit(Um::Selection,
06729                                                  Um::IGroup,
06730                                                  Um::ImageScale,
06731                                                  tooltip,
06732                                                  Um::IImageScaling);
06733        changed();
06734 }
06735 
06736 void ScribusDoc::buildAlignItemList(Selection* customSelection)
06737 {
06738        //CB TODO Handling custom selections
06739        //Selection* itemSelection = (customSelection!=0) ? customSelection : m_Selection;
06740        Selection* itemSelection = m_Selection;
06741        assert(itemSelection!=0);
06742        uint selectedItemCount=itemSelection->count();
06743        PageItem *currItem;
06744        int ObjGroup;
06745        struct AlignObjs Object;
06746        AObjects.clear();
06747        for (uint a = 0; a < selectedItemCount; ++a)
06748        {
06749               currItem = itemSelection->itemAt(a);
06750               Object.Objects.clear();
06751               currItem->getBoundingRect(&Object.x1, &Object.y1, &Object.x2, &Object.y2);
06752               if (currItem->Groups.count() > 0)
06753               {
06754                      ObjGroup = currItem->Groups.top();
06755                      bool found = false;
06756                      for (uint a2 = 0; a2 < AObjects.count(); ++a2)
06757                      {
06758                             if (AObjects[a2].Group == ObjGroup)
06759                             {
06760                                    AObjects[a2].x1 = QMIN(AObjects[a2].x1, Object.x1);
06761                                    AObjects[a2].y1 = QMIN(AObjects[a2].y1, Object.y1);
06762                                    AObjects[a2].x2 = QMAX(AObjects[a2].x2, Object.x2);
06763                                    AObjects[a2].y2 = QMAX(AObjects[a2].y2, Object.y2);
06764                                    AObjects[a2].Objects.append(currItem);
06765                                    found = true;
06766                                    break;
06767                             }
06768                      }
06769                      if (!found)
06770                      {
06771                             Object.Group = ObjGroup;
06772                             Object.ObjNr = 0;
06773                             Object.Objects.append(currItem);
06774                             AObjects.append(Object);
06775                      }
06776               }
06777               else
06778               {
06779                      Object.Group = 0;
06780                      Object.ObjNr = currItem->ItemNr;
06781                      Object.Objects.append(currItem);
06782                      AObjects.append(Object);
06783               }
06784        }
06785        for (uint i = 0; i < AObjects.count(); ++i)
06786        {
06787               AObjects[i].width = AObjects[i].x2 - AObjects[i].x1;
06788               AObjects[i].height = AObjects[i].y2 - AObjects[i].y1;
06789        }
06790 }
06791 
06792 bool ScribusDoc::startAlign()
06793 {
06794        buildAlignItemList();
06795        uint alignObjectsCount=AObjects.count();
06796        if (alignObjectsCount==0)
06797               return false;
06798               
06799        bool oneLocked=false;
06800        for (uint i = 0; i < alignObjectsCount && !oneLocked; ++i)
06801               for (uint j = 0; j < AObjects[i].Objects.count() && !oneLocked; ++j)
06802                      if (AObjects[i].Objects.at(j)->locked())
06803                             oneLocked=true;
06804        int t = 2;
06805        if (oneLocked)
06806        {
06807               t = ScMessageBox::warning(m_ScMW, CommonStrings::trWarning, tr("Some objects are locked."),
06808                                                                tr("&Unlock All"), tr("&Skip locked objects"), CommonStrings::tr_Cancel, 0, 0);
06809               if (t == 2)
06810                      return false;
06811        }
06812        
06813        QString targetTooltip = Um::ItemsInvolved + "\n";
06814        for (uint i = 0; i < m_Selection->count(); ++i)
06815               targetTooltip += "\t" + m_Selection->itemAt(i)->getUName() + "\n";
06816        // Make the align action a single action in Action History
06817        undoManager->beginTransaction(Um::Selection, 0, Um::AlignDistribute, targetTooltip, Um::IAlignDistribute);
06818        if (oneLocked && (t == 0))
06819        {
06820               for (uint i = 0; i < alignObjectsCount; ++i)
06821                      for (uint j = 0; j < AObjects[i].Objects.count(); ++j)
06822                             if (AObjects[i].Objects.at(j)->locked())
06823                                    AObjects[i].Objects.at(j)->setLocked(false);
06824        }
06825        return true;
06826 }
06827 
06828 void ScribusDoc::endAlign()
06829 {
06830        changed();
06831        m_ScMW->HaveNewSel(m_Selection->itemAt(0)->itemType());
06832        for (uint i = 0; i < m_Selection->count(); ++i)
06833               setRedrawBounding(m_Selection->itemAt(i));
06834        undoManager->commit(); // commit and send the action to the UndoManager
06835        m_View->updateContents();
06836 }
06837 
06838 
06839 void ScribusDoc::itemSelection_AlignLeftOut(AlignTo currAlignTo, double guidePosition)
06840 {
06841        if (!startAlign())
06842               return;
06843        uint alignObjectsCount=AObjects.count();
06844        int loopStart=0, loopEnd=alignObjectsCount;
06845        double newX = 99999.9;
06846        switch ( currAlignTo )
06847        {
06848               case alignFirst:
06849                      newX = AObjects[0].x1;
06850                      loopStart=1;
06851                      break;
06852               case alignLast:
06853                      newX = AObjects[alignObjectsCount-1].x1;
06854                      loopEnd=alignObjectsCount-2;
06855                      break;
06856               case alignPage:
06857                      newX = currentPage()->xOffset();
06858                      break;
06859               case alignMargins:
06860                      newX = currentPage()->xOffset();
06861                      newX += currentPage()->Margins.Left;
06862                      break;
06863               case alignGuide:
06864                      newX=currentPage()->xOffset() + guidePosition;
06865                      break;
06866               case alignSelection:
06867                      for (uint a = 0; a < alignObjectsCount; ++a)
06868                             newX = QMIN(AObjects[a].x1, newX);
06869                      break;
06870        }
06871        for (int i = loopStart; i <= loopEnd; ++i)
06872        {
06873               double diff=newX-AObjects[i].x2;
06874               for (uint j = 0; j < AObjects[i].Objects.count(); ++j)
06875                      if (!AObjects[i].Objects.at(j)->locked())
06876                             AObjects[i].Objects.at(j)->moveBy(diff, 0.0);
06877        }
06878        endAlign();
06879 }
06880 
06881 void ScribusDoc::itemSelection_AlignLeftIn(AlignTo currAlignTo, double guidePosition)
06882 {
06883        if (!startAlign())
06884               return;
06885        uint alignObjectsCount=AObjects.count();
06886        int loopStart=0, loopEnd=alignObjectsCount;
06887        double newX = 99999.9;
06888        switch ( currAlignTo ) 
06889        {
06890               case alignFirst:
06891                      newX = AObjects[0].x1;
06892                      loopStart=1;
06893                      break;
06894               case alignLast:
06895                      newX = AObjects[alignObjectsCount-1].x1;
06896                      loopEnd=alignObjectsCount-2;
06897                      break;
06898               case alignPage:
06899                      newX = currentPage()->xOffset();
06900                      break;
06901               case alignMargins:
06902                      newX = currentPage()->xOffset();
06903                      newX += currentPage()->Margins.Left;
06904                      break;
06905               case alignGuide:
06906                      newX=currentPage()->xOffset() + guidePosition;
06907                      break;
06908               case alignSelection:
06909                      for (uint a = 0; a < alignObjectsCount; ++a)
06910                             newX = QMIN(AObjects[a].x1, newX);
06911                      break;
06912        }
06913        for (int i = loopStart; i <= loopEnd; ++i)
06914        {
06915               double diff=newX-AObjects[i].x1;
06916               for (uint j = 0; j < AObjects[i].Objects.count(); ++j)
06917                      if (!AObjects[i].Objects.at(j)->locked())
06918                             AObjects[i].Objects.at(j)->moveBy(diff, 0.0);
06919        }
06920        endAlign();
06921 }
06922 
06923 void ScribusDoc::itemSelection_AlignCenterHor(AlignTo currAlignTo, double guidePosition)
06924 {
06925        if (!startAlign())
06926               return;
06927        uint alignObjectsCount=AObjects.count();
06928        int loopStart=0, loopEnd=alignObjectsCount;
06929        double newX = 0.0;
06930        switch ( currAlignTo ) 
06931        {
06932               case alignFirst:
06933                      newX = AObjects[0].x1 + (AObjects[0].width)/2;
06934                      loopStart=1;
06935                      break;
06936               case alignLast:
06937                      {
06938                             int objindex=alignObjectsCount-1;
06939                             newX = AObjects[objindex].x1 + (AObjects[objindex].width)/2;
06940                             loopEnd=alignObjectsCount-2;
06941                      }
06942                      break;
06943               case alignPage:
06944                      newX = currentPage()->xOffset();
06945                      newX += currentPage()->width()/2;
06946                      break;
06947               case alignMargins:
06948                      newX = currentPage()->xOffset();
06949                      newX += currentPage()->Margins.Left;
06950                      newX += (currentPage()->width() - currentPage()->Margins.Right - currentPage()->Margins.Left)/2;
06951                      break;
06952               case alignGuide:
06953                      newX=currentPage()->xOffset() + guidePosition;
06954                      break;
06955               case alignSelection:
06956                      double minX=99999.9, maxX=-99999.9;
06957                      for (uint a = 0; a < alignObjectsCount; ++a)
06958                      {
06959                             minX = QMIN(AObjects[a].x1, minX);
06960                             maxX = QMAX(AObjects[a].x2, maxX);
06961                      }
06962                      newX = minX + (maxX-minX)/2;
06963                      break;
06964        }
06965        for (int i = loopStart; i <= loopEnd; ++i)
06966        {
06967               double diff=newX-AObjects[i].x1-(AObjects[i].width)/2;
06968               for (uint j = 0; j < AObjects[i].Objects.count(); ++j)
06969                      if (!AObjects[i].Objects.at(j)->locked())
06970                             AObjects[i].Objects.at(j)->moveBy(diff, 0.0);
06971        }
06972        endAlign();
06973 }
06974 
06975 void ScribusDoc::itemSelection_AlignRightIn(AlignTo currAlignTo, double guidePosition)
06976 {
06977        if (!startAlign())
06978               return;
06979        uint alignObjectsCount=AObjects.count();
06980        int loopStart=0, loopEnd=alignObjectsCount;
06981        double newX = -99999.9;
06982        switch ( currAlignTo ) 
06983        {
06984               case alignFirst:
06985                      newX = AObjects[0].x2;
06986                      loopStart=1;
06987                      break;
06988               case alignLast:
06989                      newX = AObjects[alignObjectsCount-1].x2;
06990                      loopEnd=alignObjectsCount-2;
06991                      break;
06992               case alignPage:
06993                      newX = currentPage()->xOffset();
06994                      newX += currentPage()->width();;
06995                      break;
06996               case alignMargins:
06997                      newX = currentPage()->xOffset();
06998                      newX += currentPage()->width();;
06999                      newX -= currentPage()->Margins.Right;
07000                      break;
07001               case alignGuide:
07002                      newX=currentPage()->xOffset() + guidePosition;
07003                      break;
07004               case alignSelection:
07005                      for (uint a = 0; a < alignObjectsCount; ++a)
07006                             newX = QMAX(AObjects[a].x2, newX);
07007                      break;
07008        }
07009        for (int i = loopStart; i <= loopEnd; ++i)
07010        {
07011               double diff=newX-AObjects[i].x2;
07012               for (uint j = 0; j < AObjects[i].Objects.count(); ++j)
07013                      if (!AObjects[i].Objects.at(j)->locked())
07014                             AObjects[i].Objects.at(j)->moveBy(diff, 0.0);
07015        }
07016        endAlign();
07017 }
07018 
07019 void ScribusDoc::itemSelection_AlignRightOut(AlignTo currAlignTo, double guidePosition)
07020 {
07021        if (!startAlign())
07022               return;
07023        uint alignObjectsCount=AObjects.count();
07024        int loopStart=0, loopEnd=alignObjectsCount;
07025        double newX = -99999.9;
07026        switch ( currAlignTo ) 
07027        {
07028               case alignFirst:
07029                      newX = AObjects[0].x2;
07030                      loopStart=1;
07031                      break;
07032               case alignLast:
07033                      newX = AObjects[alignObjectsCount-1].x2;
07034                      loopEnd=alignObjectsCount-2;
07035                      break;
07036               case alignPage:
07037                      newX = currentPage()->xOffset();
07038                      newX += currentPage()->width();
07039                      break;
07040               case alignMargins:
07041                      newX = currentPage()->xOffset();
07042                      newX += currentPage()->width();
07043                      newX -= currentPage()->Margins.Right;
07044                      break;
07045               case alignGuide:
07046                      newX=currentPage()->xOffset() + guidePosition;
07047                      break;
07048               case alignSelection:
07049                      for (uint a = 0; a < alignObjectsCount; ++a)
07050                             newX = QMAX(AObjects[a].x2, newX);
07051                      break;
07052        }
07053        for (int i = loopStart; i <= loopEnd; ++i)
07054        {
07055               double diff=newX-AObjects[i].x1;
07056               for (uint j = 0; j < AObjects[i].Objects.count(); ++j)
07057                      if (!AObjects[i].Objects.at(j)->locked())
07058                             AObjects[i].Objects.at(j)->moveBy(diff, 0.0);
07059        }
07060        endAlign();
07061 }
07062 
07063 void ScribusDoc::itemSelection_AlignTopOut(AlignTo currAlignTo, double guidePosition)
07064 {
07065        if (!startAlign())
07066               return;
07067        uint alignObjectsCount=AObjects.count();
07068        int loopStart=0, loopEnd=alignObjectsCount;
07069        double newY = 99999.9;
07070        switch ( currAlignTo ) 
07071        {
07072               case alignFirst:
07073                      newY = AObjects[0].y1;
07074                      loopStart=1;
07075                      break;
07076               case alignLast:
07077                      newY = AObjects[alignObjectsCount-1].y1;
07078                      loopEnd=alignObjectsCount-2;
07079                      break;
07080               case alignPage:
07081                      newY = currentPage()->yOffset();
07082                      break;
07083               case alignMargins:
07084                      newY = currentPage()->yOffset();
07085                      newY += currentPage()->Margins.Top;
07086                      break;
07087               case alignGuide:
07088                      newY=currentPage()->yOffset() + guidePosition;
07089                      break;
07090               case alignSelection:
07091                      for (uint a = 0; a < alignObjectsCount; ++a)
07092                             newY = QMIN(AObjects[a].y1, newY);
07093                      break;
07094        }
07095        for (int i = loopStart; i <= loopEnd; ++i)
07096        {
07097               double diff=newY-AObjects[i].y2;
07098               for (uint j = 0; j < AObjects[i].Objects.count(); ++j)
07099                      if (!AObjects[i].Objects.at(j)->locked())
07100                             AObjects[i].Objects.at(j)->moveBy(0.0, diff);
07101        }
07102        endAlign();
07103 }
07104 
07105 void ScribusDoc::itemSelection_AlignTopIn(AlignTo currAlignTo, double guidePosition)
07106 {
07107        if (!startAlign())
07108               return;
07109        uint alignObjectsCount=AObjects.count();
07110        int loopStart=0, loopEnd=alignObjectsCount;
07111        double newY = 99999.9;
07112        switch ( currAlignTo ) 
07113        {
07114               case alignFirst:
07115                      newY = AObjects[0].y1;
07116                      loopStart=1;
07117                      break;
07118               case alignLast:
07119                      newY = AObjects[alignObjectsCount-1].y1;
07120                      loopEnd=alignObjectsCount-2;
07121                      break;
07122               case alignPage:
07123                      newY = currentPage()->yOffset();
07124                      break;
07125               case alignMargins:
07126                      newY = currentPage()->yOffset();
07127                      newY += currentPage()->Margins.Top;
07128                      break;
07129               case alignGuide:
07130                      newY=currentPage()->yOffset() + guidePosition;
07131                      break;
07132               case alignSelection:
07133                      for (uint a = 0; a < alignObjectsCount; ++a)
07134                             newY = QMIN(AObjects[a].y1, newY);
07135                      break;
07136        }
07137        for (int i = loopStart; i <= loopEnd; ++i)
07138        {
07139               double diff=newY-AObjects[i].y1;
07140               for (uint j = 0; j < AObjects[i].Objects.count(); ++j)
07141                      if (!AObjects[i].Objects.at(j)->locked())
07142                             AObjects[i].Objects.at(j)->moveBy(0.0, diff);
07143        }
07144        endAlign();
07145 }
07146 
07147 
07148 void ScribusDoc::itemSelection_AlignCenterVer(AlignTo currAlignTo, double guidePosition)
07149 {
07150        if (!startAlign())
07151               return;
07152        uint alignObjectsCount=AObjects.count();
07153        int loopStart=0, loopEnd=alignObjectsCount;
07154        double newY = 0.0;
07155        switch ( currAlignTo ) 
07156        {
07157               case alignFirst:
07158                      newY = AObjects[0].y1 + (AObjects[0].height)/2;
07159                      loopStart=1;
07160                      break;
07161               case alignLast:
07162                      {
07163                             int objindex=alignObjectsCount-1;
07164                             newY = AObjects[objindex].y1 + (AObjects[objindex].height)/2;
07165                             loopEnd=alignObjectsCount-2;
07166                      }
07167                      break;
07168               case alignPage:
07169                      newY = currentPage()->yOffset();
07170                      newY += currentPage()->height()/2;
07171                      break;
07172               case alignMargins:
07173                      newY = currentPage()->yOffset();
07174                      newY += currentPage()->Margins.Top;
07175                      newY += (currentPage()->height() - currentPage()->Margins.Bottom - currentPage()->Margins.Top)/2;
07176                      break;
07177               case alignGuide:
07178                      newY=currentPage()->yOffset() + guidePosition;
07179                      break;
07180               case alignSelection:
07181                      double minY=99999.9, maxY=-99999.9;
07182                      for (uint a = 0; a < alignObjectsCount; ++a)
07183                      {
07184                             minY = QMIN(AObjects[a].y1, minY);
07185                             maxY = QMAX(AObjects[a].y2, maxY);
07186                      }
07187                      newY = minY + (maxY-minY)/2;
07188                      break;
07189        }
07190        for (int i = loopStart; i <= loopEnd; ++i)
07191        {
07192               double diff=newY-AObjects[i].y1-(AObjects[i].height)/2;
07193               for (uint j = 0; j < AObjects[i].Objects.count(); ++j)
07194                      if (!AObjects[i].Objects.at(j)->locked())
07195                             AObjects[i].Objects.at(j)->moveBy(0.0, diff);
07196        }
07197        endAlign();
07198 }
07199 
07200 
07201 void ScribusDoc::itemSelection_AlignBottomIn(AlignTo currAlignTo, double guidePosition)
07202 {
07203        if (!startAlign())
07204               return;
07205        uint alignObjectsCount=AObjects.count();
07206        int loopStart=0, loopEnd=alignObjectsCount;
07207        double newY = -99999.9;
07208        switch ( currAlignTo ) 
07209        {
07210               case alignFirst:
07211                      newY = AObjects[0].y2;
07212                      loopStart=1;
07213                      break;
07214               case alignLast:
07215                      newY = AObjects[alignObjectsCount-1].y2;
07216                      loopEnd=alignObjectsCount-2;
07217                      break;
07218               case alignPage:
07219                      newY = currentPage()->yOffset();
07220                      newY += currentPage()->height();
07221                      break;
07222               case alignMargins:
07223                      newY = currentPage()->yOffset();
07224                      newY += currentPage()->height();
07225                      newY -= currentPage()->Margins.Bottom;
07226                      break;
07227               case alignGuide:
07228                      newY=currentPage()->yOffset() + guidePosition;
07229                      break;
07230               case alignSelection:
07231                      for (uint a = 0; a < alignObjectsCount; ++a)
07232                             newY = QMAX(AObjects[a].y2, newY);
07233                      break;
07234        }
07235        for (int i = loopStart; i <= loopEnd; ++i)
07236        {
07237               double diff=newY-AObjects[i].y2;
07238               for (uint j = 0; j < AObjects[i].Objects.count(); ++j)
07239                      if (!AObjects[i].Objects.at(j)->locked())
07240                             AObjects[i].Objects.at(j)->moveBy(0.0, diff);
07241        }
07242        endAlign();
07243 }
07244 
07245 void ScribusDoc::itemSelection_AlignBottomOut(AlignTo currAlignTo, double guidePosition)
07246 {
07247        if (!startAlign())
07248               return;
07249        uint alignObjectsCount=AObjects.count();
07250        int loopStart=0, loopEnd=alignObjectsCount;
07251        double newY = -99999.9;
07252        switch ( currAlignTo )
07253        {
07254               case alignFirst:
07255                      newY = AObjects[0].y2;
07256                      loopStart=1;
07257                      break;
07258               case alignLast:
07259                      newY = AObjects[alignObjectsCount-1].y2;
07260                      loopEnd=alignObjectsCount-2;
07261                      break;
07262               case alignPage:
07263                      newY = currentPage()->yOffset();
07264                      newY += currentPage()->height();
07265                      break;
07266               case alignMargins:
07267                      newY = currentPage()->yOffset();
07268                      newY += currentPage()->height();
07269                      newY -= currentPage()->Margins.Bottom;
07270                      break;
07271               case alignGuide:
07272                      newY=currentPage()->yOffset() + guidePosition;
07273                      break;
07274               case alignSelection:
07275                      for (uint a = 0; a < alignObjectsCount; ++a)
07276                             newY = QMAX(AObjects[a].y2, newY);
07277                      break;
07278        }
07279        for (int i = loopStart; i <= loopEnd; ++i)
07280        {
07281               double diff=newY-AObjects[i].y1;
07282               for (uint j = 0; j < AObjects[i].Objects.count(); ++j)
07283                      if (!AObjects[i].Objects.at(j)->locked())
07284                             AObjects[i].Objects.at(j)->moveBy(0.0, diff);
07285        }
07286        endAlign();
07287 }
07288 
07289 
07290 void ScribusDoc::itemSelection_DistributeLeft()
07291 {
07292        if (!startAlign())
07293               return;
07294        uint alignObjectsCount=AObjects.count();
07295        if (alignObjectsCount<=1)
07296               return;
07297        QMap<double,uint> Xsorted;
07298        for (uint a = 0; a < alignObjectsCount; ++a)
07299               Xsorted.insert(AObjects[a].x1, a, false);
07300               
07301        QMap<double,uint>::Iterator it = Xsorted.begin();
07302        QMap<double,uint>::Iterator itend = Xsorted.end();
07303        double minX=it.key();
07304        double maxX=it.key();
07305        while ( it != itend)
07306        {
07307               if (minX>it.key())
07308                      minX=it.key();
07309               if (maxX<it.key())
07310                      maxX=it.key();
07311               ++it;
07312        }
07313               
07314        double separation=(maxX-minX)/static_cast<double>(alignObjectsCount-1);
07315        int i=0;
07316        for ( QMap<double,uint>::Iterator it = Xsorted.begin(); it != Xsorted.end(); ++it )
07317        {
07318               double diff=minX + i*separation-AObjects[it.data()].x1;
07319               for (uint j = 0; j < AObjects[it.data()].Objects.count(); ++j)
07320                      if (!AObjects[it.data()].Objects.at(j)->locked())
07321                             AObjects[it.data()].Objects.at(j)->moveBy(diff, 0.0);
07322               i++;
07323        }
07324        endAlign();
07325 }
07326 
07327 void ScribusDoc::itemSelection_DistributeCenterH()
07328 {
07329        if (!startAlign())
07330               return;
07331        uint alignObjectsCount=AObjects.count();
07332        if (alignObjectsCount<=1)
07333               return;
07334        QMap<double,uint> Xsorted;
07335        for (uint a = 0; a < alignObjectsCount; ++a)
07336               Xsorted.insert(AObjects[a].x1+(AObjects[a].width)/2, a, false);
07337               
07338        QMap<double,uint>::Iterator it = Xsorted.begin();
07339        QMap<double,uint>::Iterator itend = Xsorted.end();
07340        double minX=it.key();
07341        double maxX=it.key();
07342        while ( it != itend)
07343        {
07344               if (minX>it.key())
07345                      minX=it.key();
07346               if (maxX<it.key())
07347                      maxX=it.key();
07348               ++it;
07349        }
07350               
07351        double separation=(maxX-minX)/static_cast<double>(alignObjectsCount-1);
07352        int i=0;
07353        for ( QMap<double,uint>::Iterator it = Xsorted.begin(); it != Xsorted.end(); ++it )
07354        {
07355               double diff=minX + i*separation-AObjects[it.data()].x1-(AObjects[it.data()].width)/2;
07356               for (uint j = 0; j < AObjects[it.data()].Objects.count(); ++j)
07357                      if (!AObjects[it.data()].Objects.at(j)->locked())
07358                             AObjects[it.data()].Objects.at(j)->moveBy(diff, 0.0);
07359               i++;
07360        }
07361        endAlign();
07362 }
07363 
07364 void ScribusDoc::itemSelection_DistributeRight()
07365 {
07366        if (!startAlign())
07367               return;
07368        uint alignObjectsCount=AObjects.count();
07369        if (alignObjectsCount<=1)
07370               return;
07371        QMap<double,uint> Xsorted;
07372        for (uint a = 0; a < alignObjectsCount; ++a)
07373               Xsorted.insert(AObjects[a].x2, a, false);
07374               
07375        QMap<double,uint>::Iterator it = Xsorted.begin();
07376        QMap<double,uint>::Iterator itend = Xsorted.end();
07377        double minX=it.key();
07378        double maxX=it.key();
07379        while ( it != itend)
07380        {
07381               if (minX>it.key())
07382                      minX=it.key();
07383               if (maxX<it.key())
07384                      maxX=it.key();
07385               ++it;
07386        }
07387        
07388        double separation=(maxX-minX)/static_cast<double>(alignObjectsCount-1);
07389        int i=0;
07390        for ( QMap<double,uint>::Iterator it = Xsorted.begin(); it != Xsorted.end(); ++it )
07391        {
07392               double diff=minX + i*separation-AObjects[it.data()].x2;
07393               for (uint j = 0; j < AObjects[it.data()].Objects.count(); ++j)
07394                      if (!AObjects[it.data()].Objects.at(j)->locked())
07395                             AObjects[it.data()].Objects.at(j)->moveBy(diff, 0.0);
07396               i++;
07397        }
07398        endAlign();
07399 }
07400 
07401 void ScribusDoc::itemSelection_DistributeDistH(bool usingDistance, double distance)
07402 {
07403        if (!startAlign())
07404               return;
07405        uint alignObjectsCount=AObjects.count();
07406        if (alignObjectsCount<=1)
07407               return;
07408        QMap<double,uint> X1sorted, X2sorted;
07409        for (uint a = 0; a < alignObjectsCount; ++a)
07410        {
07411               X1sorted.insert(AObjects[a].x1, a, false);
07412               X2sorted.insert(AObjects[a].x2, a, false);
07413        }      
07414        uint left=X1sorted.begin().data();
07415        uint right=X2sorted[X2sorted.keys().back()];
07416        double minX=AObjects[left].x2;
07417        double separation=0.0;
07418        if (!usingDistance)
07419        {
07420               double maxX=AObjects[right].x1;
07421               double totalSpace=maxX-minX;
07422               double totalWidth=0;
07423               uint insideObjectCount=0;
07424               for (uint a = 0; a < alignObjectsCount; ++a)
07425               {
07426                      if (a==left)
07427                             continue;
07428                      if (a==right)
07429                             continue;
07430                      totalWidth += AObjects[a].width;
07431                      ++insideObjectCount;
07432               }
07433               separation=(totalSpace-totalWidth)/(insideObjectCount+1);
07434        }
07435        else
07436               separation=value2pts(distance, unitIndex());
07437        double currX=minX;
07438        for ( QMap<double,uint>::Iterator it = X1sorted.begin(); it != X1sorted.end(); ++it )
07439        {
07440               if (it.data()==left)
07441                      continue;
07442               if (it.data()==right && !usingDistance)
07443                      continue;
07444               currX+=separation;
07445 
07446               double diff=currX-AObjects[it.data()].x1;
07447               for (uint j = 0; j < AObjects[it.data()].Objects.count(); ++j)
07448                      if (!AObjects[it.data()].Objects.at(j)->locked())
07449                             AObjects[it.data()].Objects.at(j)->moveBy(diff, 0.0);
07450               currX+=AObjects[it.data()].width;
07451        }
07452        endAlign();
07453 }
07454 
07455 void ScribusDoc::itemSelection_DistributeBottom()
07456 {
07457        if (!startAlign())
07458               return;
07459        uint alignObjectsCount=AObjects.count();
07460        if (alignObjectsCount<=1)
07461               return;
07462        QMap<double,uint> Ysorted;
07463        for (uint a = 0; a < alignObjectsCount; ++a)
07464               Ysorted.insert(AObjects[a].y2, a, false);
07465               
07466        QMap<double,uint>::Iterator it = Ysorted.begin();
07467        QMap<double,uint>::Iterator itend = Ysorted.end();
07468        double minY=it.key();
07469        double maxY=it.key();
07470        while ( it != itend)
07471        {
07472               if (minY>it.key())
07473                      minY=it.key();
07474               if (maxY<it.key())
07475                      maxY=it.key();
07476               ++it;
07477        }
07478               
07479        double separation=(maxY-minY)/static_cast<double>(alignObjectsCount-1);
07480        int i=0;
07481        for ( QMap<double,uint>::Iterator it = Ysorted.begin(); it != Ysorted.end(); ++it )
07482        {
07483               double diff=minY + i*separation-AObjects[it.data()].y2;
07484               for (uint j = 0; j < AObjects[it.data()].Objects.count(); ++j)
07485                      if (!AObjects[it.data()].Objects.at(j)->locked())
07486                             AObjects[it.data()].Objects.at(j)->moveBy(0.0, diff);
07487               i++;
07488        }
07489        endAlign();
07490 }
07491 
07492 void ScribusDoc::itemSelection_DistributeCenterV()
07493 {
07494        if (!startAlign())
07495               return;
07496        uint alignObjectsCount=AObjects.count();
07497        if (alignObjectsCount<=1)
07498               return;
07499        QMap<double,uint> Ysorted;
07500        for (uint a = 0; a < alignObjectsCount; ++a)
07501               Ysorted.insert(AObjects[a].y1+(AObjects[a].height)/2, a, false);
07502               
07503        QMap<double,uint>::Iterator it = Ysorted.begin();
07504        QMap<double,uint>::Iterator itend = Ysorted.end();
07505        double minY=it.key();
07506        double maxY=it.key();
07507        while ( it != itend)
07508        {
07509               if (minY>it.key())
07510                      minY=it.key();
07511               if (maxY<it.key())
07512                      maxY=it.key();
07513               ++it;
07514        }
07515               
07516        double separation=(maxY-minY)/static_cast<double>(alignObjectsCount-1);
07517        int i=0;
07518        for ( QMap<double,uint>::Iterator it = Ysorted.begin(); it != Ysorted.end(); ++it )
07519        {
07520               double diff=minY + i*separation-AObjects[it.data()].y1-(AObjects[it.data()].height)/2;
07521               for (uint j = 0; j < AObjects[it.data()].Objects.count(); ++j)
07522                      if (!AObjects[it.data()].Objects.at(j)->locked())
07523                             AObjects[it.data()].Objects.at(j)->moveBy(0.0, diff);
07524               i++;
07525        }
07526        endAlign();
07527 }
07528 
07529 void ScribusDoc::itemSelection_DistributeTop()
07530 {
07531        if (!startAlign())
07532               return;
07533        uint alignObjectsCount=AObjects.count();
07534        if (alignObjectsCount<=1)
07535               return;
07536        QMap<double,uint> Ysorted;
07537        for (uint a = 0; a < alignObjectsCount; ++a)
07538               Ysorted.insert(AObjects[a].y1, a, false);
07539               
07540        QMap<double,uint>::Iterator it = Ysorted.begin();
07541        QMap<double,uint>::Iterator itend = Ysorted.end();
07542        double minY=it.key();
07543        double maxY=it.key();
07544        while ( it != itend)
07545        {
07546               if (minY>it.key())
07547                      minY=it.key();
07548               if (maxY<it.key())
07549                      maxY=it.key();
07550               ++it;
07551        }
07552               
07553        double separation=(maxY-minY)/static_cast<double>(alignObjectsCount-1);
07554        int i=0;
07555        for ( QMap<double,uint>::Iterator it = Ysorted.begin(); it != Ysorted.end(); ++it )
07556        {
07557               double diff=minY + i*separation-AObjects[it.data()].y1;
07558               for (uint j = 0; j < AObjects[it.data()].Objects.count(); ++j)
07559                      if (!AObjects[it.data()].Objects.at(j)->locked())
07560                             AObjects[it.data()].Objects.at(j)->moveBy(0.0,diff);
07561               i++;
07562        }
07563        endAlign();
07564 }
07565 
07566 void ScribusDoc::itemSelection_DistributeDistV(bool usingDistance, double distance)
07567 {
07568        if (!startAlign())
07569               return;
07570        uint alignObjectsCount=AObjects.count();
07571        if (alignObjectsCount<=1)
07572               return;
07573        QMap<double,uint> Y1sorted, Y2sorted;
07574        for (uint a = 0; a < alignObjectsCount; ++a)
07575        {
07576               Y1sorted.insert(AObjects[a].y1, a, false);
07577               Y2sorted.insert(AObjects[a].y2, a, false);
07578        }      
07579        uint top=Y1sorted.begin().data();
07580        uint bottom=Y2sorted[Y2sorted.keys().back()];
07581        double minY=AObjects[top].y2;
07582        double separation=0.0;
07583        if (!usingDistance)
07584        {
07585               double maxY=AObjects[bottom].y1;
07586               double totalSpace=maxY-minY;
07587               double totalHeight=0;
07588               uint insideObjectCount=0;
07589               for (uint a = 0; a < alignObjectsCount; ++a)
07590               {
07591                      if (a==top)
07592                             continue;
07593                      if (a==bottom)
07594                             continue;
07595                      totalHeight += AObjects[a].height;
07596                      ++insideObjectCount;
07597               }
07598               separation=(totalSpace-totalHeight)/(insideObjectCount+1);
07599        }
07600        else
07601               separation=value2pts(distance, unitIndex());
07602        double currY=minY;
07603        for ( QMap<double,uint>::Iterator it = Y1sorted.begin(); it != Y1sorted.end(); ++it )
07604        {
07605               if (it.data()==top)
07606                      continue;
07607               if (it.data()==bottom && !usingDistance)
07608                      continue;
07609               currY+=separation;
07610 
07611               double diff=currY-AObjects[it.data()].y1;
07612               for (uint j = 0; j < AObjects[it.data()].Objects.count(); ++j)
07613                      if (!AObjects[it.data()].Objects.at(j)->locked())
07614                             AObjects[it.data()].Objects.at(j)->moveBy(0.0,diff);
07615               currY+=AObjects[it.data()].height;
07616        }
07617        endAlign();
07618        usingDistance=false;
07619 }
07620 
07621 
07622 void ScribusDoc::itemSelection_DistributeAcrossPage(bool useMargins)
07623 {
07624        if (!startAlign())
07625               return;
07626        uint alignObjectsCount=AObjects.count();
07627        if (alignObjectsCount<=1)
07628               return;
07629        QMap<double,uint> X1sorted, X2sorted;
07630        for (uint a = 0; a < alignObjectsCount; ++a)
07631        {
07632               X1sorted.insert(AObjects[a].x1, a, false);
07633               X2sorted.insert(AObjects[a].x2, a, false);
07634        }      
07635        
07636        double totalSpace=0.0;
07637        if (useMargins)
07638               totalSpace=currentPage()->width()-currentPage()->Margins.Left-currentPage()->Margins.Right;
07639        else
07640               totalSpace=currentPage()->width();
07641        double totalWidth=0.0;
07642        uint insideObjectCount=0;
07643        for (uint a = 0; a < alignObjectsCount; ++a)
07644        {
07645               totalWidth += AObjects[a].width;
07646               ++insideObjectCount;
07647        }
07648        double separation=(totalSpace-totalWidth)/(insideObjectCount+1);
07649        double currX=currentPage()->xOffset();
07650        if (useMargins)
07651               currX+=currentPage()->Margins.Left;
07652        //Handle when our items are too wide for the page.
07653        if (separation<0.0)
07654        {
07655               separation=(totalSpace-totalWidth)/(insideObjectCount-1);
07656               currX-=separation;
07657        }
07658               
07659        for ( QMap<double,uint>::Iterator it = X1sorted.begin(); it != X1sorted.end(); ++it )
07660        {
07661               currX+=separation;
07662               double diff=currX-AObjects[it.data()].x1;
07663               for (uint j = 0; j < AObjects[it.data()].Objects.count(); ++j)
07664                      if (!AObjects[it.data()].Objects.at(j)->locked())
07665                             AObjects[it.data()].Objects.at(j)->moveBy(diff, 0.0);
07666               currX+=AObjects[it.data()].width;
07667        }
07668        endAlign();
07669 }
07670 
07671 void ScribusDoc::itemSelection_DistributeDownPage(bool useMargins)
07672 {
07673        if (!startAlign())
07674               return;
07675        uint alignObjectsCount=AObjects.count();
07676        if (alignObjectsCount<=1)
07677               return;
07678        QMap<double,uint> Y1sorted, Y2sorted;
07679        for (uint a = 0; a < alignObjectsCount; ++a)
07680        {
07681               Y1sorted.insert(AObjects[a].y1, a, false);
07682               Y2sorted.insert(AObjects[a].y2, a, false);
07683        }      
07684        
07685        double totalSpace=0.0;
07686        if (useMargins)
07687               totalSpace=currentPage()->height()-currentPage()->Margins.Top-currentPage()->Margins.Bottom;
07688        else
07689               totalSpace=currentPage()->height();
07690        double totalHeight=0.0;
07691        uint insideObjectCount=0;
07692        for (uint a = 0; a < alignObjectsCount; ++a)
07693        {
07694               totalHeight += AObjects[a].height;
07695               ++insideObjectCount;
07696        }
07697        double separation=(totalSpace-totalHeight)/(insideObjectCount+1);
07698        double currY=currentPage()->yOffset();
07699        if (useMargins)
07700               currY+=currentPage()->Margins.Top;
07701        //Handle when our items are too high for the page.
07702        if (separation<0.0)
07703        {
07704               separation=(totalSpace-totalHeight)/(insideObjectCount-1);
07705               currY-=separation;
07706        }
07707               
07708        for ( QMap<double,uint>::Iterator it = Y1sorted.begin(); it != Y1sorted.end(); ++it )
07709        {
07710               currY+=separation;
07711               double diff=currY-AObjects[it.data()].y1;
07712               for (uint j = 0; j < AObjects[it.data()].Objects.count(); ++j)
07713                      if (!AObjects[it.data()].Objects.at(j)->locked())
07714                             AObjects[it.data()].Objects.at(j)->moveBy(0.0, diff);
07715               currY+=AObjects[it.data()].height;
07716        }
07717        endAlign();
07718 }
07719 
07720 void ScribusDoc::changed()
07721 {
07722        modified=true;
07723        emit docChanged();
07724 }
07725 
07726 Page* ScribusDoc::currentPage()
07727 {
07728        return _currentPage;
07729 }
07730 
07731 void ScribusDoc::setCurrentPage(Page *newPage)
07732 {
07733        if (newPage==NULL)
07734               return;
07735        _currentPage = newPage;
07736        if (m_ScMW)
07737        {
07738               m_ScMW->guidePalette->setDoc(this);
07739               if (!isLoading())
07740               {
07741                      m_ScMW->guidePalette->setupPage();
07742                      m_ScMW->pagePalette->markPage(newPage->pageNr());
07743               }
07744        }
07745 }
07746 
07747 QPoint ScribusDoc::ApplyGrid(const QPoint& in)
07748 {
07749        QPoint np;
07750        int onp = OnPage(in.x(), in.y());
07751        if (useRaster && (onp != -1))
07752        {
07753               np.setX(static_cast<int>(qRound((in.x() - Pages->at(onp)->xOffset()) / guidesSettings.minorGrid) * guidesSettings.minorGrid + Pages->at(onp)->xOffset()));
07754               np.setY(static_cast<int>(qRound((in.y() - Pages->at(onp)->yOffset()) / guidesSettings.minorGrid) * guidesSettings.minorGrid + Pages->at(onp)->yOffset()));
07755        }
07756        else
07757               np = in;
07758        return np;
07759 }
07760 
07761 FPoint ScribusDoc::ApplyGridF(const FPoint& in)
07762 {
07763        FPoint np;
07764        int onp = OnPage(in.x(), in.y());
07765        if (useRaster && (onp != -1))
07766        {
07767               np.setX(qRound((in.x() - Pages->at(onp)->xOffset()) / guidesSettings.minorGrid) * guidesSettings.minorGrid + Pages->at(onp)->xOffset());
07768               np.setY(qRound((in.y() - Pages->at(onp)->yOffset()) / guidesSettings.minorGrid) * guidesSettings.minorGrid + Pages->at(onp)->yOffset());
07769        }
07770        else
07771               np = in;
07772        return np;
07773 }
07774 
07775 void ScribusDoc::itemSelection_MultipleDuplicate(ItemMultipleDuplicateData& mdData)
07776 {
07777        if ((mdData.type==0 && mdData.copyCount<1) || (mdData.type==1 && (mdData.gridRows==1 && mdData.gridCols==1)))
07778               return;
07779        QString tooltip("");
07780        if (UndoManager::undoEnabled())
07781        { // Make multiple duplicate a single action in the action history
07782               if (m_Selection->count() > 1)
07783                      undoManager->beginTransaction(Um::SelectionGroup, Um::IGroup, Um::MultipleDuplicate,"",Um::IMultipleDuplicate);
07784               else
07785               {
07786                      PageItem* item=m_Selection->itemAt(0);
07787                      undoManager->beginTransaction(item->getUName(), item->getUPixmap(), Um::MultipleDuplicate, "", Um::IMultipleDuplicate);
07788               }
07789        }
07790        //FIXME: Enable paste without doing this save/restore, and stop using paste with all the refreshes
07791        bool savedAlignGrid = useRaster;
07792        bool savedAlignGuides = SnapGuides;
07793        useRaster = false;
07794        SnapGuides = false;
07795        DoDrawing = false;
07796        view()->updatesOn(false);
07797        m_ScMW->ScriptRunning = true;
07798        if (mdData.type==0) // Copy and offset or set a gap
07799        {
07800               double dH = mdData.copyShiftGapH / docUnitRatio;
07801               double dV = mdData.copyShiftGapV / docUnitRatio;
07802               double dH2 = dH;
07803               double dV2 = dV;
07804               double dR = mdData.copyRotation;
07805               double dR2 = dR;
07806               if (mdData.copyShiftOrGap==1)
07807               {
07808                      if (dH != 0.0)
07809                             dH2 += m_Selection->width();
07810                      if (dV != 0.0)
07811                             dV2 += m_Selection->height();
07812               }
07813               m_ScMW->slotEditCopy();
07814               m_View->Deselect(true);
07815               for (int i=0; i<mdData.copyCount; ++i)
07816               {
07817                      m_ScMW->slotEditPaste();
07818                      for (uint b=0; b<m_Selection->count(); ++b)
07819                      {
07820                             PageItem* bItem=m_Selection->itemAt(b);
07821                             bItem->setLocked(false);
07822                             MoveItem(dH2, dV2, bItem, true);
07823                      }
07824                      m_Selection->setGroupRect();
07825                      if (dR != 0.0)
07826                      {
07827                             if (m_Selection->count() > 1)
07828                                    m_View->RotateGroup(dR2);
07829                             else
07830                                    RotateItem(dR2, m_Selection->itemAt(0));
07831                      }
07832                      dH2 += dH;
07833                      dV2 += dV;
07834                      if (mdData.copyShiftOrGap==1)
07835                      {
07836                             if (dH != 0.0)
07837                                    dH2 += m_Selection->width();
07838                             if (dV != 0.0)
07839                                    dV2 += m_Selection->height();
07840                      }
07841                      dR2 += dR;
07842                      m_View->Deselect(true);
07843               }
07844               changed();
07845               m_View->Deselect(true);
07846               tooltip = tr("Number of copies: %1\nHorizontal shift: %2\nVertical shift: %3\nRotation: %4").arg(mdData.copyCount).arg(dH).arg(dV).arg(dR);
07847        }
07848        else
07849        if (mdData.type==1) // Create a grid of duplicated items
07850        {
07851               m_ScMW->slotEditCopy();
07852               int copyCount=mdData.gridRows*mdData.gridCols;
07853               double dX=mdData.gridGapH/docUnitRatio + m_Selection->width();
07854               double dY=mdData.gridGapV/docUnitRatio + m_Selection->height();
07855               m_View->Deselect(true);
07856               for (int i=0; i<mdData.gridRows; ++i) //skip 0, the item is the one we are copying
07857               {
07858                      for (int j=0; j<mdData.gridCols; ++j) //skip 0, the item is the one we are copying
07859                      {
07860                             if (i==0 && j==0)
07861                                    continue;
07862                             m_ScMW->slotEditPaste();
07863                             for (uint b=0; b<m_Selection->count(); ++b)
07864                             {
07865                                    PageItem* bItem=m_Selection->itemAt(b);
07866                                    bItem->setLocked(false);
07867                                    MoveItem(j*dX, i*dY, bItem, true);
07868                             }
07869                      }
07870               }
07871               changed();
07872               m_View->Deselect(true);
07873               tooltip = tr("Number of copies: %1\nHorizontal gap: %2\nVertical gap: %3").arg(copyCount-1).arg(mdData.gridGapH).arg(mdData.gridGapV);
07874        }
07875        if (UndoManager::undoEnabled())
07876               undoManager->commit("", 0, "", tooltip, 0);
07877        //FIXME: Enable paste without doing this save/restore
07878        useRaster = savedAlignGrid;
07879        SnapGuides = savedAlignGuides;
07880        DoDrawing = true;
07881        view()->updatesOn(true);
07882        m_ScMW->ScriptRunning = false;
07883        view()->DrawNew();
07884 }
07885 
07886 void ScribusDoc::itemSelection_ApplyImageEffects(ScImageEffectList& newEffectList, Selection* customSelection)
07887 {
07888        Selection* itemSelection = (customSelection!=0) ? customSelection : m_Selection;
07889        assert(itemSelection!=NULL);
07890        uint selectedItemCount=itemSelection->count();
07891        if (selectedItemCount != 0)
07892        {
07893               PageItem *currItem = itemSelection->itemAt(0);
07894               ScImageEffectList oldEffects(currItem->effectsInUse);
07895               currItem->effectsInUse = newEffectList;
07896               updatePic();
07897               
07898               // this messy part is for the undo action
07899               ItemState<QPair<ScImageEffectList, ScImageEffectList> > *state = 
07900               new ItemState<QPair<ScImageEffectList, ScImageEffectList> >(
07901                             Um::ImageEffects, "", currItem->getUPixmap());
07902               state->set("APPLY_IMAGE_EFFECTS", "apply_image_effects");
07903               state->setItem(QPair<ScImageEffectList, ScImageEffectList>(oldEffects, currItem->effectsInUse));
07904               undoManager->action(currItem, state);
07905               changed();
07906        }
07907 }
07908 
07909 
07910 void ScribusDoc::itemSelection_ApplyArrowHead(int startArrowID, int endArrowID, Selection* customSelection)
07911 {
07912        Selection* itemSelection = (customSelection!=0) ? customSelection : m_Selection;
07913        assert(itemSelection!=0);
07914        uint selectedItemCount=itemSelection->count();
07915        if (selectedItemCount == 0)
07916               return;
07917        
07918        if (UndoManager::undoEnabled() && selectedItemCount > 1)
07919               undoManager->beginTransaction();
07920        QString tooltip = Um::ItemsInvolved + "\n";
07921        for (uint a = 0; a < selectedItemCount; ++a)
07922        {
07923               PageItem *currItem = itemSelection->itemAt(a);
07924               if (!currItem->asLine())
07925                      continue;
07926               if (startArrowID!=-1)
07927               {
07928                      currItem->setStartArrowIndex(startArrowID);
07929               }
07930               if (endArrowID!=-1)
07931               {
07932                      currItem->setEndArrowIndex(endArrowID);
07933               }
07934               tooltip += "\t" + currItem->getUName() + "\n";
07935               emit refreshItem(currItem);
07936        }
07937        QString t;
07938        if (startArrowID!=-1 && endArrowID!=-1)
07939               t=Um::StartAndEndArrow;
07940        else
07941               t=(startArrowID!=-1) ? Um::StartArrow : Um::EndArrow;
07942        if (UndoManager::undoEnabled() && selectedItemCount > 1)
07943               undoManager->commit(Um::Selection,
07944                                                  Um::IGroup,
07945                                                  t,
07946                                                  tooltip,
07947                                                  Um::IArrow);
07948        changed();
07949 }
07950 
07951 void ScribusDoc::createDefaultMasterPages()
07952 {
07953        int setcol = pageSets[currentPageLayout].Columns;
07954        if (setcol == 1)
07955        {
07956               addMasterPage(0, CommonStrings::trMasterPageNormal);
07957        }
07958        else if (setcol == 2)
07959        {
07960               Page *lp = addMasterPage(0, CommonStrings::trMasterPageNormalLeft);
07961               lp->LeftPg = 1;
07962               lp->Margins.Left = lp->initialMargins.Right;
07963               lp->Margins.Right = lp->initialMargins.Left;
07964               lp = addMasterPage(1, CommonStrings::trMasterPageNormalRight);
07965               lp->LeftPg = 0;
07966               lp->Margins.Right = lp->initialMargins.Right;
07967               lp->Margins.Left = lp->initialMargins.Left;
07968        }
07969        else if ((setcol == 3) || (setcol == 4))
07970        {
07971               Page *lp = addMasterPage(0, CommonStrings::trMasterPageNormalLeft);
07972               lp->LeftPg = 1;
07973               lp->Margins.Left = lp->initialMargins.Right;
07974               lp->Margins.Right = lp->initialMargins.Left;
07975               lp = addMasterPage(1, CommonStrings::trMasterPageNormalRight);
07976               lp->LeftPg = 0;
07977               lp->Margins.Right = lp->initialMargins.Right;
07978               lp->Margins.Left = lp->initialMargins.Left;
07979               lp = addMasterPage(2, CommonStrings::trMasterPageNormalMiddle);
07980               lp->LeftPg = 2;
07981               lp->Margins.Left = lp->initialMargins.Left;
07982               lp->Margins.Right = lp->initialMargins.Left;
07983        }
07984 }
07985 
07986 void ScribusDoc::createNewDocPages(int pageCount)
07987 {
07988        int setcol = pageSets[currentPageLayout].Columns;
07989        int createCount=QMAX(pageCount,1);
07990        if (setcol == 1)
07991        {
07992               for (int i = 0; i < createCount; ++i)
07993                      addPage(i, CommonStrings::trMasterPageNormal, true);
07994        }
07995        else if (setcol == 2)
07996        {
07997               for (int i = 0; i < createCount; ++i)
07998               {
07999                      PageLocation pageLoc = locationOfPage(i);
08000                      if (pageLoc == LeftPage)
08001                             addPage(i, CommonStrings::trMasterPageNormalLeft, true);
08002                      else
08003                             addPage(i, CommonStrings::trMasterPageNormalRight, true);
08004               }
08005        }
08006        else if ((setcol == 3) || (setcol == 4))
08007        {
08008               for (int i = 0; i < createCount; ++i)
08009               {
08010                      PageLocation pageLoc = locationOfPage(i);
08011                      if (pageLoc == LeftPage)
08012                             addPage(i, CommonStrings::trMasterPageNormalLeft, true);
08013                      else if (pageLoc == RightPage)
08014                             addPage(i, CommonStrings::trMasterPageNormalRight, true);
08015                      else
08016                             addPage(i, CommonStrings::trMasterPageNormalMiddle, true);
08017               }
08018        }
08019 }
08020 
08021 void ScribusDoc::getClosestGuides(double xin, double yin, double *xout, double *yout)
08022 {
08023        m_View->GxM = -1;
08024        m_View->GyM = -1;
08025        QMap<double, uint> tmpGuidesSel;
08026        Guides tmpGuides = currentPage()->guides.horizontals(GuideManagerCore::Standard);
08027        Guides::iterator it;
08028        uint yg = 0;
08029        uint xg = 0;
08030        double viewScale=m_View->scale();
08031        for (it = tmpGuides.begin(); it != tmpGuides.end(); ++it, ++yg)
08032        {
08033               if (((*it)+currentPage()->yOffset()< (yin+guidesSettings.guideRad / viewScale)) && ((*it)+currentPage()->yOffset()> (yin-guidesSettings.guideRad / viewScale)))
08034                      tmpGuidesSel.insert(fabs(((*it)+currentPage()->yOffset()) - yin), yg);
08035        }
08036        if (tmpGuidesSel.count() != 0)
08037        {
08038               m_View->GyM = tmpGuidesSel.begin().data();
08039               *yout = tmpGuides[m_View->GyM];
08040        }
08041        tmpGuidesSel.clear();
08042        tmpGuides = currentPage()->guides.verticals(GuideManagerCore::Standard);
08043        for (it = tmpGuides.begin(); it != tmpGuides.end(); ++it, ++xg)
08044        {
08045               if (((*it)+currentPage()->xOffset()< (xin+guidesSettings.guideRad / viewScale)) && ((*it)+currentPage()->xOffset()> (xin-guidesSettings.guideRad / viewScale)))
08046                      tmpGuidesSel.insert(fabs(((*it)+currentPage()->xOffset()) - xin), xg);
08047        }
08048        if (tmpGuidesSel.count() != 0)
08049        {
08050               m_View->GxM = tmpGuidesSel.begin().data();
08051               *xout = tmpGuides[m_View->GxM];
08052        }
08053        yg = 0;
08054        xg = 0;
08055        tmpGuidesSel.clear();
08056        tmpGuides = currentPage()->guides.horizontals(GuideManagerCore::Auto);
08057        for (it = tmpGuides.begin(); it != tmpGuides.end(); ++it, ++yg)
08058        {
08059               if (((*it)+currentPage()->yOffset()< (yin+guidesSettings.guideRad / viewScale)) && ((*it)+currentPage()->yOffset()> (yin-guidesSettings.guideRad / viewScale)))
08060                      tmpGuidesSel.insert(fabs(((*it)+currentPage()->yOffset()) - yin), yg);
08061        }
08062        if (tmpGuidesSel.count() != 0)
08063        {
08064               m_View->GyM = tmpGuidesSel.begin().data();
08065               *yout = tmpGuides[m_View->GyM];
08066        }
08067        tmpGuidesSel.clear();
08068        tmpGuides = currentPage()->guides.verticals(GuideManagerCore::Auto);
08069        for (it = tmpGuides.begin(); it != tmpGuides.end(); ++it, ++xg)
08070        {
08071               if (((*it)+currentPage()->xOffset()< (xin+guidesSettings.guideRad / viewScale)) && ((*it)+currentPage()->xOffset()> (xin-guidesSettings.guideRad / viewScale)))
08072                      tmpGuidesSel.insert(fabs(((*it)+currentPage()->xOffset()) - xin), xg);
08073        }
08074        if (tmpGuidesSel.count() != 0)
08075        {
08076               m_View->GxM = tmpGuidesSel.begin().data();
08077               *xout = tmpGuides[m_View->GxM];
08078        }
08079 }
08080 
08081 //CB-->Doc
08082 void ScribusDoc::SnapToGuides(PageItem *currItem)
08083 {
08084        int pg = OnPage(currItem);
08085        double xout, yout;
08086        if (pg == -1)
08087               return;
08088        Page* page = Pages->at(pg);
08089 
08090        getClosestGuides(0, currItem->yPos(), &xout, &yout);
08091        if (m_View->GyM != -1)
08092               currItem->setYPos(yout+page->yOffset());
08093        if (currItem->asLine())
08094        {
08095               QWMatrix ma;
08096               ma.translate(currItem->xPos(), currItem->yPos());
08097               ma.rotate(currItem->rotation());
08098 //            double my = ma.m22() * currItem->height() + ma.m12() * currItem->width() + ma.dy();
08099               double my = ma.m12() * currItem->width() + ma.dy();
08100               getClosestGuides(0, my, &xout, &yout);
08101               if (m_View->GyM != -1)
08102                      currItem->moveBy(0.0, yout - my + page->yOffset());
08103        }
08104        else
08105        {
08106               getClosestGuides(0, currItem->yPos()+currItem->height(), &xout, &yout);
08107               if (m_View->GyM != -1)
08108                      currItem->setYPos(yout-currItem->height()+page->yOffset());
08109        }
08110        getClosestGuides(currItem->xPos(), 0, &xout, &yout);
08111        if (m_View->GxM != -1)
08112               currItem->setXPos(xout+page->xOffset());
08113        if (currItem->asLine())
08114        {
08115               QWMatrix ma;
08116               ma.translate(currItem->xPos(), currItem->yPos());
08117               ma.rotate(currItem->rotation());
08118               double mx = ma.m11() * currItem->width() + ma.dx();
08119 //            double mx = ma.m11() * currItem->width() + ma.m21() * currItem->height() + ma.dx();
08120               getClosestGuides(mx,  0, &xout, &yout);
08121               if (m_View->GxM != -1)
08122                      currItem->moveBy(xout - mx + page->xOffset(), 0.0);
08123        }
08124        else
08125        {
08126               getClosestGuides(currItem->xPos()+currItem->width(), 0, &xout, &yout);
08127               if (m_View->GxM != -1)
08128                      currItem->setXPos(xout-currItem->width()+page->xOffset());
08129        }
08130 }
08131 
08132 
08133 //CB-->Doc?
08134 bool ScribusDoc::ApplyGuides(double *x, double *y)
08135 {
08136 //     m_SnapCounter++;
08137        bool ret = false;
08138        double xout, yout;
08139        int pg = OnPage(*x, *y);
08140        if (pg == -1)
08141               return ret;
08142        Page* page = Pages->at(pg);
08143 //     if ((SnapGuides) && (m_SnapCounter > 1))
08144        if (SnapGuides)
08145        {
08146 //            m_SnapCounter = 0;
08147               getClosestGuides(*x, *y, &xout, &yout);
08148               if (m_View->GxM != -1)
08149               {
08150                      *x = xout+page->xOffset();
08151                      ret = true;
08152               }
08153               if (m_View->GyM != -1)
08154               {
08155                      *y = yout+page->yOffset();
08156                      ret = true;
08157               }
08158               double invViewScale=1/m_View->scale();
08159               if ((page->Margins.Left+page->xOffset() < (*x+guidesSettings.guideRad * invViewScale)) && (page->Margins.Left+page->xOffset() > (*x-guidesSettings.guideRad * invViewScale)))
08160               {
08161                      *x = page->Margins.Left+page->xOffset();
08162                      ret = true;
08163               }
08164               if (((page->width() - page->Margins.Right)+page->xOffset() < (*x+guidesSettings.guideRad * invViewScale)) && ((page->width() - page->Margins.Right)+page->xOffset() > (*x-guidesSettings.guideRad * invViewScale)))
08165               {
08166                      *x = page->width() - page->Margins.Right+page->xOffset();
08167                      ret = true;
08168               }
08169               if ((page->Margins.Top+page->yOffset() < (*y+guidesSettings.guideRad * invViewScale)) && (page->Margins.Top+page->yOffset() > (*y-guidesSettings.guideRad * invViewScale)))
08170               {
08171                      *y = page->Margins.Top+page->yOffset();
08172                      ret = true;
08173               }
08174               if (((page->height() - page->Margins.Bottom)+page->yOffset() < (*y+guidesSettings.guideRad * invViewScale)) && ((page->height() - page->Margins.Bottom)+page->yOffset() > (*y-guidesSettings.guideRad * invViewScale)))
08175               {
08176                      *y = page->height() - page->Margins.Bottom+page->yOffset();
08177                      ret = true;
08178               }
08179        }
08180 //     if (m_SnapCounter > 10)
08181 //            m_SnapCounter = 0;
08182        return ret;
08183 }
08184 
08185 //CB-->Doc
08186 bool ScribusDoc::MoveItem(double newX, double newY, PageItem* currItem, bool fromMP)
08187 {
08188        if (currItem->locked())
08189               return false;
08190        bool retw = false;
08191        double oldx = currItem->xPos();
08192        double oldy = currItem->yPos();
08193        currItem->moveBy(newX, newY);
08194 /*     if ((useRaster) && (!m_View->operItemMoving) && (!fromMP) && (static_cast<int>(currentPage()->pageNr()) == currItem->OwnPage))
08195        {
08196               FPoint np = ApplyGridF(FPoint(currItem->xPos(), currItem->yPos()));
08197               currItem->setXYPos(np.x(), np.y());
08198        }
08199        if ((SnapGuides) && (!m_View->operItemMoving) && (appMode == modeNormal) && (!EditClip) && (!fromMP))
08200               SnapToGuides(currItem); */
08201        if ((currItem->xPos() != oldx) || (currItem->yPos() != oldy))
08202               retw = true;
08203        if (!fromMP)
08204        {
08205 /*            if (GroupSel)
08206               {
08207                      double gx, gy, gh, gw;
08208                      setGroupRect();
08209                      getGroupRect(&gx, &gy, &gw, &gh);
08210                      emit ItemPos(gx, gy);
08211               }
08212               else */
08213               //CB if (!GroupSel)
08214               //CB   emit ItemPos(currItem->xPos(), currItem->yPos());
08215               //CB qDebug("if (!GroupSel)                      emit ItemPos(currItem->xPos(), currItem->yPos());");
08216        }
08217 /*     if (!loading)
08218               emit UpdtObj(currentPage->pageNr(), b->ItemNr); */
08219        QRect oldR(currItem->getRedrawBounding(m_View->scale()));
08220        setRedrawBounding(currItem);
08221        QRect newR(currItem->getRedrawBounding(m_View->scale()));
08222        if ((!m_View->operItemMoving) && (!currItem->Sizing))
08223               emit updateContents(newR.unite(oldR));
08224        currItem->OwnPage = OnPage(currItem);
08225        return retw;
08226 }
08227 
08228 //CB-->Doc
08229 void ScribusDoc::RotateItem(double win, int ite)
08230 {
08231        RotateItem(win, Items->at(ite));
08232 }
08233 
08234 //CB-->Doc
08235 void ScribusDoc::RotateItem(double win, PageItem *currItem)
08236 {
08237        if (currItem->locked())
08238               return;
08239        QRect oldR(currItem->getRedrawBounding(m_View->scale()));
08240 //     if ((Doc->RotMode != 0) && (m_MouseButtonPressed))
08241        if (RotMode != 0)
08242        {
08243               QWMatrix ma;
08244               ma.translate(currItem->xPos(), currItem->yPos());
08245               ma.scale(1, 1);
08246               ma.rotate(currItem->rotation());
08247               double ro = win-currItem->rotation();
08248               currItem->setRotation(win);
08249               FPoint n(0,0);
08250               switch (RotMode)
08251               {
08252               case 2:
08253                      ma.translate(currItem->width()/2, currItem->height()/2);
08254                      n = FPoint(-currItem->width()/2, -currItem->height()/2);
08255                      break;
08256               case 4:
08257                      ma.translate(currItem->width(), currItem->height());
08258                      n = FPoint(-currItem->width(), -currItem->height());
08259                      break;
08260               case 3:
08261                      ma.translate(0, currItem->height());
08262                      n = FPoint(0, -currItem->height());
08263                      break;
08264               case 1:
08265                      ma.translate(currItem->width(), 0);
08266                      n = FPoint(-currItem->width(), 0);
08267                      break;
08268               }
08269               ma.rotate(ro);
08270               double x = ma.m11() * n.x() + ma.m21() * n.y() + ma.dx();
08271               double y = ma.m22() * n.y() + ma.m12() * n.x() + ma.dy();
08272               bool oldS = currItem->Sizing;
08273               currItem->Sizing = true;
08274               MoveItem(x-currItem->xPos(), y-currItem->yPos(), currItem);
08275               currItem->Sizing = oldS;
08276        }
08277        else
08278        {
08279               currItem->setRotation(win);
08280               setRedrawBounding(currItem);
08281        }
08282        QRect newR(currItem->getRedrawBounding(m_View->scale()));
08283        emit updateContents(newR.unite(oldR));
08284        //emit SetAngle(currItem->rotation());
08285 }
08286 
08287 
08288 //CB-->Doc
08289 void ScribusDoc::MoveRotated(PageItem *currItem, FPoint npv, bool fromMP)
08290 {
08291        QWMatrix ma;
08292        ma.translate(currItem->xPos(), currItem->yPos());
08293        ma.rotate(currItem->rotation());
08294        double mxc = currItem->xPos() - (ma.m11() * npv.x() + ma.m21() * npv.y() + ma.dx());
08295        double myc = currItem->yPos() - (ma.m22() * npv.y() + ma.m12() * npv.x() + ma.dy());
08296        MoveItem(-mxc, -myc, currItem, fromMP);
08297 }
08298 
08299 //CB-->Doc
08300 bool ScribusDoc::SizeItem(double newX, double newY, int ite, bool fromMP, bool DoUpdateClip, bool redraw)
08301 {
08302        return SizeItem(newX, newY, Items->at(ite), fromMP, DoUpdateClip, redraw);
08303 }
08304 
08305 //CB-->Doc
08306 bool ScribusDoc::SizeItem(double newX, double newY, PageItem *pi, bool fromMP, bool DoUpdateClip, bool redraw)
08307 {
08308        PageItem *currItem = pi;
08309        if (currItem->locked())
08310               return false;
08311        QPainter p;
08312        double viewScale=m_View->scale();
08313        QRect oldR(currItem->getRedrawBounding(viewScale));
08314        //Uncomment for stopping resize in any direction
08315        //and remove the height/width <0 tests in item sizing switch
08316        /*
08317        if (!currItem->asLine())
08318        {
08319               newX = QMAX(newX, 1);
08320               newY = QMAX(newY, 1);
08321        }
08322        */
08323        int ph = static_cast<int>(QMAX(1.0, currItem->lineWidth() / 2.0));
08324        QWMatrix ma;
08325        ma.rotate(currItem->rotation());
08326        double dX = ma.m11() * (currItem->width() - newX) + ma.m21() * (currItem->height() - newY) + ma.dx();
08327        double dY = ma.m22() * (currItem->height() - newY) + ma.m12() * (currItem->width() - newX) + ma.dy();
08328        currItem->setWidthHeight(newX, newY, true);
08329        if ((RotMode != 0) && (fromMP) && (!isLoading()) && (appMode == modeNormal))
08330        {
08331               double moveX=dX, moveY=dY;
08332               if (RotMode==2)
08333               {
08334                      moveX/=2.0;
08335                      moveY/=2.0;
08336               }
08337               else if (RotMode==3)
08338                      moveX=0.0;
08339               else if (RotMode==1)
08340                      moveY=0.0;
08341               MoveItem(moveX, moveY, currItem);
08342        }
08343        if ((currItem->asImageFrame()) && (!currItem->Sizing) && (!EditClip))
08344        {
08345               currItem->AdjustPictScale();
08346        }
08347        if (currItem->asLine())
08348        {
08349               if (!fromMP)
08350               {
08351                      currItem->setRotation(atan2(currItem->height(),currItem->width())*(180.0/M_PI));
08352                      currItem->setWidthHeight(sqrt(pow(currItem->width(),2)+pow(currItem->height(),2)), 1.0);
08353               }
08354               currItem->Clip.setPoints(4, -ph,-ph, static_cast<int>(currItem->width()+ph),-ph,
08355                                 static_cast<int>(currItem->width()+ph),static_cast<int>(currItem->height()+ph),
08356                                 -ph,static_cast<int>(currItem->height()+ph));
08357        }
08358        setRedrawBounding(currItem);
08359        currItem->OwnPage = OnPage(currItem);
08360        if (currItem->Sizing)
08361        {
08362 //            currItem->Tinput = true;
08363               currItem->FrameOnly = true;
08364               if ((m_View->frameResizeHandle == 1) && !(currItem->asLine()))
08365                      currItem->paintObj();
08366               if ((currItem->FrameType == 0) || (currItem->asLine()) || (m_View->frameResizeHandle != 1))
08367                      return true;
08368               QPainter p;
08369               p.begin(m_View->viewport());
08370               QPoint in(qRound((currItem->xPos()-minCanvasCoordinate.x())*viewScale), qRound((currItem->yPos()-minCanvasCoordinate.y())*viewScale));
08371               QPoint out(m_View->contentsToViewport(in));
08372               p.translate(out.x(), out.y());
08373               p.scale(viewScale, viewScale);
08374               p.rotate(currItem->rotation());
08375               p.setRasterOp(XorROP);
08376               p.setBrush(NoBrush);
08377               p.setPen(QPen(white, 1, DotLine, FlatCap, MiterJoin));
08378               p.save();
08379               if (currItem->OldB2 < 0.0)
08380               {
08381                      p.scale(-1, 1);
08382                      p.translate(qRound(-currItem->OldB2), 0);
08383               }
08384               if (currItem->OldH2 < 0.0)
08385               {
08386                      p.scale(1, -1);
08387                      p.translate(0, qRound(-currItem->OldH2));
08388               }
08389               currItem->DrawPolyL(&p, currItem->Clip);
08390               p.restore();
08391               currItem->updateClip();
08392 //            currItem->updateGradientVectors();
08393               p.save();
08394               if (currItem->width() < 0.0)
08395               {
08396                      p.scale(-1, 1);
08397                      p.translate(qRound(-currItem->width()), 0);
08398               }
08399               if (currItem->height() < 0.0)
08400               {
08401                      p.scale(1, -1);
08402                      p.translate(0, qRound(-currItem->height()));
08403               }
08404               currItem->DrawPolyL(&p, currItem->Clip);
08405               p.restore();
08406               p.end();
08407               return true;
08408        }
08409        if (DoUpdateClip)
08410        {
08411               double nX=0.0, nY=0.0;
08412               if (fromMP)
08413               {
08414                      if (currItem->imageFlippedH())
08415                             nX=-(currItem->width() - currItem->OldB2)/currItem->imageXScale();
08416                      if (currItem->imageFlippedV())
08417                             nY=-(currItem->height() - currItem->OldH2)/currItem->imageYScale();
08418               }
08419               else
08420               {
08421                      if (!currItem->imageFlippedH())
08422                             nX=(currItem->width() - currItem->OldB2)/currItem->imageXScale();
08423                      if (!currItem->imageFlippedV())
08424                             nY=(currItem->height() - currItem->OldH2)/currItem->imageYScale();
08425               }
08426               if (nX!=0.0 || nY!=0.0)
08427                      currItem->moveImageInFrame(dX,dY);
08428               currItem->updateClip();
08429        }
08430 //     currItem->updateGradientVectors();
08431        if (redraw)
08432        {
08433               QRect newR(currItem->getRedrawBounding(viewScale));
08434               emit updateContents(newR.unite(oldR));
08435        }
08436        if (!fromMP)
08437        {
08438               if (m_Selection->isMultipleSelection())
08439               {
08440                      double gx, gy, gh, gw;
08441                      m_Selection->setGroupRect();
08442                      m_Selection->getGroupRect(&gx, &gy, &gw, &gh);
08443                      qDebug("doc, emit w&h, when was this used?");
08444                      emit widthAndHeight(gw, gh);
08445               }
08446        }
08447        currItem->setCornerRadius(QMIN(currItem->cornerRadius(), QMIN(currItem->width(),currItem->height())/2));
08448        return true;
08449 }
08450 
08451 //CB-->Doc
08452 bool ScribusDoc::MoveSizeItem(FPoint newX, FPoint newY, int ite, bool fromMP, bool constrainRotation)
08453 {
08454        PageItem *currItem = Items->at(ite);
08455        double viewScale=m_View->scale();
08456        QRect oldR(currItem->getRedrawBounding(viewScale));
08457        if (currItem->asLine())
08458        {
08459               QWMatrix ma;
08460               ma.translate(currItem->xPos(), currItem->yPos());
08461               ma.rotate(currItem->rotation());
08462               double mx = ma.m11() * currItem->width() + ma.dx();
08463               double my = ma.m12() * currItem->width() + ma.dy();
08464               MoveItem(newX.x(), newX.y(), currItem, fromMP);
08465               double newRot=xy2Deg(mx - currItem->xPos(), my - currItem->yPos());
08466               //CB Hmm should work, doesnt. (constraining on the first point of a line)
08467               //if (constrainRotation)
08468               //     qDebug(QString("%1").arg(constrainAngle(newRot)));
08469               currItem->setRotation(newRot);
08470               currItem->setWidthHeight(sqrt(pow(mx - currItem->xPos(),2)+pow(my - currItem->yPos(),2)), 1.0);
08471               currItem->updateClip();
08472               setRedrawBounding(currItem);
08473               QRect newR(currItem->getRedrawBounding(viewScale));
08474               emit updateContents(oldR);
08475               emit updateContents(newR);
08476 //            updateContents(newR.unite(oldR));
08477        }
08478        else
08479        {
08480               currItem->OldB2 = currItem->width();
08481               currItem->OldH2 = currItem->height();
08482               if (currItem->rotation() != 0)
08483               {
08484                      FPoint npv(newX.x(), newX.y());
08485                      QWMatrix ma3;
08486                      ma3.translate(currItem->xPos(), currItem->yPos());
08487                      ma3.rotate(currItem->rotation());
08488                      double mxc3 = currItem->xPos() - (ma3.m11() * npv.x() + ma3.m21() * npv.y() + ma3.dx());
08489                      double myc3 = currItem->yPos() - (ma3.m22() * npv.y() + ma3.m12() * npv.x() + ma3.dy());
08490                      SizeItem(currItem->width() - newY.x(), currItem->height() - newY.y(), ite, fromMP, true, false);
08491                      MoveItem(-mxc3, -myc3, currItem, fromMP);
08492               }
08493               else
08494               {
08495                      SizeItem(currItem->width() - newY.x(), currItem->height() - newY.y(), ite, fromMP, true, false);
08496                      MoveItem(newX.x(), newX.y(), currItem, fromMP);
08497               }
08498        }
08499        return true;
08500 }
08501 
08502 //CB-->Doc
08503 void ScribusDoc::AdjustItemSize(PageItem *currItem)
08504 {
08505        bool siz = currItem->Sizing;
08506        currItem->Sizing = false;
08507        FPointArray Clip;
08508        Clip = currItem->PoLine;
08509        FPoint tp2(getMinClipF(&Clip));
08510        SizeItem(currItem->width() - tp2.x(), currItem->height() - tp2.y(), currItem, true, false, false);
08511        Clip.translate(-tp2.x(), -tp2.y());
08512        if (currItem->rotation() != 0)
08513        {
08514               FPoint npv(tp2.x(), tp2.y());
08515               MoveRotated(currItem, npv, true);
08516        }
08517        else
08518               MoveItem(tp2.x(), tp2.y(), currItem, true);
08519        if (!currItem->imageFlippedH())
08520               currItem->moveImageInFrame(-tp2.x()/currItem->imageXScale(), 0);
08521        if (!currItem->imageFlippedV())
08522               currItem->moveImageInFrame(0, -tp2.y()/currItem->imageYScale());
08523        FPoint tp(getMaxClipF(&Clip));
08524        if (currItem->imageFlippedH())
08525               currItem->moveImageInFrame((currItem->width() - tp.x())/currItem->imageXScale(), 0);
08526        if (currItem->imageFlippedV())
08527               currItem->moveImageInFrame(0, (currItem->height() - tp.y())/currItem->imageYScale());
08528        SizeItem(tp.x(), tp.y(), currItem, true, false);
08529        currItem->ClipEdited = true;
08530        currItem->PoLine = Clip.copy();
08531        if (currItem->asPolyLine())
08532               currItem->setPolyClip(qRound(QMAX(currItem->lineWidth() / 2, 1)));
08533        else if (currItem->asPathText())
08534               currItem->updatePolyClip();
08535        else
08536               currItem->Clip = FlattenPath(currItem->PoLine, currItem->Segments);
08537        currItem->Sizing = siz;
08538 }
08539 
08540 void ScribusDoc::itemSelection_UniteItems(Selection* /*customSelection*/)
08541 {
08542        PageItem *currItem;
08543        PageItem *bb;
08544        QValueList<int> toDel;
08545        toDel.clear();
08546        uint docSelectionCount = m_Selection->count();
08547        if (docSelectionCount > 1)
08548        {
08549               currItem = m_Selection->itemAt(0);
08550               if (currItem->Groups.count() != 0)
08551                      return;
08552               currItem->Frame = false;
08553               currItem->ClipEdited = true;
08554               currItem->FrameType = 3;
08555               for (uint a = 1; a < docSelectionCount; ++a)
08556               {
08557                      bb = m_Selection->itemAt(a);
08558                      toDel.append(bb->ItemNr);
08559                      QWMatrix ma;
08560                      ma.translate(bb->xPos(), bb->yPos());
08561                      ma.rotate(bb->rotation());
08562                      bb->PoLine.map(ma);
08563                      QWMatrix ma2;
08564                      ma2.translate(currItem->xPos(), currItem->yPos());
08565                      ma2.rotate(currItem->rotation());
08566                      ma2 = ma2.invert();
08567                      bb->PoLine.map(ma2);
08568                      currItem->PoLine.setMarker();
08569                      currItem->PoLine.putPoints(currItem->PoLine.size(), bb->PoLine.size(), bb->PoLine);
08570               }
08571 //            currItem->Clip = FlattenPath(currItem->PoLine, currItem->Segments);
08572               AdjustItemSize(currItem);
08573               currItem->ContourLine = currItem->PoLine.copy();
08574               m_View->Deselect(true);
08575               for (uint c = 0; c < toDel.count(); ++c)
08576                      m_View->SelectItemNr(*toDel.at(c));
08577               itemSelection_DeleteItem();
08578               emit updateContents();
08579        }
08580 }
08581 
08582 void ScribusDoc::itemSelection_SplitItems(Selection* /*customSelection*/)
08583 {
08584        PageItem *bb;
08585        uint StartInd = 0;
08586        uint z;
08587        PageItem *currItem = m_Selection->itemAt(0);
08588        uint EndInd = currItem->PoLine.size();
08589        for (uint a = EndInd-1; a > 0; --a)
08590        {
08591               if (currItem->PoLine.point(a).x() > 900000)
08592               {
08593                      StartInd = a + 1;
08594                      z = itemAdd(PageItem::Polygon, PageItem::Unspecified, currItem->xPos(), currItem->yPos(), currItem->width(), currItem->height(), currItem->lineWidth(), currItem->fillColor(), currItem->lineColor(), true);
08595                      bb = Items->at(z);
08596                      bb->PoLine.resize(0);
08597                      bb->PoLine.putPoints(0, EndInd - StartInd, currItem->PoLine, StartInd);
08598                      bb->setRotation(currItem->rotation());
08599                      AdjustItemSize(bb);
08600                      bb->ContourLine = bb->PoLine.copy();
08601                      bb->ClipEdited = true;
08602                      a -= 3;
08603                      EndInd = StartInd - 4;
08604               }
08605        }
08606        currItem->PoLine.resize(StartInd-4);
08607        AdjustItemSize(currItem);
08608        currItem->ContourLine = currItem->PoLine.copy();
08609        currItem->ClipEdited = true;
08610        m_View->Deselect(true);
08611        emit updateContents();
08612 }
08613 
08614 //CB-->Doc
08615 //Fix size/move item calls
08616 //CB TODO Use the selection loop properly
08617 void ScribusDoc::itemSelection_adjustFrametoImageSize( Selection *customSelection)
08618 {
08619        Selection* itemSelection = (customSelection!=0) ? customSelection : m_Selection;
08620        assert(itemSelection!=0);
08621        uint selectedItemCount=itemSelection->count();
08622        if (selectedItemCount == 0)
08623               return;
08624        
08625        if (selectedItemCount > 0)
08626        {
08627               bool toUpdate=false;
08628               for (uint i = 0; i < selectedItemCount; ++i)
08629               {
08630                      PageItem *currItem = itemSelection->itemAt(i);
08631                      if (currItem!=NULL)
08632                      {
08633                             if (currItem->asImageFrame() && currItem->PicAvail && !currItem->isTableItem)
08634                             {
08635                                    undoManager->beginTransaction(selectedItemCount == 1 ?
08636                                                                  currItem->getUName() : Um::SelectionGroup,
08637                                                                  selectedItemCount == 1 ?
08638                                                                  currItem->getUPixmap() : Um::IGroup,
08639                                                                  Um::AdjustFrameToImage,"",Um::IResize);
08640                                    double w, h, x, y;
08641                                    w = currItem->OrigW * currItem->imageXScale();
08642                                    h = currItem->OrigH * currItem->imageYScale();
08643                                    x = currItem->imageXOffset() * currItem->imageXScale();
08644                                    y = currItem->imageYOffset() * currItem->imageYScale();
08645                                    SizeItem(w, h, currItem->ItemNr);
08646                                    MoveItem(x, y, currItem);
08647                                    currItem->setImageXYOffset(0.0, 0.0);
08648                                    toUpdate=true;
08649                             }
08650                      }
08651               }
08652               if (toUpdate)
08653               {
08654                      emit updateContents();
08655                      changed();
08656                      undoManager->commit();
08657               }
08658        }
08659 }