You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@openoffice.apache.org by af...@apache.org on 2013/02/22 14:50:46 UTC

svn commit: r1449041 [2/5] - in /openoffice/branches/sidebar/main: officecfg/registry/data/org/openoffice/Office/UI/ sd/prj/ sd/sdi/ sd/source/ui/app/ sd/source/ui/framework/factories/ sd/source/ui/framework/module/ sd/source/ui/func/ sd/source/ui/inc/...

Added: openoffice/branches/sidebar/main/sd/source/ui/sidebar/LayoutMenu.cxx
URL: http://svn.apache.org/viewvc/openoffice/branches/sidebar/main/sd/source/ui/sidebar/LayoutMenu.cxx?rev=1449041&view=auto
==============================================================================
--- openoffice/branches/sidebar/main/sd/source/ui/sidebar/LayoutMenu.cxx (added)
+++ openoffice/branches/sidebar/main/sd/source/ui/sidebar/LayoutMenu.cxx Fri Feb 22 13:50:42 2013
@@ -0,0 +1,1003 @@
+/**************************************************************
+ * 
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * 
+ *************************************************************/
+
+#include "precompiled_sd.hxx"
+
+#include "LayoutMenu.hxx"
+
+#include "SidebarShellManager.hxx"
+#include "app.hrc"
+#include "drawdoc.hxx"
+#include "framework/FrameworkHelper.hxx"
+#include "glob.hrc"
+#include "glob.hxx"
+#include "helpids.h"
+#include "pres.hxx"
+#include "res_bmp.hrc"
+#include "sdpage.hxx"
+#include "sdresid.hxx"
+#include "strings.hrc"
+#include "tools/SlotStateListener.hxx"
+#include "DrawController.hxx"
+#include "DrawDocShell.hxx"
+#include "DrawViewShell.hxx"
+#include "EventMultiplexer.hxx"
+#include "SlideSorterViewShell.hxx"
+#include "ViewShellBase.hxx"
+
+#include <comphelper/processfactory.hxx>
+#include <sfx2/app.hxx>
+#include <sfx2/dispatch.hxx>
+#include <sfx2/objface.hxx>
+#include <sfx2/request.hxx>
+#include <sfx2/viewfrm.hxx>
+#include <svl/languageoptions.hxx>
+#include <vcl/image.hxx>
+#include <vcl/floatwin.hxx>
+
+#include <com/sun/star/frame/XController.hpp>
+#include <com/sun/star/drawing/framework/XControllerManager.hpp>
+#include <com/sun/star/drawing/framework/XView.hpp>
+#include <com/sun/star/drawing/framework/ResourceId.hpp>
+
+#include <vector>
+#include <memory>
+
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::text;
+using namespace ::com::sun::star::uno;
+using namespace ::com::sun::star::drawing::framework;
+using namespace ::sd::slidesorter;
+using ::sd::framework::FrameworkHelper;
+
+namespace sd { namespace sidebar {
+
+
+
+struct snewfoil_value_info
+{
+    sal_uInt16 mnBmpResId;
+    sal_uInt16 mnHCBmpResId;
+    sal_uInt16 mnStrResId;
+    WritingMode meWritingMode;
+    AutoLayout maAutoLayout;
+};
+
+static snewfoil_value_info notes[] =
+{
+    {BMP_FOILN_01, BMP_FOILN_01_H, STR_AUTOLAYOUT_NOTES, WritingMode_LR_TB,
+     AUTOLAYOUT_NOTES},
+    {0, 0, 0, WritingMode_LR_TB, AUTOLAYOUT_NONE},
+};
+
+static snewfoil_value_info handout[] =
+{
+    {BMP_FOILH_01, BMP_FOILH_01_H, STR_AUTOLAYOUT_HANDOUT1, WritingMode_LR_TB,
+     AUTOLAYOUT_HANDOUT1},
+    {BMP_FOILH_02, BMP_FOILH_02_H, STR_AUTOLAYOUT_HANDOUT2, WritingMode_LR_TB,
+     AUTOLAYOUT_HANDOUT2},
+    {BMP_FOILH_03, BMP_FOILH_03_H, STR_AUTOLAYOUT_HANDOUT3, WritingMode_LR_TB,
+     AUTOLAYOUT_HANDOUT3},
+    {BMP_FOILH_04, BMP_FOILH_04_H, STR_AUTOLAYOUT_HANDOUT4, WritingMode_LR_TB,
+     AUTOLAYOUT_HANDOUT4},
+    {BMP_FOILH_06, BMP_FOILH_06_H, STR_AUTOLAYOUT_HANDOUT6, WritingMode_LR_TB,
+     AUTOLAYOUT_HANDOUT6},
+    {BMP_FOILH_09, BMP_FOILH_09_H, STR_AUTOLAYOUT_HANDOUT9, WritingMode_LR_TB,
+     AUTOLAYOUT_HANDOUT9},
+    {0, 0, 0, WritingMode_LR_TB, AUTOLAYOUT_NONE},
+};
+
+static snewfoil_value_info standard[] =
+{
+    {BMP_LAYOUT_EMPTY, BMP_LAYOUT_EMPTY_H, STR_AUTOLAYOUT_NONE, WritingMode_LR_TB,        AUTOLAYOUT_NONE},
+	{BMP_LAYOUT_HEAD03, BMP_LAYOUT_HEAD03_H, STR_AUTOLAYOUT_TITLE, WritingMode_LR_TB,       AUTOLAYOUT_TITLE},
+    {BMP_LAYOUT_HEAD02, BMP_LAYOUT_HEAD02_H, STR_AUTOLAYOUT_CONTENT, WritingMode_LR_TB,        AUTOLAYOUT_ENUM},   
+	{BMP_LAYOUT_HEAD02A, BMP_LAYOUT_HEAD02A_H, STR_AUTOLAYOUT_2CONTENT, WritingMode_LR_TB,       AUTOLAYOUT_2TEXT},
+	{BMP_LAYOUT_HEAD01, BMP_LAYOUT_HEAD01_H, STR_AUTOLAYOUT_ONLY_TITLE, WritingMode_LR_TB,  AUTOLAYOUT_ONLY_TITLE},    
+	{BMP_LAYOUT_TEXTONLY, BMP_LAYOUT_TEXTONLY_H, STR_AUTOLAYOUT_ONLY_TEXT, WritingMode_LR_TB,   AUTOLAYOUT_ONLY_TEXT},
+    {BMP_LAYOUT_HEAD03B, BMP_LAYOUT_HEAD03B_H, STR_AUTOLAYOUT_2CONTENT_CONTENT, WritingMode_LR_TB,    AUTOLAYOUT_2OBJTEXT},
+	{BMP_LAYOUT_HEAD03C, BMP_LAYOUT_HEAD03C_H, STR_AUTOLAYOUT_CONTENT_2CONTENT, WritingMode_LR_TB,    AUTOLAYOUT_TEXT2OBJ},
+	{BMP_LAYOUT_HEAD03A, BMP_LAYOUT_HEAD03A_H, STR_AUTOLAYOUT_2CONTENT_OVER_CONTENT,WritingMode_LR_TB, AUTOLAYOUT_2OBJOVERTEXT},    
+	{BMP_LAYOUT_HEAD02B, BMP_LAYOUT_HEAD02B_H, STR_AUTOLAYOUT_CONTENT_OVER_CONTENT, WritingMode_LR_TB, AUTOLAYOUT_OBJOVERTEXT},
+    {BMP_LAYOUT_HEAD04, BMP_LAYOUT_HEAD04_H, STR_AUTOLAYOUT_4CONTENT, WritingMode_LR_TB,        AUTOLAYOUT_4OBJ},   
+	{BMP_LAYOUT_HEAD06, BMP_LAYOUT_HEAD06_H, STR_AUTOLAYOUT_6CONTENT, WritingMode_LR_TB,    AUTOLAYOUT_6CLIPART},
+
+	// vertical
+    {BMP_LAYOUT_VERTICAL02, BMP_LAYOUT_VERTICAL02_H, STR_AL_VERT_TITLE_TEXT_CHART, WritingMode_TB_RL,AUTOLAYOUT_VERTICAL_TITLE_TEXT_CHART},
+    {BMP_LAYOUT_VERTICAL01, BMP_LAYOUT_VERTICAL01_H, STR_AL_VERT_TITLE_VERT_OUTLINE, WritingMode_TB_RL, AUTOLAYOUT_VERTICAL_TITLE_VERTICAL_OUTLINE},
+    {BMP_LAYOUT_HEAD02, BMP_LAYOUT_HEAD02_H, STR_AL_TITLE_VERT_OUTLINE, WritingMode_TB_RL, AUTOLAYOUT_TITLE_VERTICAL_OUTLINE},
+    {BMP_LAYOUT_HEAD02A, BMP_LAYOUT_HEAD02A_H, STR_AL_TITLE_VERT_OUTLINE_CLIPART,   WritingMode_TB_RL, AUTOLAYOUT_TITLE_VERTICAL_OUTLINE_CLIPART},
+    {0, 0, 0, WritingMode_LR_TB, AUTOLAYOUT_NONE}
+};
+
+
+
+
+LayoutMenu::LayoutMenu (
+    ::Window* pParent,
+    ViewShellBase& rViewShellBase,
+    const cssu::Reference<css::ui::XSidebar>& rxSidebar)
+    : ValueSet (pParent),
+      DragSourceHelper(this),
+      DropTargetHelper(this),
+      mrBase(rViewShellBase),
+      mbUseOwnScrollBar(false),
+      mnPreferredColumnCount(3),
+      mxListener(NULL),
+      mbSelectionUpdatePending(true),
+      mbIsMainViewChangePending(false),
+      mxSidebar(rxSidebar),
+      mbIsDisposed(false)
+{
+    implConstruct( *mrBase.GetDocument()->GetDocSh() );
+    OSL_TRACE("created LayoutMenu at %x", this);
+    
+#ifdef DEBUG
+    SetText(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("sd:LayoutMenu")));
+#endif
+}
+
+
+
+
+void LayoutMenu::implConstruct( DrawDocShell& rDocumentShell )
+{
+    OSL_ENSURE( mrBase.GetDocument()->GetDocSh() == &rDocumentShell,
+        "LayoutMenu::implConstruct: hmm?" );
+    // if this fires, then my assumption that the rDocumentShell parameter to our first ctor is superfluous ...
+
+	SetStyle (
+        ( GetStyle()  & ~(WB_ITEMBORDER) )
+        | WB_TABSTOP
+        | WB_NO_DIRECTSELECT
+        );
+    if (mbUseOwnScrollBar)
+        SetStyle (GetStyle() | WB_VSCROLL);
+	SetExtraSpacing(2);
+	SetSelectHdl (LINK(this, LayoutMenu, ClickHandler));
+    InvalidateContent();
+
+    Link aEventListenerLink (LINK(this,LayoutMenu,EventMultiplexerListener));
+    mrBase.GetEventMultiplexer()->AddEventListener(aEventListenerLink,
+        ::sd::tools::EventMultiplexerEvent::EID_CURRENT_PAGE
+        | ::sd::tools::EventMultiplexerEvent::EID_SLIDE_SORTER_SELECTION
+        | ::sd::tools::EventMultiplexerEvent::EID_MAIN_VIEW_ADDED
+        | ::sd::tools::EventMultiplexerEvent::EID_MAIN_VIEW_REMOVED
+        | ::sd::tools::EventMultiplexerEvent::EID_CONFIGURATION_UPDATED
+        | ::sd::tools::EventMultiplexerEvent::EID_EDIT_MODE_NORMAL
+        | ::sd::tools::EventMultiplexerEvent::EID_EDIT_MODE_MASTER);
+
+    Window::SetHelpId(HID_SD_TASK_PANE_PREVIEW_LAYOUTS);
+    SetAccessibleName(SdResId(STR_TASKPANEL_LAYOUT_MENU_TITLE));
+    
+    Link aStateChangeLink (LINK(this,LayoutMenu,StateChangeHandler));
+    mxListener = new ::sd::tools::SlotStateListener(
+        aStateChangeLink,
+        Reference<frame::XDispatchProvider>(mrBase.GetController()->getFrame(), UNO_QUERY),
+        ::rtl::OUString::createFromAscii(".uno:VerticalTextState"));
+
+    SetSizePixel(GetParent()->GetSizePixel());
+    Link aWindowEventHandlerLink (LINK(this,LayoutMenu,WindowEventHandler));
+    GetParent()->AddEventListener(aWindowEventHandlerLink);
+}
+
+
+
+
+LayoutMenu::~LayoutMenu (void)
+{
+    OSL_TRACE("destroying LayoutMenu at %x", this);
+    Dispose();
+}
+
+
+
+
+void LayoutMenu::Dispose (void)
+{
+    if (mbIsDisposed)
+        return;
+
+    OSL_TRACE("disposing LayoutMenu at %x", this);
+
+    mbIsDisposed = true;
+
+    Reference<lang::XComponent> xComponent (mxListener, UNO_QUERY);
+    if (xComponent.is())
+        xComponent->dispose();
+
+    Clear();
+    Link aLink (LINK(this,LayoutMenu,EventMultiplexerListener));
+    mrBase.GetEventMultiplexer()->RemoveEventListener (aLink);
+
+    Link aWindowEventHandlerLink (LINK(this,LayoutMenu,WindowEventHandler));
+    GetParent()->RemoveEventListener(aWindowEventHandlerLink);
+}
+
+
+
+
+AutoLayout LayoutMenu::GetSelectedAutoLayout (void)
+{
+    AutoLayout aResult = AUTOLAYOUT_NONE;
+    
+    if ( ! IsNoSelection() && GetSelectItemId()!=0)
+    {
+        AutoLayout* pLayout = static_cast<AutoLayout*>(GetItemData(GetSelectItemId()));
+        if (pLayout != NULL)
+            aResult = *pLayout;
+    }
+
+    return aResult;
+}
+
+
+
+
+/** The preferred size depends on the preferred number of columns, the
+    number of items, and the size of the items.
+*/
+Size LayoutMenu::GetPreferredSize (void)
+{
+    Size aItemSize = CalcItemSizePixel (Size());
+    Size aPreferredWindowSize = CalcWindowSizePixel (
+        aItemSize, 
+         (sal_uInt16)mnPreferredColumnCount,
+        (sal_uInt16)CalculateRowCount (aItemSize,mnPreferredColumnCount));
+    return aPreferredWindowSize;
+}
+
+
+
+
+sal_Int32 LayoutMenu::GetPreferredWidth (sal_Int32 nHeight)
+{
+    sal_Int32 nPreferredWidth = 100;
+    if (GetItemCount() > 0)
+    {
+        Image aImage = GetItemImage(GetItemId(0));
+        Size aItemSize = CalcItemSizePixel (aImage.GetSizePixel());
+        if (nHeight>0 && aItemSize.Height()>0)
+        {
+            int nRowCount = nHeight / aItemSize.Height();
+            if (nRowCount <= 0)
+                nRowCount = 1;
+            int nColumnCount = (GetItemCount() + nRowCount-1) / nRowCount;
+            nPreferredWidth = nColumnCount * aItemSize.Width();
+        }
+    }
+
+    return nPreferredWidth;
+}
+
+
+
+
+ui::LayoutSize LayoutMenu::GetHeightForWidth (const sal_Int32 nWidth)
+{
+    sal_Int32 nPreferredHeight = 200;
+    if ( ! mbUseOwnScrollBar && GetItemCount()>0)
+    {
+        Image aImage = GetItemImage(GetItemId(0));
+        Size aItemSize = CalcItemSizePixel (aImage.GetSizePixel());
+        if (nWidth>0 && aItemSize.Width()>0)
+        {
+            aItemSize.Width() += 8;
+            aItemSize.Height() += 8;
+            int nColumnCount = nWidth / aItemSize.Width();
+            if (nColumnCount <= 0)
+                nColumnCount = 1;
+            else if (nColumnCount > 4)
+                nColumnCount = 4;
+            int nRowCount = (GetItemCount() + nColumnCount-1) / nColumnCount;
+            nPreferredHeight = nRowCount * aItemSize.Height();
+        }
+    }
+    return ui::LayoutSize(nPreferredHeight,nPreferredHeight,nPreferredHeight);
+}
+
+
+
+
+sal_Int32 LayoutMenu::GetMinimumWidth (void)
+{
+    sal_Int32 nMinimumWidth = 0;
+    if (GetItemCount()>0)
+    {
+        Image aImage = GetItemImage(GetItemId(0));
+        Size aItemSize = CalcItemSizePixel (aImage.GetSizePixel());
+        nMinimumWidth = aItemSize.Width();
+    }
+    return nMinimumWidth;
+}
+
+
+
+
+void LayoutMenu::UpdateEnabledState (const MasterMode eMode)
+{
+    bool bIsEnabled (false);
+
+    ::boost::shared_ptr<ViewShell> pMainViewShell (mrBase.GetMainViewShell());
+    if (pMainViewShell)
+    {
+        switch (pMainViewShell->GetShellType())
+        {
+            case ViewShell::ST_NONE:
+            case ViewShell::ST_OUTLINE:
+            case ViewShell::ST_PRESENTATION:
+            case ViewShell::ST_SIDEBAR:
+                // The complete task pane is disabled for these values or
+                // not even visible.  Disabling the LayoutMenu would be
+                // logical but unnecessary.  The main disadvantage is that
+                // after re-enabling it (typically) another panel is
+                // expanded.
+                bIsEnabled = true;
+                break;
+                
+            case ViewShell::ST_DRAW:
+            case ViewShell::ST_IMPRESS:
+            {
+                switch (eMode)
+                {
+                    case MM_UNKNOWN:
+                    {
+                        ::boost::shared_ptr<DrawViewShell> pDrawViewShell (
+                            ::boost::dynamic_pointer_cast<DrawViewShell>(pMainViewShell));
+                        if (pDrawViewShell)
+                            bIsEnabled = pDrawViewShell->GetEditMode() != EM_MASTERPAGE;
+                        break;
+                    }
+                    case MM_NORMAL:
+                        bIsEnabled = true;
+                        break;
+
+                    case MM_MASTER:
+                        bIsEnabled = false;
+                        break;
+                }
+                break;
+            }
+
+            case ViewShell::ST_HANDOUT:
+            case ViewShell::ST_NOTES:
+            case ViewShell::ST_SLIDE_SORTER:
+            default:
+                bIsEnabled = true;
+                break;
+        }
+    }
+}
+
+
+
+
+void LayoutMenu::Paint (const Rectangle& rRect)
+{
+	SetBackground (GetSettings().GetStyleSettings().GetWindowColor());
+
+    if (mbSelectionUpdatePending)
+    {
+        mbSelectionUpdatePending = false;
+        UpdateSelection();
+    }
+    ValueSet::Paint (rRect);
+
+	SetBackground (Wallpaper());
+}
+
+
+
+
+void LayoutMenu::Resize (void)
+{
+    Size aWindowSize = GetOutputSizePixel();
+    if (IsVisible() && aWindowSize.Width() > 0)
+    {
+        // Calculate the number of rows and columns.
+        if (GetItemCount() > 0)
+        {
+            Image aImage = GetItemImage(GetItemId(0));
+            Size aItemSize = CalcItemSizePixel (
+                aImage.GetSizePixel());
+            aItemSize.Width() += 8;
+            aItemSize.Height() += 8;
+            int nColumnCount = aWindowSize.Width() / aItemSize.Width();
+            if (nColumnCount < 1)
+                nColumnCount = 1;
+            else if (nColumnCount > 4)
+                nColumnCount = 4;
+
+            int nRowCount = CalculateRowCount (aItemSize, nColumnCount);
+            
+            SetColCount ((sal_uInt16)nColumnCount);
+            SetLineCount ((sal_uInt16)nRowCount);
+        }
+    }
+
+    ValueSet::Resize ();
+}
+
+
+
+
+void LayoutMenu::MouseButtonDown (const MouseEvent& rEvent)
+{
+    // As a preparation for the context menu the item under the mouse is
+    // selected.
+    if (rEvent.IsRight())
+    {
+        ReleaseMouse();
+        sal_uInt16 nIndex = GetItemId (rEvent.GetPosPixel());
+        if (nIndex > 0)
+            SelectItem(nIndex);
+    }
+    
+    ValueSet::MouseButtonDown (rEvent);
+}
+
+
+
+/*
+void LayoutMenu::GetState (SfxItemSet& rItemSet)
+{
+    // Cut and paste is not supported.  The SID_(CUT,COPY,PASTE) entries
+    // therefore must not show up in the context menu.
+    rItemSet.DisableItem (SID_CUT);
+    rItemSet.DisableItem (SID_COPY);
+    rItemSet.DisableItem (SID_PASTE);
+
+    // The SID_INSERTPAGE_LAYOUT_MENU slot depends on the SID_INSERTPAGE
+    // slot being supported elsewhere.
+    const SfxPoolItem* pItem = NULL;
+    const SfxItemState aState (
+        mrBase.GetViewFrame()->GetDispatcher()->QueryState(SID_INSERTPAGE, pItem));
+    if (aState == SFX_ITEM_DISABLED)
+        rItemSet.DisableItem(SID_INSERTPAGE_LAYOUT_MENU);
+}
+*/
+
+
+
+void LayoutMenu::InsertPageWithLayout (AutoLayout aLayout)
+{
+    ViewShell* pViewShell = mrBase.GetMainViewShell().get();
+    if (pViewShell == NULL)
+        return;
+
+    SfxViewFrame* pViewFrame = mrBase.GetViewFrame();
+    if (pViewFrame == NULL)
+        return;
+
+    SfxDispatcher* pDispatcher = pViewFrame->GetDispatcher();
+    if (pDispatcher == NULL)
+        return;
+
+    // Call SID_INSERTPAGE with the right arguments.  This is because
+    // the popup menu can not call this slot with arguments directly.
+    SfxRequest aRequest (CreateRequest(SID_INSERTPAGE, aLayout));
+    if (aRequest.GetArgs() != NULL)
+    {
+        pDispatcher->Execute(
+            SID_INSERTPAGE,
+            SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD,
+            *aRequest.GetArgs());
+    }
+    UpdateSelection();
+}
+
+
+
+
+void LayoutMenu::InvalidateContent (void)
+{
+    // The number of items may have changed.  Request a resize so that the
+    // vertical size of this control can be adapted.
+    //    RequestResize();
+
+    // Throw away the current set and fill the menu anew according to the
+    // current settings (this includes the support for vertical writing.)
+    Fill();
+
+    if (mxSidebar.is())
+        mxSidebar->requestLayout();
+}
+
+
+
+
+int LayoutMenu::CalculateRowCount (const Size&, int nColumnCount)
+{
+    int nRowCount = 0;
+
+    if (GetItemCount() > 0 && nColumnCount > 0)
+    {
+        nRowCount = (GetItemCount() + nColumnCount - 1) / nColumnCount;
+        //        nRowCount = GetOutputSizePixel().Height() / rItemSize.Height();
+        if (nRowCount < 1)
+            nRowCount = 1;
+    }
+
+    return nRowCount;
+}
+
+
+
+
+IMPL_LINK(LayoutMenu, ClickHandler, ValueSet*, EMPTYARG)
+{
+    AssignLayoutToSelectedSlides (GetSelectedAutoLayout());
+    return 0;
+}
+
+
+
+
+/** The specified layout is assigned to the current page of the view shell
+    in the center pane.
+*/
+void LayoutMenu::AssignLayoutToSelectedSlides (AutoLayout aLayout)
+{
+    using namespace ::sd::slidesorter;
+    using namespace ::sd::slidesorter::controller;
+
+    do
+    {
+        // The view shell in the center pane has to be present.
+        ViewShell* pMainViewShell = mrBase.GetMainViewShell().get();
+        if (pMainViewShell == NULL)
+            break;
+
+        // Determine if the current view is in an invalid master page mode.
+        // The handout view is always in master page mode and therefore not
+        // invalid.
+        bool bMasterPageMode (false);
+        switch (pMainViewShell->GetShellType())
+        {
+            case ViewShell::ST_NOTES:
+            case ViewShell::ST_IMPRESS:
+            {
+                DrawViewShell* pDrawViewShell = static_cast<DrawViewShell*>(pMainViewShell);
+                if (pDrawViewShell != NULL)
+                    if (pDrawViewShell->GetEditMode() == EM_MASTERPAGE)
+                        bMasterPageMode = true;
+            }
+			default:
+				break;
+        }
+        if (bMasterPageMode)
+            break;
+
+        // Get a list of all selected slides and call the SID_MODIFYPAGE
+        // slot for all of them.
+		::sd::slidesorter::SharedPageSelection pPageSelection;
+
+        // Get a list of selected pages.
+        // First we try to obtain this list from a slide sorter.  This is
+        // possible only some of the view shells in the center pane.  When
+        // no valid slide sorter is available then ask the main view shell
+        // for its current page.
+        SlideSorterViewShell* pSlideSorter = NULL;
+        switch (pMainViewShell->GetShellType())
+        {
+            case ViewShell::ST_IMPRESS:
+            case ViewShell::ST_NOTES:
+            case ViewShell::ST_SLIDE_SORTER:
+                pSlideSorter = SlideSorterViewShell::GetSlideSorter(mrBase);
+                break;
+			default:
+				break;
+        }
+		if (pSlideSorter != NULL)
+		{
+			// There is a slide sorter visible so get the list of selected pages from it.
+            pPageSelection = pSlideSorter->GetPageSelection();
+		}
+
+		if( (pSlideSorter == NULL) || (pPageSelection.get() == 0) || pPageSelection->empty() )
+		{
+			// No valid slide sorter available.  Ask the main view shell for
+			// its current page.
+            pPageSelection.reset(new ::sd::slidesorter::SlideSorterViewShell::PageSelection());
+            pPageSelection->push_back(pMainViewShell->GetActualPage());
+		}
+			
+
+		if (pPageSelection->empty())
+			break;
+
+		::std::vector<SdPage*>::iterator iPage;
+		for (iPage=pPageSelection->begin(); iPage!=pPageSelection->end(); ++iPage)
+			{
+				if ((*iPage) == NULL)
+					continue;
+
+				// Call the SID_ASSIGN_LAYOUT slot with all the necessary parameters.
+				SfxRequest aRequest (mrBase.GetViewFrame(), SID_ASSIGN_LAYOUT);
+				aRequest.AppendItem(SfxUInt32Item (ID_VAL_WHATPAGE, ((*iPage)->GetPageNum()-1)/2));
+				aRequest.AppendItem(SfxUInt32Item (ID_VAL_WHATLAYOUT, aLayout));
+				pMainViewShell->ExecuteSlot (aRequest, sal_Bool(sal_False));
+			}
+    }
+    while(false);
+}
+
+
+
+
+SfxRequest LayoutMenu::CreateRequest (
+    sal_uInt16 nSlotId,
+    AutoLayout aLayout)
+{
+    SfxRequest aRequest (mrBase.GetViewFrame(), nSlotId);
+
+    do
+    {
+        SdrLayerAdmin& rLayerAdmin (mrBase.GetDocument()->GetLayerAdmin());
+        sal_uInt8 aBackground (rLayerAdmin.GetLayerID(
+            String(SdResId(STR_LAYER_BCKGRND)), sal_False));
+        sal_uInt8 aBackgroundObject (rLayerAdmin.GetLayerID(
+            String(SdResId(STR_LAYER_BCKGRNDOBJ)), sal_False));
+        ViewShell* pViewShell = mrBase.GetMainViewShell().get();
+        if (pViewShell == NULL)
+            break;
+        SdPage* pPage = pViewShell->GetActualPage();
+        if (pPage == NULL)
+            break;
+
+        SetOfByte aVisibleLayers (pPage->TRG_GetMasterPageVisibleLayers());
+    
+        aRequest.AppendItem(
+            SfxStringItem (ID_VAL_PAGENAME, String()));//pPage->GetName()));
+        aRequest.AppendItem(SfxUInt32Item (ID_VAL_WHATLAYOUT, aLayout));
+        aRequest.AppendItem(
+            SfxBoolItem(ID_VAL_ISPAGEBACK, aVisibleLayers.IsSet(aBackground)));
+        aRequest.AppendItem(
+            SfxBoolItem(
+                ID_VAL_ISPAGEOBJ,
+                aVisibleLayers.IsSet(aBackgroundObject)));
+    }
+    while (false);
+
+    return aRequest;
+}
+
+
+
+
+void LayoutMenu::Fill (void)
+{
+	const bool bHighContrast = GetSettings().GetStyleSettings().GetHighContrastMode();
+	SvtLanguageOptions aLanguageOptions;
+    sal_Bool bVertical = aLanguageOptions.IsVerticalTextEnabled();
+    SdDrawDocument* pDocument = mrBase.GetDocument();
+    sal_Bool bRightToLeft = (pDocument!=NULL 
+        && pDocument->GetDefaultWritingMode() == WritingMode_RL_TB);
+
+    // Get URL of the view in the center pane.
+    ::rtl::OUString sCenterPaneViewName;
+    try
+    {
+        Reference<XControllerManager> xControllerManager (
+            Reference<XWeak>(&mrBase.GetDrawController()), UNO_QUERY_THROW);
+        Reference<XResourceId> xPaneId (ResourceId::create(
+            ::comphelper::getProcessComponentContext(),
+            FrameworkHelper::msCenterPaneURL));
+        Reference<XView> xView (FrameworkHelper::Instance(mrBase)->GetView(xPaneId));
+        if (xView.is())
+            sCenterPaneViewName = xView->getResourceId()->getResourceURL();
+    }
+    catch (RuntimeException&)
+    {}
+    
+	snewfoil_value_info* pInfo = NULL;
+    if (sCenterPaneViewName.equals(framework::FrameworkHelper::msNotesViewURL))
+    {
+        pInfo = notes;
+    }
+    else if (sCenterPaneViewName.equals(framework::FrameworkHelper::msHandoutViewURL))
+    {
+        pInfo = handout;
+    }
+    else if (sCenterPaneViewName.equals(framework::FrameworkHelper::msImpressViewURL)
+        || sCenterPaneViewName.equals(framework::FrameworkHelper::msSlideSorterURL))
+    {
+        pInfo = standard;
+    }
+    else
+    {
+        pInfo = NULL;
+	}
+
+    Clear();
+    int n = 0;
+	for (sal_uInt16 i=1; pInfo!=NULL&&pInfo->mnBmpResId!=0; i++,pInfo++)
+	{
+        if ((WritingMode_TB_RL != pInfo->meWritingMode) || bVertical)
+        {
+            BitmapEx aBmp (SdResId (bHighContrast 
+                             ? pInfo->mnHCBmpResId 
+                             : pInfo->mnBmpResId));
+		
+            if (bRightToLeft && (WritingMode_TB_RL != pInfo->meWritingMode))
+                aBmp.Mirror (BMP_MIRROR_HORZ);
+
+            InsertItem (i, aBmp, String (SdResId (pInfo->mnStrResId)));
+            SetItemData (i, new AutoLayout(pInfo->maAutoLayout));
+            n++;
+        }
+	}
+
+    mbSelectionUpdatePending = true;
+}
+
+
+
+
+void LayoutMenu::Clear (void)
+{
+    for (sal_uInt16 nId=1; nId<=GetItemCount(); nId++)
+        delete static_cast<AutoLayout*>(GetItemData(nId));
+    ValueSet::Clear();
+}
+
+
+
+void LayoutMenu::StartDrag (sal_Int8 , const Point& )
+{
+}
+
+
+
+
+sal_Int8 LayoutMenu::AcceptDrop (const AcceptDropEvent& )
+{
+    return 0;
+}
+
+
+
+
+sal_Int8 LayoutMenu::ExecuteDrop (const ExecuteDropEvent& )
+{
+    return 0;
+}
+
+
+
+
+void LayoutMenu::Command (const CommandEvent& rEvent)
+{
+    switch (rEvent.GetCommand())
+    {
+        case COMMAND_CONTEXTMENU:
+            if ( ! SD_MOD()->GetWaterCan())
+            {
+                // Determine the position where to show the menu.
+                Point aMenuPosition;
+                if (rEvent.IsMouseEvent())
+                {
+                    if (GetItemId(rEvent.GetMousePosPixel()) <= 0)
+                        return;
+                    aMenuPosition = rEvent.GetMousePosPixel();
+                }
+                else
+                {
+                    if (GetSelectItemId() == (sal_uInt16)-1)
+                        return;
+                    Rectangle aBBox (GetItemRect(GetSelectItemId()));
+                    aMenuPosition = aBBox.Center();
+                }
+
+                // Setup the menu.
+                ::boost::shared_ptr<PopupMenu> pMenu (new PopupMenu(SdResId(RID_TASKPANE_LAYOUTMENU_POPUP)));
+                FloatingWindow* pMenuWindow = dynamic_cast<FloatingWindow*>(pMenu->GetWindow());
+                if (pMenuWindow != NULL)
+                    pMenuWindow->SetPopupModeFlags(
+                        pMenuWindow->GetPopupModeFlags() | FLOATWIN_POPUPMODE_NOMOUSEUPCLOSE);
+                pMenu->SetSelectHdl(LINK(this, LayoutMenu, OnMenuItemSelected));
+
+                // Disable the SID_INSERTPAGE_LAYOUT_MENU item when
+                // the document is read-only.
+                const SfxPoolItem* pItem = NULL;
+                const SfxItemState aState (
+                    mrBase.GetViewFrame()->GetDispatcher()->QueryState(SID_INSERTPAGE, pItem));
+                if (aState == SFX_ITEM_DISABLED)
+                    pMenu->EnableItem(SID_INSERTPAGE_LAYOUT_MENU, sal_False);
+
+                // Show the menu.
+                pMenu->Execute(this, Rectangle(aMenuPosition,Size(1,1)), POPUPMENU_EXECUTE_DOWN);
+            }
+            break;
+
+        default:
+            ValueSet::Command(rEvent);
+            break;
+    }
+}
+
+
+
+
+IMPL_LINK(LayoutMenu, StateChangeHandler, ::rtl::OUString*, EMPTYARG)
+{
+    InvalidateContent();
+    return 0;
+}
+
+
+
+
+IMPL_LINK(LayoutMenu, OnMenuItemSelected, Menu*, pMenu)
+{
+    if (pMenu == NULL)
+    {
+        OSL_ENSURE(pMenu!=NULL, "LayoutMenu::OnMenuItemSelected: illegal menu!");
+        return 0;
+    }
+
+    pMenu->Deactivate();
+    const sal_Int32 nIndex (pMenu->GetCurItemId());
+
+    if (nIndex == SID_TP_APPLY_TO_SELECTED_SLIDES)
+    {
+        AssignLayoutToSelectedSlides(GetSelectedAutoLayout());
+    }
+    else if (nIndex == SID_INSERTPAGE_LAYOUT_MENU)
+    {
+        // Add arguments to this slot and forward it to the main view
+        // shell.
+        InsertPageWithLayout(GetSelectedAutoLayout());
+    }
+
+    return 0;
+}
+
+
+
+
+void LayoutMenu::UpdateSelection (void)
+{
+    bool bItemSelected = false;
+
+    do
+    {
+        // Get current page of main view.
+        ViewShell* pViewShell = mrBase.GetMainViewShell().get();
+        if (pViewShell == NULL)
+            break;
+        
+        SdPage* pCurrentPage = pViewShell->getCurrentPage();
+        if (pCurrentPage == NULL)
+            break;
+
+        // Get layout of current page.
+        AutoLayout aLayout (pCurrentPage->GetAutoLayout());
+        if (aLayout<AUTOLAYOUT__START || aLayout>AUTOLAYOUT__END)
+            break;
+
+        // Find the entry of the menu for to the layout.
+        sal_uInt16 nItemCount (GetItemCount());
+        for (sal_uInt16 nId=1; nId<=nItemCount; nId++)
+        {
+            if (*static_cast<AutoLayout*>(GetItemData(nId)) == aLayout)
+            {
+                SelectItem(nId);
+                bItemSelected = true;
+                break;
+            }
+        }
+    }
+    while (false);
+
+    if ( ! bItemSelected)
+        SetNoSelection();
+}
+
+
+
+
+IMPL_LINK(LayoutMenu, EventMultiplexerListener, ::sd::tools::EventMultiplexerEvent*, pEvent)
+{
+    switch (pEvent->meEventId)
+    {
+        case ::sd::tools::EventMultiplexerEvent::EID_CURRENT_PAGE:
+        case ::sd::tools::EventMultiplexerEvent::EID_SLIDE_SORTER_SELECTION:
+            if ( ! mbSelectionUpdatePending)
+                UpdateSelection();
+            break;
+
+        case ::sd::tools::EventMultiplexerEvent::EID_MAIN_VIEW_ADDED:
+            mbIsMainViewChangePending = true;
+            UpdateEnabledState(MM_UNKNOWN);
+            break;
+
+        case ::sd::tools::EventMultiplexerEvent::EID_MAIN_VIEW_REMOVED:
+            HideFocus();
+            break;
+
+        case ::sd::tools::EventMultiplexerEvent::EID_CONFIGURATION_UPDATED:
+            if (mbIsMainViewChangePending)
+            {
+                mbIsMainViewChangePending = false;
+                InvalidateContent();
+            }
+            break;
+
+        case ::sd::tools::EventMultiplexerEvent::EID_EDIT_MODE_NORMAL:
+            UpdateEnabledState(MM_NORMAL);
+            break;
+
+        case ::sd::tools::EventMultiplexerEvent::EID_EDIT_MODE_MASTER:
+            UpdateEnabledState(MM_MASTER);
+            break;
+
+        default:
+            /* Ignored */
+            break;
+    }
+
+    return 0;
+}
+
+
+
+
+IMPL_LINK(LayoutMenu, WindowEventHandler, VclWindowEvent*, pEvent)
+{
+    if (pEvent != NULL)
+    {
+        switch (pEvent->GetId())
+        {
+            case VCLEVENT_WINDOW_SHOW:
+            case VCLEVENT_WINDOW_RESIZE:
+                SetSizePixel(GetParent()->GetSizePixel());
+                return sal_True;
+
+            default:
+                return sal_False;
+        }
+
+        const SfxSimpleHint* pSimpleHint = PTR_CAST(SfxSimpleHint, pEvent);
+        if (pSimpleHint != NULL
+            && pSimpleHint->GetId() == SFX_HINT_DYING)
+        {
+            return sal_True;
+        }
+    }
+
+    return sal_False;
+}
+
+
+
+
+void LayoutMenu::DataChanged (const DataChangedEvent& rEvent)
+{
+    Fill();
+    ValueSet::DataChanged(rEvent);
+}
+
+
+
+
+
+} } // end of namespace ::sd::sidebar

Added: openoffice/branches/sidebar/main/sd/source/ui/sidebar/LayoutMenu.hxx
URL: http://svn.apache.org/viewvc/openoffice/branches/sidebar/main/sd/source/ui/sidebar/LayoutMenu.hxx?rev=1449041&view=auto
==============================================================================
--- openoffice/branches/sidebar/main/sd/source/ui/sidebar/LayoutMenu.hxx (added)
+++ openoffice/branches/sidebar/main/sd/source/ui/sidebar/LayoutMenu.hxx Fri Feb 22 13:50:42 2013
@@ -0,0 +1,225 @@
+/**************************************************************
+ * 
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * 
+ *************************************************************/
+
+#ifndef SD_SIDEBAR_LAYOUT_MENU_HXX
+#define SD_SIDEBAR_LAYOUT_MENU_HXX
+
+#include "IDisposable.hxx"
+#include "ISidebarReceiver.hxx"
+#include <sfx2/sidebar/ILayoutableWindow.hxx>
+
+#include "glob.hxx"
+#include "pres.hxx"
+
+#include <vcl/ctrl.hxx>
+#include <svtools/valueset.hxx>
+#include <svtools/transfer.hxx>
+#include <sfx2/shell.hxx>
+
+#include <com/sun/star/frame/XStatusListener.hpp>
+#include <com/sun/star/ui/XSidebar.hpp>
+
+
+class SfxModule;
+
+namespace css = ::com::sun::star;
+namespace cssu = ::com::sun::star::uno;
+
+namespace sd {
+class DrawDocShell;
+class PaneManagerEvent;
+class ViewShellBase;
+}
+
+
+namespace sd { namespace tools {
+class EventMultiplexerEvent;
+} }
+
+
+namespace sd { namespace sidebar {
+
+class ControlFactory;
+class SidebarViewShell;
+class SidebarShellManager;
+
+
+class LayoutMenu
+    : public ValueSet,
+      public DragSourceHelper, 
+      public DropTargetHelper,
+      public sfx2::sidebar::ILayoutableWindow
+{
+public:
+    /** Create a new layout menu.  Depending on the given flag it
+        displays its own scroll bar or lets a surrounding window
+        handle that.
+        @param i_pParent
+            the parent node in the control tree
+        @param i_rPanelViewShell
+            the view shell of the task pane.
+    */
+    LayoutMenu (
+        ::Window* pParent,
+        ViewShellBase& rViewShellBase,
+        const cssu::Reference<css::ui::XSidebar>& rxSidebar);
+    virtual ~LayoutMenu (void);
+
+    virtual void Dispose (void);
+    
+    /** Return a numerical value representing the currently selected
+        layout.
+    */
+    AutoLayout GetSelectedAutoLayout (void);
+
+    Size GetPreferredSize (void);
+    sal_Int32 GetPreferredWidth (sal_Int32 nHeight);
+    sal_Int32 GetMinimumWidth (void);
+
+    // From ILayoutableWindow
+    virtual css::ui::LayoutSize GetHeightForWidth (const sal_Int32 nWidth);
+
+    // From ::Window
+	virtual void Paint (const Rectangle& rRect);
+    virtual void Resize (void);
+
+    /** Show a context menu when the right mouse button is pressed.
+    */
+    virtual void MouseButtonDown (const MouseEvent& rEvent);
+
+    /** The LayoutMenu does not support some main views.  In this case the
+        LayoutMenu is disabled.  This state is updated in this method.
+        @param eMode
+            On some occasions the edit mode is being switched when this
+            method is called can not (yet) be reliably detected.  Luckily,
+            in these cases the new value is provided by some broadcaster.
+            On other occasions the edit mode is not modified and is also not
+            provided.  Therefore the Unknown value.
+    */
+    enum MasterMode { MM_NORMAL, MM_MASTER, MM_UNKNOWN };
+    void UpdateEnabledState (const MasterMode eMode);
+
+    /** Call this method when the set of displayed layouts is not up-to-date
+        anymore.  It will re-assemple this set according to the current
+        settings.
+    */
+    void InvalidateContent (void);
+
+	// DragSourceHelper
+	virtual void StartDrag (sal_Int8 nAction, const Point& rPosPixel);
+
+	// DropTargetHelper
+	virtual sal_Int8 AcceptDrop (const AcceptDropEvent& rEvent);
+	virtual sal_Int8 ExecuteDrop (const ExecuteDropEvent& rEvent);
+
+    /** The context menu is requested over this Command() method.
+    */
+	virtual void Command (const CommandEvent& rEvent);
+
+    /** Call Fill() when switching to or from high contrast mode so that the
+        correct set of icons is displayed.
+    */
+    virtual void DataChanged (const DataChangedEvent& rEvent);
+
+	using Window::GetWindow;
+	using ValueSet::StartDrag;
+
+private:
+    ViewShellBase& mrBase;
+
+    /** Do we use our own scroll bar or is viewport handling done by
+        our parent?
+    */
+    bool mbUseOwnScrollBar;
+
+    /** If we are asked for the preferred window size, then use this
+        many columns for the calculation.
+    */
+    const int mnPreferredColumnCount;
+    cssu::Reference<css::frame::XStatusListener> mxListener;
+    bool mbSelectionUpdatePending;
+    bool mbIsMainViewChangePending;
+    cssu::Reference<css::ui::XSidebar> mxSidebar;
+    bool mbIsDisposed;
+
+    /** Calculate the number of displayed rows.  This depends on the given
+        item size, the given number of columns, and the size of the
+        control.  Note that this is not the number of rows managed by the
+        valueset.  This number may be larger.  In that case a vertical
+        scroll bar is displayed.
+    */
+    int CalculateRowCount (const Size& rItemSize, int nColumnCount);
+
+    /** Fill the value set with the layouts that are applicable to the
+        current main view shell.
+    */
+    void Fill (void);
+
+    /** Remove all items from the value set.
+    */
+    void Clear (void);
+
+    /** Assign the given layout to all selected slides of a slide sorter.
+        If no slide sorter is active then this call is ignored.  The slide
+        sorter in the center pane is preferred if the choice exists.
+    */
+    void AssignLayoutToSelectedSlides (AutoLayout aLayout);
+
+    /** Insert a new page with the given layout.  The page is inserted via
+        the main view shell, i.e. its SID_INSERTPAGE slot is called.  It it
+        does not support this slot then inserting a new page does not take
+        place.  The new page is inserted after the currently active one (the
+        one returned by ViewShell::GetActualPage().)
+    */
+    void InsertPageWithLayout (AutoLayout aLayout);
+
+    /** Create a request structure that can be used with the SID_INSERTPAGE
+        and SID_MODIFYPAGE slots.  The parameters are set so that the given
+        layout is assigned to the current page of the main view shell.
+        @param nSlotId
+            Supported slots are SID_INSERTPAGE and SID_MODIFYPAGE.
+        @param aLayout
+            Layout of the page to insert or to assign.
+    */
+    SfxRequest CreateRequest (
+        sal_uInt16 nSlotId,
+        AutoLayout aLayout);
+
+    /** Select the layout that is used by the current page.
+    */
+    void UpdateSelection (void);
+
+    // internal ctor
+    void    implConstruct( DrawDocShell& rDocumentShell );
+
+    /** When clicked then set the current page of the view in the center pane.
+    */
+    DECL_LINK(ClickHandler, ValueSet*);
+    DECL_LINK(RightClickHandler, MouseEvent*);
+    DECL_LINK(StateChangeHandler, ::rtl::OUString*);
+    DECL_LINK(EventMultiplexerListener, ::sd::tools::EventMultiplexerEvent*);
+    DECL_LINK(WindowEventHandler, VclWindowEvent*);
+    DECL_LINK(OnMenuItemSelected, Menu*);
+};
+
+} } // end of namespace ::sd::toolpanel
+
+#endif

Added: openoffice/branches/sidebar/main/sd/source/ui/sidebar/MasterPageContainer.cxx
URL: http://svn.apache.org/viewvc/openoffice/branches/sidebar/main/sd/source/ui/sidebar/MasterPageContainer.cxx?rev=1449041&view=auto
==============================================================================
--- openoffice/branches/sidebar/main/sd/source/ui/sidebar/MasterPageContainer.cxx (added)
+++ openoffice/branches/sidebar/main/sd/source/ui/sidebar/MasterPageContainer.cxx Fri Feb 22 13:50:42 2013
@@ -0,0 +1,1212 @@
+/**************************************************************
+ * 
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * 
+ *************************************************************/
+
+#include "precompiled_sd.hxx"
+
+#include "MasterPageContainer.hxx"
+
+#include "MasterPageDescriptor.hxx"
+#include "MasterPageContainerFiller.hxx"
+#include "MasterPageContainerQueue.hxx"
+#include "TemplateScanner.hxx"
+#include "tools/AsynchronousTask.hxx"
+#include "strings.hrc"
+#include <algorithm>
+#include <list>
+#include <set>
+
+#include "unomodel.hxx"
+#include <com/sun/star/frame/XComponentLoader.hpp>
+#include <com/sun/star/io/XStream.hpp>
+#include <com/sun/star/io/XInputStream.hpp>
+#include <com/sun/star/lang/XSingleServiceFactory.hpp>
+#include <com/sun/star/lang/XMultiServiceFactory.hpp>
+#include <com/sun/star/uno/Reference.hxx>
+#include <com/sun/star/uno/Any.hxx>
+#include <com/sun/star/uno/Sequence.hxx>
+#include <com/sun/star/util/XCloseable.hpp>
+#include <comphelper/processfactory.hxx>
+#include <tools/urlobj.hxx>
+#include <sfx2/app.hxx>
+#include <svx/svdpage.hxx>
+#include "DrawDocShell.hxx"
+#include "drawdoc.hxx"
+#include "sdpage.hxx"
+#include <svl/itemset.hxx>
+#include <svl/eitem.hxx>
+#include "sdresid.hxx"
+#include "tools/TimerBasedTaskExecution.hxx"
+#include "pres.hxx"
+#include <osl/mutex.hxx>
+#include <boost/weak_ptr.hpp>
+
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::uno;
+
+namespace {
+
+typedef ::std::vector<sd::sidebar::SharedMasterPageDescriptor> MasterPageContainerType;
+
+} // end of anonymous namespace
+
+
+namespace sd { namespace sidebar {
+
+
+/** Inner implementation class of the MasterPageContainer.
+*/
+class MasterPageContainer::Implementation
+    : public SdGlobalResource,
+      public MasterPageContainerFiller::ContainerAdapter,
+      public MasterPageContainerQueue::ContainerAdapter
+{
+public:
+    mutable ::osl::Mutex maMutex;
+
+    static ::boost::weak_ptr<Implementation> mpInstance;
+    MasterPageContainerType maContainer;
+
+    static ::boost::shared_ptr<Implementation> Instance (void);
+
+    void LateInit (void);
+    void AddChangeListener (const Link& rLink);
+    void RemoveChangeListener (const Link& rLink);
+    void UpdatePreviewSizePixel (void);
+    Size GetPreviewSizePixel (PreviewSize eSize) const;
+
+    bool HasToken (Token aToken) const;
+    const SharedMasterPageDescriptor GetDescriptor (MasterPageContainer::Token aToken) const;
+    SharedMasterPageDescriptor GetDescriptor (MasterPageContainer::Token aToken);
+    virtual Token PutMasterPage (const SharedMasterPageDescriptor& rDescriptor);
+    void InvalidatePreview (Token aToken);
+    Image GetPreviewForToken (
+        Token aToken,
+        PreviewSize ePreviewSize);
+    PreviewState GetPreviewState (Token aToken) const;
+    bool RequestPreview (Token aToken);
+
+    Reference<frame::XModel> GetModel (void);
+    SdDrawDocument* GetDocument (void);
+
+    void FireContainerChange (
+        MasterPageContainerChangeEvent::EventType eType,
+        Token aToken,
+        bool bNotifyAsynchronously = false);
+
+    virtual bool UpdateDescriptor (
+        const SharedMasterPageDescriptor& rpDescriptor,
+        bool bForcePageObject,
+        bool bForcePreview,
+        bool bSendEvents);
+
+    void ReleaseDescriptor (Token aToken);
+
+    /** Called by the MasterPageContainerFiller to notify that all master
+        pages from template documents have been added.
+    */
+    virtual void FillingDone (void);
+
+private:
+    Implementation (void);
+    virtual ~Implementation (void);
+
+    class Deleter { public:
+        void operator() (Implementation* pObject) { delete pObject; }
+    };
+    friend class Deleter;
+
+    enum InitializationState { NOT_INITIALIZED, INITIALIZING, INITIALIZED } meInitializationState;
+
+    ::boost::scoped_ptr<MasterPageContainerQueue> mpRequestQueue;
+    ::com::sun::star::uno::Reference<com::sun::star::frame::XModel> mxModel;
+    SdDrawDocument* mpDocument;
+    PreviewRenderer maPreviewRenderer;
+    /** Remember whether the first page object has already been used to
+        determine the correct size ratio.
+    */
+    bool mbFirstPageObjectSeen;
+    
+    // The widths for the previews contain two pixels for the border that is
+    // painted arround the preview.
+    static const int SMALL_PREVIEW_WIDTH = 72 + 2;
+    static const int LARGE_PREVIEW_WIDTH = 2*72 + 2;
+
+    /** This substition of page preview shows "Preparing preview" and is
+        shown as long as the actual previews are not being present.
+    */
+    Image maLargePreviewBeingCreated;
+    Image maSmallPreviewBeingCreated;
+
+    /** This substition of page preview is shown when a preview can not be
+        created and thus is not available.
+    */
+    Image maLargePreviewNotAvailable;
+    Image maSmallPreviewNotAvailable;
+
+    ::std::vector<Link> maChangeListeners;
+
+    // We have to remember the tasks for initialization and filling in case
+    // a MasterPageContainer object is destroyed before these tasks have
+    // been completed.
+    ::boost::weak_ptr<sd::tools::TimerBasedTaskExecution> mpFillerTask;
+
+    Size maSmallPreviewSizePixel;
+    Size maLargePreviewSizePixel;
+    bool mbPageRatioKnown;
+
+    bool mbContainerCleaningPending;
+
+    typedef ::std::pair<MasterPageContainerChangeEvent::EventType,Token> EventData;
+    DECL_LINK(AsynchronousNotifyCallback, EventData*);
+    ::sd::DrawDocShell* LoadDocument (
+        const String& sFileName,
+        SfxObjectShellLock& rxDocumentShell);
+
+    Image GetPreviewSubstitution (sal_uInt16 nId, PreviewSize ePreviewSize);
+
+    void CleanContainer (void);
+};
+
+
+
+
+//===== MasterPageContainer ===================================================
+
+::boost::weak_ptr<MasterPageContainer::Implementation>
+    MasterPageContainer::Implementation::mpInstance;
+static const MasterPageContainer::Token NIL_TOKEN (-1);
+
+
+
+
+::boost::shared_ptr<MasterPageContainer::Implementation>
+    MasterPageContainer::Implementation::Instance (void)
+{
+    ::boost::shared_ptr<MasterPageContainer::Implementation> pInstance;
+    
+    if (Implementation::mpInstance.expired())
+    {
+        ::osl::GetGlobalMutex aMutexFunctor;
+        ::osl::MutexGuard aGuard (aMutexFunctor());
+        if (Implementation::mpInstance.expired())
+        {
+            OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER();
+            pInstance = ::boost::shared_ptr<MasterPageContainer::Implementation>(
+                new MasterPageContainer::Implementation(),
+                MasterPageContainer::Implementation::Deleter());
+            SdGlobalResourceContainer::Instance().AddResource(pInstance);
+            Implementation::mpInstance = pInstance;
+        }
+        else
+            pInstance = ::boost::shared_ptr<MasterPageContainer::Implementation>(
+                Implementation::mpInstance);
+    }
+    else
+    {
+        OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER();
+        pInstance = ::boost::shared_ptr<MasterPageContainer::Implementation>(
+            Implementation::mpInstance);
+    }
+
+    DBG_ASSERT (pInstance.get()!=NULL,
+        "MasterPageContainer::Implementation::Instance(): instance is NULL");
+    return pInstance;
+}
+
+
+
+
+MasterPageContainer::MasterPageContainer (void)
+    : mpImpl(Implementation::Instance()),
+      mePreviewSize(SMALL)
+{
+    mpImpl->LateInit();
+}
+
+
+
+
+MasterPageContainer::~MasterPageContainer (void)
+{
+}
+
+
+
+
+void MasterPageContainer::AddChangeListener (const Link& rLink)
+{
+    mpImpl->AddChangeListener(rLink);
+}
+
+
+
+
+void MasterPageContainer::RemoveChangeListener (const Link& rLink)
+{
+    mpImpl->RemoveChangeListener(rLink);
+}
+
+
+
+
+void MasterPageContainer::SetPreviewSize (PreviewSize eSize)
+{
+    mePreviewSize = eSize;
+    mpImpl->FireContainerChange(
+        MasterPageContainerChangeEvent::SIZE_CHANGED,
+        NIL_TOKEN);
+}
+
+
+
+
+MasterPageContainer::PreviewSize MasterPageContainer::GetPreviewSize (void) const
+{
+    return mePreviewSize;
+}
+
+
+
+
+Size MasterPageContainer::GetPreviewSizePixel (void) const
+{
+    return mpImpl->GetPreviewSizePixel(mePreviewSize);
+}
+
+
+
+
+MasterPageContainer::Token MasterPageContainer::PutMasterPage (
+    const SharedMasterPageDescriptor& rDescriptor)
+{
+    return mpImpl->PutMasterPage(rDescriptor);
+}
+
+
+
+
+void MasterPageContainer::AcquireToken (Token aToken)
+{
+    SharedMasterPageDescriptor pDescriptor = mpImpl->GetDescriptor(aToken);
+    if (pDescriptor.get() != NULL)
+    {
+        ++pDescriptor->mnUseCount;
+    }
+}
+
+
+
+
+void MasterPageContainer::ReleaseToken (Token aToken)
+{
+    SharedMasterPageDescriptor pDescriptor = mpImpl->GetDescriptor(aToken);
+    if (pDescriptor.get() != NULL)
+    {
+        OSL_ASSERT(pDescriptor->mnUseCount>0);
+        --pDescriptor->mnUseCount;
+        if (pDescriptor->mnUseCount <= 0)
+        {
+            switch (pDescriptor->meOrigin)
+            {
+                case DEFAULT:
+                case TEMPLATE:
+                default:
+                    break;
+
+                case MASTERPAGE:
+                    mpImpl->ReleaseDescriptor(aToken);
+                    break;
+            }
+        }
+    }
+}
+
+
+
+
+int MasterPageContainer::GetTokenCount (void) const
+{
+    const ::osl::MutexGuard aGuard (mpImpl->maMutex);
+
+    return mpImpl->maContainer.size();
+}
+
+
+
+
+bool MasterPageContainer::HasToken (Token aToken) const
+{
+    const ::osl::MutexGuard aGuard (mpImpl->maMutex);
+
+    return mpImpl->HasToken(aToken);
+}
+
+
+
+
+MasterPageContainer::Token MasterPageContainer::GetTokenForIndex (int nIndex)
+{
+    const ::osl::MutexGuard aGuard (mpImpl->maMutex);
+
+    Token aResult (NIL_TOKEN);
+    if (HasToken(nIndex))
+        aResult = mpImpl->maContainer[nIndex]->maToken;
+    return aResult;
+}
+
+
+
+
+MasterPageContainer::Token MasterPageContainer::GetTokenForURL (
+    const String& sURL)
+{
+    const ::osl::MutexGuard aGuard (mpImpl->maMutex);
+
+    Token aResult (NIL_TOKEN);
+    if (sURL.Len() > 0)
+    {
+        MasterPageContainerType::iterator iEntry (
+            ::std::find_if (
+                mpImpl->maContainer.begin(),
+                mpImpl->maContainer.end(),
+                MasterPageDescriptor::URLComparator(sURL)));
+        if (iEntry != mpImpl->maContainer.end())
+            aResult = (*iEntry)->maToken;
+    }
+    return aResult;
+}
+
+
+
+
+MasterPageContainer::Token MasterPageContainer::GetTokenForStyleName (const String& sStyleName)
+{
+    const ::osl::MutexGuard aGuard (mpImpl->maMutex);
+
+    Token aResult (NIL_TOKEN);
+    if (sStyleName.Len() > 0)
+    {
+        MasterPageContainerType::iterator iEntry (
+            ::std::find_if (
+                mpImpl->maContainer.begin(),
+                mpImpl->maContainer.end(),
+                MasterPageDescriptor::StyleNameComparator(sStyleName)));
+        if (iEntry != mpImpl->maContainer.end())
+            aResult = (*iEntry)->maToken;
+    }
+    return aResult;
+}
+
+
+
+
+MasterPageContainer::Token MasterPageContainer::GetTokenForPageObject (
+    const SdPage* pPage)
+{
+    const ::osl::MutexGuard aGuard (mpImpl->maMutex);
+
+    Token aResult (NIL_TOKEN);
+    if (pPage != NULL)
+    {
+        MasterPageContainerType::iterator iEntry (
+            ::std::find_if (
+                mpImpl->maContainer.begin(),
+                mpImpl->maContainer.end(),
+                MasterPageDescriptor::PageObjectComparator(pPage)));
+        if (iEntry != mpImpl->maContainer.end())
+            aResult = (*iEntry)->maToken;
+    }
+    return aResult;
+}
+
+
+
+
+String MasterPageContainer::GetURLForToken (
+    MasterPageContainer::Token aToken)
+{
+    const ::osl::MutexGuard aGuard (mpImpl->maMutex);
+
+    SharedMasterPageDescriptor pDescriptor = mpImpl->GetDescriptor(aToken);
+    if (pDescriptor.get() != NULL)
+        return pDescriptor->msURL;
+    else
+        return String();
+}
+
+
+
+
+String MasterPageContainer::GetPageNameForToken (
+    MasterPageContainer::Token aToken)
+{
+    const ::osl::MutexGuard aGuard (mpImpl->maMutex);
+
+    SharedMasterPageDescriptor pDescriptor = mpImpl->GetDescriptor(aToken);
+    if (pDescriptor.get() != NULL)
+        return pDescriptor->msPageName;
+    else
+        return String();
+}
+
+
+
+
+String MasterPageContainer::GetStyleNameForToken (
+    MasterPageContainer::Token aToken)
+{
+    const ::osl::MutexGuard aGuard (mpImpl->maMutex);
+
+    SharedMasterPageDescriptor pDescriptor = mpImpl->GetDescriptor(aToken);
+    if (pDescriptor.get() != NULL)
+        return pDescriptor->msStyleName;
+    else
+        return String();
+}
+
+
+
+
+SdPage* MasterPageContainer::GetPageObjectForToken (
+    MasterPageContainer::Token aToken,
+    bool bLoad)
+{
+    const ::osl::MutexGuard aGuard (mpImpl->maMutex);
+
+    SdPage* pPageObject = NULL;
+    SharedMasterPageDescriptor pDescriptor = mpImpl->GetDescriptor(aToken);
+    if (pDescriptor.get() != NULL)
+    {
+        pPageObject = pDescriptor->mpMasterPage;
+        if (pPageObject == NULL)
+        {
+            // The page object is not (yet) present.  Call
+            // UpdateDescriptor() to trigger the PageObjectProvider() to
+            // provide it.
+            if (bLoad)
+                mpImpl->GetModel();
+            if (mpImpl->UpdateDescriptor(pDescriptor,bLoad,false, true))
+                pPageObject = pDescriptor->mpMasterPage;
+        }
+    }
+    return pPageObject;
+}
+
+
+
+
+MasterPageContainer::Origin MasterPageContainer::GetOriginForToken (Token aToken)
+{
+    const ::osl::MutexGuard aGuard (mpImpl->maMutex);
+
+    SharedMasterPageDescriptor pDescriptor = mpImpl->GetDescriptor(aToken);
+    if (pDescriptor.get() != NULL)
+        return pDescriptor->meOrigin;
+    else
+        return UNKNOWN;
+}
+
+
+
+
+sal_Int32 MasterPageContainer::GetTemplateIndexForToken (Token aToken)
+{
+    const ::osl::MutexGuard aGuard (mpImpl->maMutex);
+
+    SharedMasterPageDescriptor pDescriptor = mpImpl->GetDescriptor(aToken);
+    if (pDescriptor.get() != NULL)
+        return pDescriptor->mnTemplateIndex;
+    else
+        return -1;
+}
+
+
+
+
+SharedMasterPageDescriptor MasterPageContainer::GetDescriptorForToken (
+    MasterPageContainer::Token aToken)
+{
+    const ::osl::MutexGuard aGuard (mpImpl->maMutex);
+
+    return mpImpl->GetDescriptor(aToken);
+}
+
+
+
+void MasterPageContainer::InvalidatePreview (MasterPageContainer::Token aToken)
+{
+    mpImpl->InvalidatePreview(aToken);
+}
+
+
+
+
+Image MasterPageContainer::GetPreviewForToken (MasterPageContainer::Token aToken)
+{
+    return mpImpl->GetPreviewForToken(aToken,mePreviewSize);
+}
+
+
+
+
+MasterPageContainer::PreviewState MasterPageContainer::GetPreviewState (Token aToken)
+{
+    return mpImpl->GetPreviewState(aToken);
+}
+
+
+
+
+bool MasterPageContainer::RequestPreview (Token aToken)
+{
+    return mpImpl->RequestPreview(aToken);
+}
+
+
+
+
+//==== Implementation ================================================
+
+MasterPageContainer::Implementation::Implementation (void)
+    : maMutex(),
+      maContainer(),
+	  meInitializationState(NOT_INITIALIZED),
+      mpRequestQueue(NULL),
+      mxModel(NULL),
+      mpDocument(NULL),
+      maPreviewRenderer(),
+      mbFirstPageObjectSeen(false),
+      maLargePreviewBeingCreated(),
+      maSmallPreviewBeingCreated(),
+      maLargePreviewNotAvailable(),
+      maSmallPreviewNotAvailable(),
+      maChangeListeners(),
+      maSmallPreviewSizePixel(),
+      maLargePreviewSizePixel(),
+      mbPageRatioKnown(false),
+      mbContainerCleaningPending(true)
+
+{
+    UpdatePreviewSizePixel();
+}
+
+
+
+
+MasterPageContainer::Implementation::~Implementation (void)
+{
+    // When the initializer or filler tasks are still running then we have
+    // to stop them now in order to prevent them from calling us back.
+    tools::TimerBasedTaskExecution::ReleaseTask(mpFillerTask);
+
+    mpRequestQueue.reset();
+
+    uno::Reference<util::XCloseable> xCloseable (mxModel, uno::UNO_QUERY);
+    if (xCloseable.is())
+    {
+        try
+        {
+            xCloseable->close(true);
+        }
+        catch (::com::sun::star::util::CloseVetoException aException)
+        {
+        }
+    }
+    mxModel = NULL;
+}
+
+
+
+
+void MasterPageContainer::Implementation::LateInit (void)
+{
+    const ::osl::MutexGuard aGuard (maMutex);
+
+    if (meInitializationState == NOT_INITIALIZED)
+    {
+        meInitializationState = INITIALIZING;
+
+        OSL_ASSERT(Instance().get()==this);
+        mpRequestQueue.reset(MasterPageContainerQueue::Create(
+            ::boost::shared_ptr<MasterPageContainerQueue::ContainerAdapter>(Instance())));
+
+        mpFillerTask = ::sd::tools::TimerBasedTaskExecution::Create(
+            ::boost::shared_ptr<tools::AsynchronousTask>(new MasterPageContainerFiller(*this)),
+            5,
+            50);
+
+        meInitializationState = INITIALIZED;
+    }
+}
+
+
+
+
+void MasterPageContainer::Implementation::AddChangeListener (const Link& rLink)
+{
+    const ::osl::MutexGuard aGuard (maMutex);
+
+    ::std::vector<Link>::iterator iListener (
+        ::std::find(maChangeListeners.begin(),maChangeListeners.end(),rLink));
+    if (iListener == maChangeListeners.end())
+        maChangeListeners.push_back(rLink);
+
+}
+
+
+
+
+void MasterPageContainer::Implementation::RemoveChangeListener (const Link& rLink)
+{
+    const ::osl::MutexGuard aGuard (maMutex);
+
+    ::std::vector<Link>::iterator iListener (
+        ::std::find(maChangeListeners.begin(),maChangeListeners.end(),rLink));
+    if (iListener != maChangeListeners.end())
+        maChangeListeners.erase(iListener);
+}
+
+
+
+
+void MasterPageContainer::Implementation::UpdatePreviewSizePixel (void)
+{
+    const ::osl::MutexGuard aGuard (maMutex);
+
+    // The default aspect ratio is 4:3
+    int nWidth (4);
+    int nHeight (3);
+    
+    // Search for the first entry with an existing master page.
+    MasterPageContainerType::const_iterator iDescriptor;
+    MasterPageContainerType::const_iterator iContainerEnd(maContainer.end());
+    for (iDescriptor=maContainer.begin(); iDescriptor!=iContainerEnd; ++iDescriptor)
+        if (*iDescriptor!=NULL && (*iDescriptor)->mpMasterPage != NULL)
+        {
+            Size aPageSize ((*iDescriptor)->mpMasterPage->GetSize());
+            nWidth = aPageSize.Width();
+            nHeight = aPageSize.Height();
+            mbFirstPageObjectSeen = true;
+            break;
+        }
+
+    maSmallPreviewSizePixel.Width() = SMALL_PREVIEW_WIDTH;
+    maLargePreviewSizePixel.Width() = LARGE_PREVIEW_WIDTH;
+
+    int nNewSmallHeight ((maSmallPreviewSizePixel.Width()-2) * nHeight / nWidth + 2);
+    int nNewLargeHeight ((maLargePreviewSizePixel.Width()-2) * nHeight / nWidth + 2);
+
+    if (nNewSmallHeight!=maSmallPreviewSizePixel.Height()
+        || nNewLargeHeight!=maLargePreviewSizePixel.Height())
+    {
+        maSmallPreviewSizePixel.Height() = nNewSmallHeight;
+        maLargePreviewSizePixel.Height() = nNewLargeHeight;
+        FireContainerChange(
+            MasterPageContainerChangeEvent::SIZE_CHANGED,
+            NIL_TOKEN);
+    }
+}
+
+
+
+
+Size MasterPageContainer::Implementation::GetPreviewSizePixel (PreviewSize eSize) const
+{
+    if (eSize == SMALL)
+        return maSmallPreviewSizePixel;
+    else
+        return maLargePreviewSizePixel;
+}
+
+
+
+
+IMPL_LINK(MasterPageContainer::Implementation,AsynchronousNotifyCallback, EventData*, pData)
+{
+    const ::osl::MutexGuard aGuard (maMutex);
+
+    if (pData != NULL)
+    {
+        FireContainerChange(pData->first, pData->second, false);
+        delete pData;
+    }
+
+    return 0;
+}
+
+
+
+
+MasterPageContainer::Token MasterPageContainer::Implementation::PutMasterPage (
+    const SharedMasterPageDescriptor& rpDescriptor)
+{
+    const ::osl::MutexGuard aGuard (maMutex);
+
+    Token aResult (NIL_TOKEN);
+
+    // Get page object and preview when that is inexpensive.
+    UpdateDescriptor(rpDescriptor,false,false, false);
+
+    // Look up the new MasterPageDescriptor and either insert it or update
+    // an already existing one.
+    MasterPageContainerType::iterator aEntry (
+        ::std::find_if (
+            maContainer.begin(),
+            maContainer.end(),
+            MasterPageDescriptor::AllComparator(rpDescriptor)));
+    if (aEntry == maContainer.end())
+    {
+        // Insert a new MasterPageDescriptor.
+        bool bIgnore (rpDescriptor->mpPageObjectProvider.get()==NULL
+            && rpDescriptor->msURL.getLength()==0);
+
+        if ( ! bIgnore)
+        {
+            if (mbContainerCleaningPending)
+                CleanContainer();
+            
+            aResult = maContainer.size();
+            rpDescriptor->SetToken(aResult);
+
+            // Templates are precious, i.e. we lock them so that they will
+            // not be destroyed when (temporarily) no one references them.
+            // They will only be deleted when the container is destroyed.
+            switch (rpDescriptor->meOrigin)
+            {
+                case TEMPLATE:
+                case DEFAULT:
+                    ++rpDescriptor->mnUseCount;
+                    break;
+
+                default:
+                    break;
+            }
+            
+            maContainer.push_back(rpDescriptor);
+            aEntry = maContainer.end()-1;
+            
+            FireContainerChange(MasterPageContainerChangeEvent::CHILD_ADDED,aResult);
+        }
+    }
+    else
+    {
+        // Update an existing MasterPageDescriptor.
+        aResult = (*aEntry)->maToken;
+        ::std::auto_ptr<std::vector<MasterPageContainerChangeEvent::EventType> > pEventTypes(
+            (*aEntry)->Update(*rpDescriptor));
+        if (pEventTypes.get()!=NULL && pEventTypes->size()>0)
+        {
+            // One or more aspects of the descriptor have changed.  Send
+            // appropriate events to the listeners.
+            UpdateDescriptor(*aEntry,false,false, true);
+            
+            std::vector<MasterPageContainerChangeEvent::EventType>::const_iterator iEventType;
+            for (iEventType=pEventTypes->begin(); iEventType!=pEventTypes->end(); ++iEventType)
+            {
+                FireContainerChange(
+                    *iEventType,
+                    (*aEntry)->maToken,
+                    false);
+            }
+        }
+    }
+
+    return aResult;
+}
+
+
+
+
+bool MasterPageContainer::Implementation::HasToken (Token aToken) const
+{
+    return aToken>=0
+        && (unsigned)aToken<maContainer.size()
+        && maContainer[aToken].get()!=NULL;
+}
+
+
+
+
+const SharedMasterPageDescriptor MasterPageContainer::Implementation::GetDescriptor (
+    Token aToken) const
+{
+    if (aToken>=0 && (unsigned)aToken<maContainer.size())
+        return maContainer[aToken];
+    else
+        return SharedMasterPageDescriptor();
+}
+
+
+
+
+SharedMasterPageDescriptor MasterPageContainer::Implementation::GetDescriptor (Token aToken)
+{
+    if (aToken>=0 && (unsigned)aToken<maContainer.size())
+        return maContainer[aToken];
+    else
+        return SharedMasterPageDescriptor();
+}
+
+
+
+
+void MasterPageContainer::Implementation::InvalidatePreview (Token aToken)
+{
+    const ::osl::MutexGuard aGuard (maMutex);
+
+    SharedMasterPageDescriptor pDescriptor (GetDescriptor(aToken));
+    if (pDescriptor.get() != NULL)
+    {
+        pDescriptor->maSmallPreview = Image();
+        pDescriptor->maLargePreview = Image();
+        RequestPreview(aToken);
+    }
+}
+
+
+
+
+Image MasterPageContainer::Implementation::GetPreviewForToken (
+    MasterPageContainer::Token aToken,
+    PreviewSize ePreviewSize)
+{
+    const ::osl::MutexGuard aGuard (maMutex);
+
+    Image aPreview;
+    PreviewState ePreviewState (GetPreviewState(aToken));
+
+    SharedMasterPageDescriptor pDescriptor = GetDescriptor(aToken);
+    
+    // When the preview is missing but inexpensively creatable then do that
+    // now.
+    if (pDescriptor.get()!=NULL)
+    {
+        if (ePreviewState == PS_CREATABLE)
+            if (UpdateDescriptor(pDescriptor, false,false, true))
+                if (pDescriptor->maLargePreview.GetSizePixel().Width() != 0)
+                    ePreviewState = PS_AVAILABLE;
+
+        switch (ePreviewState)
+        {
+            case PS_AVAILABLE:
+                aPreview = pDescriptor->GetPreview(ePreviewSize);
+                break;
+
+            case PS_PREPARING:
+                aPreview = GetPreviewSubstitution(
+                    STR_TASKPANEL_PREPARING_PREVIEW_SUBSTITUTION,
+                    ePreviewSize);
+                break;
+
+            case PS_CREATABLE:
+                aPreview = GetPreviewSubstitution(
+                    STR_TASKPANEL_PREPARING_PREVIEW_SUBSTITUTION,
+                    ePreviewSize);
+                break;
+
+            case PS_NOT_AVAILABLE:
+                aPreview = GetPreviewSubstitution(
+                    STR_TASKPANEL_NOT_AVAILABLE_SUBSTITUTION,
+                    ePreviewSize);
+                if (ePreviewSize == SMALL)
+                    pDescriptor->maSmallPreview = aPreview;
+                else
+                    pDescriptor->maLargePreview = aPreview;
+                break;
+        }
+    }
+    
+    return aPreview;
+}
+
+
+
+
+MasterPageContainer::PreviewState MasterPageContainer::Implementation::GetPreviewState (
+    Token aToken) const
+{
+    const ::osl::MutexGuard aGuard (maMutex);
+
+    PreviewState eState (PS_NOT_AVAILABLE);
+
+    SharedMasterPageDescriptor pDescriptor = GetDescriptor(aToken);
+    if (pDescriptor.get() != NULL)
+    {
+        if (pDescriptor->maLargePreview.GetSizePixel().Width() != 0)
+            eState = PS_AVAILABLE;
+        else if (pDescriptor->mpPreviewProvider.get() != NULL)
+        {
+            // The preview does not exist but can be created.  When that is
+            // not expensive then do it at once.
+            if (mpRequestQueue->HasRequest(aToken))
+                eState = PS_PREPARING;
+            else
+                eState = PS_CREATABLE;
+        }
+        else
+            eState = PS_NOT_AVAILABLE;
+    }
+
+    return eState;
+}
+
+
+
+
+bool MasterPageContainer::Implementation::RequestPreview (Token aToken)
+{
+    SharedMasterPageDescriptor pDescriptor = GetDescriptor(aToken);
+    if (pDescriptor.get() != NULL)
+        return mpRequestQueue->RequestPreview(pDescriptor);
+    else
+        return false;
+}
+
+
+
+
+Reference<frame::XModel> MasterPageContainer::Implementation::GetModel (void)
+{
+    const ::osl::MutexGuard aGuard (maMutex);
+
+    if ( ! mxModel.is())
+    {
+        // Get the desktop a s service factory.
+        ::rtl::OUString sDesktopServiceName (
+            RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.Desktop"));
+        uno::Reference<frame::XComponentLoader> xDesktop (
+            ::comphelper::getProcessServiceFactory()->createInstance(
+                sDesktopServiceName), 
+            uno::UNO_QUERY);
+
+        // Create a new model.
+        ::rtl::OUString sModelServiceName (
+            RTL_CONSTASCII_USTRINGPARAM(
+                "com.sun.star.presentation.PresentationDocument"));
+        mxModel = uno::Reference<frame::XModel>(
+            ::comphelper::getProcessServiceFactory()->createInstance(
+                sModelServiceName),
+            uno::UNO_QUERY);
+
+        // Initialize the model.
+        uno::Reference<frame::XLoadable> xLoadable (mxModel,uno::UNO_QUERY);
+        if (xLoadable.is())
+            xLoadable->initNew();
+
+        // Use its tunnel to get a pointer to its core implementation.
+        uno::Reference<lang::XUnoTunnel> xUnoTunnel (mxModel, uno::UNO_QUERY);
+        if (xUnoTunnel.is())
+        {
+            mpDocument = reinterpret_cast<SdXImpressDocument*>(
+                xUnoTunnel->getSomething(
+                    SdXImpressDocument::getUnoTunnelId()))->GetDoc();
+        }
+
+        // Create a default page.
+        uno::Reference<drawing::XDrawPagesSupplier> xSlideSupplier (mxModel, uno::UNO_QUERY);
+        if (xSlideSupplier.is())
+        {
+            uno::Reference<drawing::XDrawPages> xSlides (
+                xSlideSupplier->getDrawPages(), uno::UNO_QUERY);
+            if (xSlides.is())
+            {
+                sal_Int32 nIndex (0);
+                uno::Reference<drawing::XDrawPage> xNewPage (xSlides->insertNewByIndex(nIndex));
+                uno::Reference<beans::XPropertySet> xProperties(xNewPage, uno::UNO_QUERY);
+                if (xProperties.is())
+                    xProperties->setPropertyValue(
+                        rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Layout")),
+                        makeAny((sal_Int16)AUTOLAYOUT_TITLE));
+            }
+        }
+    }
+    return mxModel;
+}
+
+
+
+
+SdDrawDocument* MasterPageContainer::Implementation::GetDocument (void)
+{
+    GetModel();
+    return mpDocument;
+}
+
+
+
+
+Image MasterPageContainer::Implementation::GetPreviewSubstitution (
+    sal_uInt16 nId,
+    PreviewSize ePreviewSize)
+{
+    const ::osl::MutexGuard aGuard (maMutex);
+
+    Image aPreview;
+    
+    switch (nId)
+    {
+        case STR_TASKPANEL_PREPARING_PREVIEW_SUBSTITUTION:
+        {
+            Image& rPreview (ePreviewSize==SMALL
+                ? maSmallPreviewBeingCreated
+                : maLargePreviewBeingCreated);
+            if (rPreview.GetSizePixel().Width() == 0)
+            {
+                rPreview = maPreviewRenderer.RenderSubstitution(
+                    ePreviewSize==SMALL ? maSmallPreviewSizePixel : maLargePreviewSizePixel,
+                    SdResId(STR_TASKPANEL_PREPARING_PREVIEW_SUBSTITUTION));
+            }
+            aPreview = rPreview;
+        }
+        break;
+
+        case STR_TASKPANEL_NOT_AVAILABLE_SUBSTITUTION:
+        {
+            Image& rPreview (ePreviewSize==SMALL
+                ? maSmallPreviewNotAvailable
+                : maLargePreviewNotAvailable);
+            if (rPreview.GetSizePixel().Width() == 0)
+            {
+                rPreview = maPreviewRenderer.RenderSubstitution(
+                    ePreviewSize==SMALL ? maSmallPreviewSizePixel : maLargePreviewSizePixel,
+                    SdResId(STR_TASKPANEL_NOT_AVAILABLE_SUBSTITUTION));
+            }
+            aPreview = rPreview;
+        }
+        break;
+    }
+
+    return aPreview;
+}
+
+
+
+
+void MasterPageContainer::Implementation::CleanContainer (void)
+{
+    // Remove the empty elements at the end of the container.  The empty
+    // elements in the middle can not be removed because that would
+    // invalidate the references still held by others.
+    int nIndex (maContainer.size()-1);
+    while (nIndex>=0 && maContainer[nIndex].get()==NULL)
+        --nIndex;
+    maContainer.resize(++nIndex);
+}
+
+
+
+
+void MasterPageContainer::Implementation::FireContainerChange (
+    MasterPageContainerChangeEvent::EventType eType,
+    Token aToken,
+    bool bNotifyAsynchronously)
+{
+    if (bNotifyAsynchronously)
+    {
+        Application::PostUserEvent(
+            LINK(this,Implementation,AsynchronousNotifyCallback),
+            new EventData(eType,aToken));
+    }
+    else
+    {
+        ::std::vector<Link> aCopy(maChangeListeners.begin(),maChangeListeners.end());
+        ::std::vector<Link>::iterator iListener;
+        MasterPageContainerChangeEvent aEvent;
+        aEvent.meEventType = eType;
+        aEvent.maChildToken = aToken;
+        for (iListener=aCopy.begin(); iListener!=aCopy.end(); ++iListener)
+            iListener->Call(&aEvent);
+    }
+}
+
+
+
+
+bool MasterPageContainer::Implementation::UpdateDescriptor (
+    const SharedMasterPageDescriptor& rpDescriptor,
+    bool bForcePageObject,
+    bool bForcePreview,
+    bool bSendEvents)
+{
+    const ::osl::MutexGuard aGuard (maMutex);
+
+    // We have to create the page object when the preview provider needs it
+    // and the caller needs the preview.
+    bForcePageObject |= (bForcePreview
+        && rpDescriptor->mpPreviewProvider->NeedsPageObject()
+        && rpDescriptor->mpMasterPage==NULL);
+
+    // Define a cost threshold so that an update or page object or preview
+    // that is at least this cost are made at once. Updates with higher cost
+    // are scheduled for later.
+    sal_Int32 nCostThreshold (mpRequestQueue->IsEmpty() ? 5 : 0);
+
+    // Update the page object (which may be used for the preview update).
+    if (bForcePageObject)
+        GetDocument();
+    bool bPageObjectModified (rpDescriptor->UpdatePageObject(
+        (bForcePageObject ? -1 : nCostThreshold),
+        mpDocument));
+    if (bPageObjectModified && bSendEvents)
+        FireContainerChange(
+            MasterPageContainerChangeEvent::DATA_CHANGED,
+            rpDescriptor->maToken);
+    if (bPageObjectModified && ! mbFirstPageObjectSeen)
+        UpdatePreviewSizePixel();
+
+    // Update the preview.
+    bool bPreviewModified (rpDescriptor->UpdatePreview(
+        (bForcePreview ? -1 : nCostThreshold),
+        maSmallPreviewSizePixel,
+        maLargePreviewSizePixel,
+        maPreviewRenderer));
+
+    if (bPreviewModified && bSendEvents)
+        FireContainerChange(
+            MasterPageContainerChangeEvent::PREVIEW_CHANGED,
+            rpDescriptor->maToken);
+
+    return bPageObjectModified || bPreviewModified;
+}
+
+
+
+
+void MasterPageContainer::Implementation::ReleaseDescriptor (Token aToken)
+{
+    if (aToken>=0 && (unsigned)aToken<maContainer.size())
+    {
+        maContainer[aToken].reset();
+        mbContainerCleaningPending = true;
+    }
+}
+
+
+
+
+void MasterPageContainer::Implementation::FillingDone (void)
+{
+    mpRequestQueue->ProcessAllRequests();
+}
+
+
+
+} } // end of namespace sd::sidebar

Added: openoffice/branches/sidebar/main/sd/source/ui/sidebar/MasterPageContainer.hxx
URL: http://svn.apache.org/viewvc/openoffice/branches/sidebar/main/sd/source/ui/sidebar/MasterPageContainer.hxx?rev=1449041&view=auto
==============================================================================
--- openoffice/branches/sidebar/main/sd/source/ui/sidebar/MasterPageContainer.hxx (added)
+++ openoffice/branches/sidebar/main/sd/source/ui/sidebar/MasterPageContainer.hxx Fri Feb 22 13:50:42 2013
@@ -0,0 +1,214 @@
+/**************************************************************
+ * 
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * 
+ *************************************************************/
+
+#ifndef SD_SIDEBAR_PANELS_MASTER_PAGE_CONTAINER_HXX
+#define SD_SIDEBAR_PANELS_MASTER_PAGE_CONTAINER_HXX
+
+#include "MasterPageContainerProviders.hxx"
+
+#include <osl/mutex.hxx>
+#include <tools/string.hxx>
+#include <vcl/image.hxx>
+#include <memory>
+#include "PreviewRenderer.hxx"
+#include <com/sun/star/frame/XModel.hpp>
+#include <vcl/timer.hxx>
+#include "tools/SdGlobalResourceContainer.hxx"
+
+#include <boost/shared_ptr.hpp>
+
+class SdPage;
+class SdDrawDocument;
+class SfxObjectShellLock;
+
+namespace sd {
+class DrawDocShell;
+}
+
+namespace sd { namespace sidebar {
+
+class MasterPageDescriptor;
+
+/** This container manages the master pages used by the MasterPagesSelector
+    controls.  It uses internally a singleton implementation object.
+    Therefore, all MasterPageContainer object operator on the same set of
+    master pages.  Each MasterPageContainer, however, has its own
+    PreviewSize value and thus can independantly switch between large and
+    small previews.
+    
+    The container maintains its own document to store master page objects.
+    
+    For each master page container stores its URL, preview bitmap, page
+    name, and, if available, the page object.
+    
+    Entries are accessed via a Token, which is mostly a numerical index but
+    whose values do not neccessarily have to be consecutive.
+*/
+class MasterPageContainer
+{
+public:
+    typedef int Token;
+    static const Token NIL_TOKEN = -1;
+
+    MasterPageContainer (void);
+    virtual ~MasterPageContainer (void);
+
+    void AddChangeListener (const Link& rLink);
+    void RemoveChangeListener (const Link& rLink);
+
+    enum PreviewSize { SMALL, LARGE };
+    /** There are two different preview sizes, a small one and a large one.
+        Which one is used by the called container can be changed with this
+        method.
+        When the preview size is changed then all change listeners are
+        notified of this.
+    */
+    void SetPreviewSize (PreviewSize eSize);
+
+    /** Returns the preview size.
+    */
+    PreviewSize GetPreviewSize (void) const;
+
+    /** Return the preview size in pixels.
+    */
+    Size GetPreviewSizePixel (void) const;
+
+    enum PreviewState { PS_AVAILABLE, PS_CREATABLE, PS_PREPARING, PS_NOT_AVAILABLE };
+    PreviewState GetPreviewState (Token aToken);
+
+    /** This method is typically called for entries in the container for
+        which GetPreviewState() returns OS_CREATABLE.  The creation of the
+        preview is then scheduled to be executed asynchronously at a later
+        point in time.  When the preview is available the change listeners
+        will be notified.
+    */
+    bool RequestPreview (Token aToken);
+
+    /** Each entry of the container is either the first page of a template
+        document or is a master page of an Impress document. 
+    */
+    enum Origin {
+        MASTERPAGE,  // Master page of a document.
+        TEMPLATE,    // First page of a template file.
+        DEFAULT,     // Empty master page with default style.
+        UNKNOWN
+    };
+
+    /** Put the master page identified and described by the given parameters
+        into the container.  When there already is a master page with the
+        given URL, page name, or object pointer (when that is not NULL) then
+        the existing entry is replaced/updated by the given one.  Otherwise
+        a new entry is inserted.
+    */
+    Token PutMasterPage (const ::boost::shared_ptr<MasterPageDescriptor>& rDescriptor);
+    void AcquireToken (Token aToken);
+    void ReleaseToken (Token aToken);
+
+    /** This and the GetTokenForIndex() methods can be used to iterate over
+        all members of the container.
+    */
+    int GetTokenCount (void) const;
+
+    /** Determine whether the container has a member for the given token.
+    */
+    bool HasToken (Token aToken) const;
+    
+    /** Return a token for an index in the range 
+        0 <= index < GetTokenCount().
+    */
+    Token GetTokenForIndex (int nIndex);
+
+    Token GetTokenForURL (const String& sURL);
+    Token GetTokenForStyleName (const String& sStyleName);
+    Token GetTokenForPageObject (const SdPage* pPage);
+
+    String GetURLForToken (Token aToken);
+    String GetPageNameForToken (Token aToken);
+    String GetStyleNameForToken (Token aToken);
+    SdPage* GetPageObjectForToken (Token aToken, bool bLoad=true);
+    Origin GetOriginForToken (Token aToken);
+    sal_Int32 GetTemplateIndexForToken (Token aToken);
+    ::boost::shared_ptr<MasterPageDescriptor> GetDescriptorForToken (Token aToken);
+    
+    void InvalidatePreview (Token aToken);
+
+    /** Return a preview for the specified token.  When the preview is not
+        present then the PreviewProvider associated with the token is
+        executed only when that is not expensive.  It is the responsibility
+        of the caller to call RequestPreview() to do the same
+        (asynchronously) for expensive PreviewProviders.
+        Call GetPreviewState() to find out if that is necessary.
+        @param aToken
+            This token specifies for which master page to return the prview.
+            Tokens are returned for example by the GetTokenFor...() methods.
+        @return
+            The returned image is the requested preview or a substitution.
+    */
+    Image GetPreviewForToken (Token aToken);
+
+private:
+    class Implementation;
+    ::boost::shared_ptr<Implementation> mpImpl;
+    PreviewSize mePreviewSize;
+
+    /** Retrieve the preview of the document specified by the given URL.
+    */
+    static BitmapEx LoadPreviewFromURL (const ::rtl::OUString& aURL);
+};
+
+
+
+
+/** For some changes to the set of master pages in a MasterPageContainer or
+    to the data stored for each master page one or more events are sent to
+    registered listeners.
+    Each event has an event type and a token that tells the listener where
+    the change took place.
+*/
+class MasterPageContainerChangeEvent
+{
+public:
+    enum EventType {
+        // A master page was added to the container.
+        CHILD_ADDED,
+        // A master page was removed from the container.
+        CHILD_REMOVED,
+        // The preview of a master page has changed.
+        PREVIEW_CHANGED,
+        // The size of a preview has changed.
+        SIZE_CHANGED,
+        // Some of the data stored for a master page has changed.
+        DATA_CHANGED,
+        // The TemplateIndex of a master page has changed.
+        INDEX_CHANGED,
+        // More than one entries changed their TemplateIndex
+        INDEXES_CHANGED
+    } meEventType;
+
+    // Token of the container entry whose data changed or which was added or
+    // removed.
+    MasterPageContainer::Token maChildToken;
+};
+
+
+} } // end of namespace sd::sidebar
+
+#endif

Added: openoffice/branches/sidebar/main/sd/source/ui/sidebar/MasterPageContainerFiller.cxx
URL: http://svn.apache.org/viewvc/openoffice/branches/sidebar/main/sd/source/ui/sidebar/MasterPageContainerFiller.cxx?rev=1449041&view=auto
==============================================================================
--- openoffice/branches/sidebar/main/sd/source/ui/sidebar/MasterPageContainerFiller.cxx (added)
+++ openoffice/branches/sidebar/main/sd/source/ui/sidebar/MasterPageContainerFiller.cxx Fri Feb 22 13:50:42 2013
@@ -0,0 +1,191 @@
+/**************************************************************
+ * 
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * 
+ *************************************************************/
+
+#include "precompiled_sd.hxx"
+
+#include "MasterPageContainerFiller.hxx"
+
+#include "MasterPageDescriptor.hxx"
+#include "MasterPageContainerProviders.hxx"
+#include "TemplateScanner.hxx"
+
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::uno;
+
+
+namespace sd { namespace sidebar {
+
+MasterPageContainerFiller::MasterPageContainerFiller (ContainerAdapter& rpAdapter)
+    : mrContainerAdapter(rpAdapter),
+      meState(INITIALIZE_TEMPLATE_SCANNER),
+      mpScannerTask(),
+      mpLastAddedEntry(NULL),
+      mnIndex(1)
+{
+    // Add one entry for the default master page.  We use temporarily the
+    // DefaultPagePreviewProvider to prevent the rendering (and the
+    // expensive creation) of the default page.  It is replaced later on by
+    // another.
+    SharedMasterPageDescriptor pDescriptor (new MasterPageDescriptor(
+        MasterPageContainer::DEFAULT,
+        0,
+        String(),
+        String(),
+        String(),
+        false,
+        ::boost::shared_ptr<PageObjectProvider>(new DefaultPageObjectProvider()),
+        ::boost::shared_ptr<PreviewProvider>(new PagePreviewProvider())));
+    mrContainerAdapter.PutMasterPage(pDescriptor);
+}
+
+
+
+
+MasterPageContainerFiller::~MasterPageContainerFiller (void)
+{
+}
+
+
+
+
+void MasterPageContainerFiller::RunNextStep (void)
+{
+    switch (meState)
+    {
+        case INITIALIZE_TEMPLATE_SCANNER:
+            mpScannerTask.reset(new TemplateScanner());
+            meState = SCAN_TEMPLATE;
+            break;
+
+        case SCAN_TEMPLATE:
+            meState = ScanTemplate();
+            break;
+            
+        case ADD_TEMPLATE:
+            meState = AddTemplate();
+            break;
+            
+        case DONE:
+        case ERROR:
+        default:
+            break;
+    }
+
+    // When the state has just been set to DONE or ERROR then tell the
+    // container that no more templates will be coming and stop the
+    // scanning.
+    switch (meState)
+    {
+        case DONE:
+        case ERROR:
+            if (mpScannerTask.get() != NULL)
+            {
+                mrContainerAdapter.FillingDone();
+                mpScannerTask.reset();
+            }
+		default:
+			break;
+    }
+}
+
+
+
+
+bool MasterPageContainerFiller::HasNextStep (void)
+{
+    switch (meState)
+    {
+        case DONE:
+        case ERROR:
+            return false;
+            
+        default:
+            return true;
+    }
+}
+
+
+
+
+MasterPageContainerFiller::State MasterPageContainerFiller::ScanTemplate (void)
+{
+    State eState (ERROR);
+
+    if (mpScannerTask.get() != NULL)
+    {
+        if (mpScannerTask->HasNextStep())
+        {
+            mpScannerTask->RunNextStep();
+            if (mpScannerTask->GetLastAddedEntry() != mpLastAddedEntry)
+            {
+                mpLastAddedEntry = mpScannerTask->GetLastAddedEntry();
+                if (mpLastAddedEntry != NULL)
+                    eState = ADD_TEMPLATE;
+                else
+                    eState = SCAN_TEMPLATE;
+            }
+            else
+                eState = SCAN_TEMPLATE;
+        }
+        else
+            eState = DONE;
+    }
+
+    return eState;
+}
+
+
+
+
+MasterPageContainerFiller::State MasterPageContainerFiller::AddTemplate (void)
+{
+    if (mpLastAddedEntry != NULL)
+    {
+        SharedMasterPageDescriptor pDescriptor (new MasterPageDescriptor(
+            MasterPageContainer::TEMPLATE,
+            mnIndex,
+            mpLastAddedEntry->msPath,
+            mpLastAddedEntry->msTitle,
+            String(),
+            false,
+            ::boost::shared_ptr<PageObjectProvider>(
+                new TemplatePageObjectProvider(mpLastAddedEntry->msPath)),
+            ::boost::shared_ptr<PreviewProvider>(
+                new TemplatePreviewProvider(mpLastAddedEntry->msPath))));
+        // For user supplied templates we use a different preview provider:
+        // The preview in the document shows not only shapes on the master
+        // page but also shapes on the foreground.  This is misleading and
+        // therefore these previews are discarded and created directly from
+        // the page objects.
+        if (pDescriptor->GetURLClassification() == MasterPageDescriptor::URLCLASS_USER)
+            pDescriptor->mpPreviewProvider = ::boost::shared_ptr<PreviewProvider>(
+                new PagePreviewProvider());
+
+        mrContainerAdapter.PutMasterPage(pDescriptor);
+        ++mnIndex;
+    }
+
+    return SCAN_TEMPLATE;
+}
+
+
+
+} } // end of namespace sd::sidebar