<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ChartFrameloader.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 18:05:02 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "ChartFrameloader.hxx"
#include "servicenames.hxx"
#include "MediaDescriptorHelper.hxx"
#include "macros.hxx"

#ifndef _COMPHELPER_MEDIADESCRIPTOR_HXX_
#include <comphelper/mediadescriptor.hxx>
#endif

#ifndef _COM_SUN_STAR_DOCUMENT_XIMPORTER_HPP_
#include <com/sun/star/document/XImporter.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XFILTER_HPP_
#include <com/sun/star/document/XFilter.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XLOADABLE_HPP_
#include <com/sun/star/frame/XLoadable.hpp>
#endif

//.............................................................................
namespace chart
{
//.............................................................................

using namespace ::com::sun::star;

ChartFrameLoader::ChartFrameLoader(
        uno::Reference<uno::XComponentContext> const & xContext)
        : m_bCancelRequired( sal_False )
{
    m_xCC = xContext;
    m_oCancelFinished.reset();
}

ChartFrameLoader::~ChartFrameLoader()
{
}

    sal_Bool ChartFrameLoader
::impl_checkCancel()
{
    if(m_bCancelRequired)
    {
        m_oCancelFinished.set();
        return sal_True;
    }
    return sal_False;
}

//-----------------------------------------------------------------
// lang::XServiceInfo
//-----------------------------------------------------------------

APPHELPER_XSERVICEINFO_IMPL(ChartFrameLoader,CHART_FRAMELOADER_SERVICE_IMPLEMENTATION_NAME)

    uno::Sequence< rtl::OUString > ChartFrameLoader
::getSupportedServiceNames_Static()
{
    uno::Sequence< rtl::OUString > aSNS( 1 );
    aSNS.getArray()[ 0 ] = CHART_FRAMELOADER_SERVICE_NAME;
    return aSNS;
}

//-----------------------------------------------------------------
// frame::XFrameLoader
//-----------------------------------------------------------------

    sal_Bool SAL_CALL ChartFrameLoader
::load( const uno::Sequence< beans::PropertyValue >& rMediaDescriptor
        , const uno::Reference<frame::XFrame >& xFrame )
        throw (uno::RuntimeException)
{
    //@todo ? need to add as terminate listener to desktop?

    uno::Reference< frame::XModel >         xModel;
    bool bHaveLoadedModel = false;

    comphelper::MediaDescriptor aMediaDescriptor(rMediaDescriptor);
    {
        comphelper::MediaDescriptor::const_iterator aIt( aMediaDescriptor.find( aMediaDescriptor.PROP_MODEL()));
        if( aIt != aMediaDescriptor.end())
        {
            xModel.set( (*aIt).second.get< uno::Reference< frame::XModel > >());
            bHaveLoadedModel = true;
        }
    }

    //create and initialize the model
    if( ! xModel.is())
    {
        //@todo?? load mechanism to cancel during loading of document
        xModel.set(
                m_xCC->getServiceManager()->createInstanceWithContext(
                CHART_MODEL_SERVICE_IMPLEMENTATION_NAME, m_xCC )
                , uno::UNO_QUERY );

        if( impl_checkCancel() )
            return sal_False;
    }

    //create the controller(+XWindow)
    uno::Reference< frame::XController >    xController = NULL;
    uno::Reference< awt::XWindow >          xComponentWindow = NULL;
    {
        xController = uno::Reference< frame::XController >(
            m_xCC->getServiceManager()->createInstanceWithContext(
            CHART_CONTROLLER_SERVICE_IMPLEMENTATION_NAME,m_xCC )
            , uno::UNO_QUERY );

        //!!!it is a special characteristic of the example application
        //that the controller simultaniously provides the XWindow controller functionality
        xComponentWindow =
                      uno::Reference< awt::XWindow >( xController, uno::UNO_QUERY );

        if( impl_checkCancel() )
            return sal_False;
    }

    //connect frame, controller and model one to each other:
    if(xController.is()&&xModel.is())
    {
        xModel->connectController(xController);
        xModel->setCurrentController(xController);
        xController->attachModel(xModel);
        if(xFrame.is())
            xFrame->setComponent(xComponentWindow,xController);
        //creates the view and menu
        //for correct menu creation the initialized component must be already set into the frame
        xController->attachFrame(xFrame);
    }

    // call initNew() or load() at XLoadable
    if(!bHaveLoadedModel)
    try
    {
        comphelper::MediaDescriptor::const_iterator aIt( aMediaDescriptor.find( aMediaDescriptor.PROP_URL()));
        if( aIt != aMediaDescriptor.end())
        {
            ::rtl::OUString aURL( (*aIt).second.get< ::rtl::OUString >());
            if( aURL.matchAsciiL(
                RTL_CONSTASCII_STRINGPARAM( "private:factory/schart" )))
            {
                // create new file
                uno::Reference< frame::XLoadable > xLoadable( xModel, uno::UNO_QUERY_THROW );
                xLoadable->initNew();
            }
            else
            {
                aMediaDescriptor.addInputStream();
                uno::Sequence< beans::PropertyValue > aCompleteMediaDescriptor;
                aMediaDescriptor >> aCompleteMediaDescriptor;
                apphelper::MediaDescriptorHelper aMDHelper( aCompleteMediaDescriptor );

                // load file
                // @todo: replace: aMediaDescriptorHelper.getReducedForModel()
                uno::Reference< frame::XLoadable > xLoadable( xModel, uno::UNO_QUERY_THROW );
                xLoadable->load( aCompleteMediaDescriptor );

                //resize standalone files to get correct size:
                if( xComponentWindow.is() && aMDHelper.ISSET_FilterName && aMDHelper.FilterName.equals( C2U("StarChart 5.0")) )
                {
                    awt::Rectangle aRect( xComponentWindow->getPosSize() );
                    sal_Int16 nFlags=0;
                    xComponentWindow->setPosSize( aRect.X, aRect.Y, aRect.Width, aRect.Height, nFlags );
                }
            }
        }
    }
    catch( uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }

    return sal_True;
}

    void SAL_CALL ChartFrameLoader
::cancel() throw (uno::RuntimeException)
{
    m_oCancelFinished.reset();
    m_bCancelRequired = sal_True;
    m_oCancelFinished.wait();
    m_bCancelRequired = sal_False;
}

//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS changefileheader (1.4.126); FILE MERGED 2008/04/01 15:04:10 thb 1.4.126.3: #i85898# Stripping all external header guards 2008/04/01 10:50:25 thb 1.4.126.2: #i85898# Stripping all external header guards 2008/03/28 16:43:49 rt 1.4.126.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ChartFrameloader.cxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "ChartFrameloader.hxx"
#include "servicenames.hxx"
#include "MediaDescriptorHelper.hxx"
#include "macros.hxx"
#include <comphelper/mediadescriptor.hxx>
#include <com/sun/star/document/XImporter.hpp>
#include <com/sun/star/document/XFilter.hpp>
#include <com/sun/star/frame/XLoadable.hpp>

//.............................................................................
namespace chart
{
//.............................................................................

using namespace ::com::sun::star;

ChartFrameLoader::ChartFrameLoader(
        uno::Reference<uno::XComponentContext> const & xContext)
        : m_bCancelRequired( sal_False )
{
    m_xCC = xContext;
    m_oCancelFinished.reset();
}

ChartFrameLoader::~ChartFrameLoader()
{
}

    sal_Bool ChartFrameLoader
::impl_checkCancel()
{
    if(m_bCancelRequired)
    {
        m_oCancelFinished.set();
        return sal_True;
    }
    return sal_False;
}

//-----------------------------------------------------------------
// lang::XServiceInfo
//-----------------------------------------------------------------

APPHELPER_XSERVICEINFO_IMPL(ChartFrameLoader,CHART_FRAMELOADER_SERVICE_IMPLEMENTATION_NAME)

    uno::Sequence< rtl::OUString > ChartFrameLoader
::getSupportedServiceNames_Static()
{
    uno::Sequence< rtl::OUString > aSNS( 1 );
    aSNS.getArray()[ 0 ] = CHART_FRAMELOADER_SERVICE_NAME;
    return aSNS;
}

//-----------------------------------------------------------------
// frame::XFrameLoader
//-----------------------------------------------------------------

    sal_Bool SAL_CALL ChartFrameLoader
::load( const uno::Sequence< beans::PropertyValue >& rMediaDescriptor
        , const uno::Reference<frame::XFrame >& xFrame )
        throw (uno::RuntimeException)
{
    //@todo ? need to add as terminate listener to desktop?

    uno::Reference< frame::XModel >         xModel;
    bool bHaveLoadedModel = false;

    comphelper::MediaDescriptor aMediaDescriptor(rMediaDescriptor);
    {
        comphelper::MediaDescriptor::const_iterator aIt( aMediaDescriptor.find( aMediaDescriptor.PROP_MODEL()));
        if( aIt != aMediaDescriptor.end())
        {
            xModel.set( (*aIt).second.get< uno::Reference< frame::XModel > >());
            bHaveLoadedModel = true;
        }
    }

    //create and initialize the model
    if( ! xModel.is())
    {
        //@todo?? load mechanism to cancel during loading of document
        xModel.set(
                m_xCC->getServiceManager()->createInstanceWithContext(
                CHART_MODEL_SERVICE_IMPLEMENTATION_NAME, m_xCC )
                , uno::UNO_QUERY );

        if( impl_checkCancel() )
            return sal_False;
    }

    //create the controller(+XWindow)
    uno::Reference< frame::XController >    xController = NULL;
    uno::Reference< awt::XWindow >          xComponentWindow = NULL;
    {
        xController = uno::Reference< frame::XController >(
            m_xCC->getServiceManager()->createInstanceWithContext(
            CHART_CONTROLLER_SERVICE_IMPLEMENTATION_NAME,m_xCC )
            , uno::UNO_QUERY );

        //!!!it is a special characteristic of the example application
        //that the controller simultaniously provides the XWindow controller functionality
        xComponentWindow =
                      uno::Reference< awt::XWindow >( xController, uno::UNO_QUERY );

        if( impl_checkCancel() )
            return sal_False;
    }

    //connect frame, controller and model one to each other:
    if(xController.is()&&xModel.is())
    {
        xModel->connectController(xController);
        xModel->setCurrentController(xController);
        xController->attachModel(xModel);
        if(xFrame.is())
            xFrame->setComponent(xComponentWindow,xController);
        //creates the view and menu
        //for correct menu creation the initialized component must be already set into the frame
        xController->attachFrame(xFrame);
    }

    // call initNew() or load() at XLoadable
    if(!bHaveLoadedModel)
    try
    {
        comphelper::MediaDescriptor::const_iterator aIt( aMediaDescriptor.find( aMediaDescriptor.PROP_URL()));
        if( aIt != aMediaDescriptor.end())
        {
            ::rtl::OUString aURL( (*aIt).second.get< ::rtl::OUString >());
            if( aURL.matchAsciiL(
                RTL_CONSTASCII_STRINGPARAM( "private:factory/schart" )))
            {
                // create new file
                uno::Reference< frame::XLoadable > xLoadable( xModel, uno::UNO_QUERY_THROW );
                xLoadable->initNew();
            }
            else
            {
                aMediaDescriptor.addInputStream();
                uno::Sequence< beans::PropertyValue > aCompleteMediaDescriptor;
                aMediaDescriptor >> aCompleteMediaDescriptor;
                apphelper::MediaDescriptorHelper aMDHelper( aCompleteMediaDescriptor );

                // load file
                // @todo: replace: aMediaDescriptorHelper.getReducedForModel()
                uno::Reference< frame::XLoadable > xLoadable( xModel, uno::UNO_QUERY_THROW );
                xLoadable->load( aCompleteMediaDescriptor );

                //resize standalone files to get correct size:
                if( xComponentWindow.is() && aMDHelper.ISSET_FilterName && aMDHelper.FilterName.equals( C2U("StarChart 5.0")) )
                {
                    awt::Rectangle aRect( xComponentWindow->getPosSize() );
                    sal_Int16 nFlags=0;
                    xComponentWindow->setPosSize( aRect.X, aRect.Y, aRect.Width, aRect.Height, nFlags );
                }
            }
        }
    }
    catch( uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }

    return sal_True;
}

    void SAL_CALL ChartFrameLoader
::cancel() throw (uno::RuntimeException)
{
    m_oCancelFinished.reset();
    m_bCancelRequired = sal_True;
    m_oCancelFinished.wait();
    m_bCancelRequired = sal_False;
}

//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>


<commit_before><commit_msg>fixed memory leak in descriptor regression tests<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/login/wizard_controller.h"

#include <gdk/gdk.h>
#include <signal.h>
#include <sys/types.h>

#include <string>
#include <vector>

#include "app/l10n_util.h"
#include "base/command_line.h"
#include "base/logging.h"  // For NOTREACHED.
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/login_library.h"
#include "chrome/browser/chromeos/login/account_screen.h"
#include "chrome/browser/chromeos/login/background_view.h"
#include "chrome/browser/chromeos/login/existing_user_controller.h"
#include "chrome/browser/chromeos/login/network_screen.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/chromeos/login/update_screen.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "views/accelerator.h"
#include "views/painter.h"
#include "views/screen.h"
#include "views/view.h"
#include "views/widget/widget_gtk.h"

namespace {

const int kWizardScreenWidth = 700;
const int kWizardScreenHeight = 416;

// RootView of the Widget WizardController creates. Contains the contents of the
// WizardController.
class ContentView : public views::View {
 public:
  ContentView(bool paint_background, int window_x, int window_y, int screen_w,
              int screen_h)
      : window_x_(window_x),
        window_y_(window_y),
        screen_w_(screen_w),
        screen_h_(screen_h),
        accel_login_screen_(views::Accelerator(base::VKEY_L,
                                               false, true, true)) {
    if (paint_background) {
      painter_.reset(chromeos::CreateWizardPainter(
                         &chromeos::BorderDefinition::kWizardBorder));
    }

    AddAccelerator(accel_login_screen_);
  }

  ~ContentView() {
    NotificationService::current()->Notify(
        NotificationType::WIZARD_CONTENT_VIEW_DESTROYED,
        NotificationService::AllSources(),
        NotificationService::NoDetails());
  }

  bool AcceleratorPressed(const views::Accelerator& accel) {
    if (accel == accel_login_screen_) {
      WizardController* controller = WizardController::default_controller();
      if (controller)
        controller->SetCurrentScreen(controller->GetLoginScreen());
      return true;
    }

    return false;
  }

  void PaintBackground(gfx::Canvas* canvas) {
    if (painter_.get()) {
      // TODO(sky): nuke this once new login manager is in place. This needs to
      // exist because with no window manager transparency isn't really
      // supported.
      canvas->TranslateInt(-window_x_, -window_y_);
      painter_->Paint(screen_w_, screen_h_, canvas);
    }
  }

  virtual void Layout() {
    for (int i = 0; i < GetChildViewCount(); ++i) {
      views::View* cur = GetChildViewAt(i);
      if (cur->IsVisible())
        cur->SetBounds(0, 0, width(), height());
    }
  }

 private:
  scoped_ptr<views::Painter> painter_;

  const int window_x_;
  const int window_y_;
  const int screen_w_;
  const int screen_h_;

  views::Accelerator accel_login_screen_;

  DISALLOW_COPY_AND_ASSIGN(ContentView);
};

// Returns bounds of the screen to use for login wizard.
// The rect is centered within the default monitor and sized accordingly if
// |size| is not empty. Otherwise the whole monitor is occupied.
gfx::Rect CalculateScreenBounds(const gfx::Size& size) {
  gfx::Rect bounds(views::Screen::GetMonitorWorkAreaNearestWindow(NULL));
  if (!size.IsEmpty()) {
    int horizontal_diff = bounds.width() - size.width();
    int vertical_diff = bounds.height() - size.height();
    bounds.Inset(horizontal_diff / 2, vertical_diff / 2);
  }

  return bounds;
}

}  // namespace

const char WizardController::kNetworkScreenName[] = "network";
const char WizardController::kLoginScreenName[] = "login";
const char WizardController::kAccountScreenName[] = "account";
const char WizardController::kUpdateScreenName[] = "update";

// Passing this parameter as a "first screen" initiates full OOBE flow.
const char WizardController::kOutOfBoxScreenName[] = "oobe";

// Special test value that commands not to create any window yet.
const char WizardController::kTestNoScreenName[] = "test:nowindow";

// Initialize default controller.
// static
WizardController* WizardController::default_controller_ = NULL;

///////////////////////////////////////////////////////////////////////////////
// WizardController, public:
WizardController::WizardController()
    : widget_(NULL),
      background_widget_(NULL),
      background_view_(NULL),
      contents_(NULL),
      current_screen_(NULL),
      is_out_of_box_(false),
      observer_(NULL) {
  DCHECK(default_controller_ == NULL);
  default_controller_ = this;
}

WizardController::~WizardController() {
  // Close ends up deleting the widget.
  if (background_widget_)
    background_widget_->Close();

  if (widget_)
    widget_->Close();

  default_controller_ = NULL;
}

void WizardController::Init(const std::string& first_screen_name,
                            const gfx::Rect& screen_bounds,
                            bool paint_background) {
  DCHECK(!contents_);

  int offset_x = (screen_bounds.width() - kWizardScreenWidth) / 2;
  int offset_y = (screen_bounds.height() - kWizardScreenHeight) / 2;
  int window_x = screen_bounds.x() + offset_x;
  int window_y = screen_bounds.y() + offset_y;

  contents_ = new ContentView(paint_background,
                              offset_x, offset_y,
                              screen_bounds.width(), screen_bounds.height());

  views::WidgetGtk* window =
      new views::WidgetGtk(views::WidgetGtk::TYPE_WINDOW);
  widget_ = window;
  if (!paint_background)
    window->MakeTransparent();
  window->Init(NULL, gfx::Rect(window_x, window_y, kWizardScreenWidth,
                               kWizardScreenHeight));
  chromeos::WmIpc::instance()->SetWindowType(
      window->GetNativeView(),
      chromeos::WmIpc::WINDOW_TYPE_LOGIN_GUEST,
      NULL);
  window->SetContentsView(contents_);

  if (chromeos::UserManager::Get()->GetUsers().empty() ||
      first_screen_name == kOutOfBoxScreenName) {
    is_out_of_box_ = true;
  }

  ShowFirstScreen(first_screen_name);

  // This keeps the window from flashing at startup.
  GdkWindow* gdk_window = window->GetNativeView()->window;
  gdk_window_set_back_pixmap(gdk_window, NULL, false);
}

void WizardController::Show() {
  DCHECK(widget_);
  widget_->Show();
}

void WizardController::ShowBackground(const gfx::Rect& bounds) {
  DCHECK(!background_widget_);
  background_widget_ =
      chromeos::BackgroundView::CreateWindowContainingView(bounds,
                                                           &background_view_);
  background_widget_->Show();
}

void WizardController::OwnBackground(
    views::Widget* background_widget,
    chromeos::BackgroundView* background_view) {
  DCHECK(!background_widget_);
  background_widget_ = background_widget;
  background_view_ = background_view;
}

chromeos::NetworkScreen* WizardController::GetNetworkScreen() {
  if (!network_screen_.get())
    network_screen_.reset(new chromeos::NetworkScreen(this, is_out_of_box_));
  return network_screen_.get();
}

LoginScreen* WizardController::GetLoginScreen() {
  if (!login_screen_.get())
    login_screen_.reset(new LoginScreen(this));
  return login_screen_.get();
}

chromeos::AccountScreen* WizardController::GetAccountScreen() {
  if (!account_screen_.get())
    account_screen_.reset(new chromeos::AccountScreen(this));
  return account_screen_.get();
}

chromeos::UpdateScreen* WizardController::GetUpdateScreen() {
  if (!update_screen_.get())
    update_screen_.reset(new chromeos::UpdateScreen(this));
  return update_screen_.get();
}

void WizardController::SetCurrentScreen(WizardScreen* new_current) {
  if (current_screen_)
    current_screen_->Hide();
  current_screen_ = new_current;
  if (current_screen_) {
    current_screen_->Show();
    contents_->Layout();
  }
  contents_->SchedulePaint();
}

///////////////////////////////////////////////////////////////////////////////
// WizardController, ExitHandlers:
void WizardController::OnLoginSignInSelected() {
  // We're on the stack, so don't try and delete us now.
  MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}

void WizardController::OnLoginCreateAccount() {
  SetCurrentScreen(GetAccountScreen());
}

void WizardController::OnNetworkConnected() {
  if (is_out_of_box_) {
    SetCurrentScreen(GetUpdateScreen());
    update_screen_->StartUpdate();
  } else {
    SetCurrentScreen(GetLoginScreen());
  }
}

void WizardController::OnNetworkOffline() {
  // TODO(dpolukhin): if(is_out_of_box_) we cannot work offline and
  // should report some error message here and stay on the same screen.
  SetCurrentScreen(GetLoginScreen());
}

void WizardController::OnAccountCreateBack() {
  SetCurrentScreen(GetLoginScreen());
}

void WizardController::OnAccountCreated() {
  LoginScreen* login = GetLoginScreen();
  SetCurrentScreen(login);
  if (!username_.empty()) {
    login->view()->SetUsername(username_);
    if (!password_.empty()) {
      login->view()->SetPassword(password_);
      // TODO(dpolukhin): clear password memory for real. Now it is not
      // a problem becuase we can't extract password from the form.
      password_.clear();
      login->view()->Login();
    }
  }
}

void WizardController::OnConnectionFailed() {
  // TODO(dpolukhin): show error message before going back to network screen.
  is_out_of_box_ = false;
  SetCurrentScreen(GetNetworkScreen());
}

void WizardController::OnUpdateCompleted() {
  SetCurrentScreen(GetLoginScreen());
}

void WizardController::OnUpdateNetworkError() {
  // If network connection got interrupted while downloading the update,
  // return to network selection screen.
  // TODO(nkostylev): Show message to the user explaining update error.
  SetCurrentScreen(GetNetworkScreen());
}

///////////////////////////////////////////////////////////////////////////////
// WizardController, private:

void WizardController::OnSetUserNamePassword(const std::string& username,
                                             const std::string& password) {
  username_ = username;
  password_ = password;
}

void WizardController::ShowFirstScreen(const std::string& first_screen_name) {
  if (first_screen_name == kNetworkScreenName) {
    SetCurrentScreen(GetNetworkScreen());
  } else if (first_screen_name == kLoginScreenName) {
    SetCurrentScreen(GetLoginScreen());
  } else if (first_screen_name == kAccountScreenName) {
    SetCurrentScreen(GetAccountScreen());
  } else if (first_screen_name == kUpdateScreenName) {
    SetCurrentScreen(GetUpdateScreen());
    update_screen_->StartUpdate();
  } else if (first_screen_name != kTestNoScreenName) {
    if (is_out_of_box_) {
      SetCurrentScreen(GetNetworkScreen());
    } else {
      SetCurrentScreen(GetLoginScreen());
    }
  }
}

///////////////////////////////////////////////////////////////////////////////
// WizardController, chromeos::ScreenObserver overrides:
void WizardController::OnExit(ExitCodes exit_code) {
  switch (exit_code) {
    case LOGIN_SIGN_IN_SELECTED:
      OnLoginSignInSelected();
      break;
    case LOGIN_CREATE_ACCOUNT:
      OnLoginCreateAccount();
      break;
    case NETWORK_CONNECTED:
      OnNetworkConnected();
      break;
    case NETWORK_OFFLINE:
      OnNetworkOffline();
      break;
    case ACCOUNT_CREATE_BACK:
      OnAccountCreateBack();
      break;
    case ACCOUNT_CREATED:
      OnAccountCreated();
      break;
    case CONNECTION_FAILED:
      OnConnectionFailed();
      break;
    case UPDATE_INSTALLED:
    case UPDATE_NOUPDATE:
      OnUpdateCompleted();
      break;
    case UPDATE_NETWORK_ERROR:
    case UPDATE_OTHER_ERROR:
      OnUpdateNetworkError();
      break;
    default:
      NOTREACHED();
  }
}

///////////////////////////////////////////////////////////////////////////////
// WizardController, WizardScreen overrides:
views::View* WizardController::GetWizardView() {
  return contents_;
}

chromeos::ScreenObserver* WizardController::GetObserver(WizardScreen* screen) {
  return observer_ ? observer_ : this;
}

namespace browser {

// Declared in browser_dialogs.h so that others don't need to depend on our .h.
void ShowLoginWizard(const std::string& first_screen_name,
                     const gfx::Size& size) {
  gfx::Rect screen_bounds(CalculateScreenBounds(size));

  if (first_screen_name.empty() &&
      chromeos::CrosLibrary::Get()->EnsureLoaded() &&
      CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnableLoginImages)) {
    std::vector<chromeos::UserManager::User> users =
        chromeos::UserManager::Get()->GetUsers();
    if (!users.empty()) {
      // ExistingUserController deletes itself.
      (new chromeos::ExistingUserController(users, screen_bounds))->Init();
      return;
    }
  }

  WizardController* controller = new WizardController();
  controller->ShowBackground(screen_bounds);
  controller->Init(first_screen_name, screen_bounds, true);
  controller->Show();
  if (chromeos::CrosLibrary::Get()->EnsureLoaded())
    chromeos::CrosLibrary::Get()->GetLoginLibrary()->EmitLoginPromptReady();
}

}  // namespace browser
<commit_msg>Added more keyboard shortcuts for other wizard screens.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/login/wizard_controller.h"

#include <gdk/gdk.h>
#include <signal.h>
#include <sys/types.h>

#include <string>
#include <vector>

#include "app/l10n_util.h"
#include "base/command_line.h"
#include "base/logging.h"  // For NOTREACHED.
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/login_library.h"
#include "chrome/browser/chromeos/login/account_screen.h"
#include "chrome/browser/chromeos/login/background_view.h"
#include "chrome/browser/chromeos/login/existing_user_controller.h"
#include "chrome/browser/chromeos/login/network_screen.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/chromeos/login/update_screen.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "views/accelerator.h"
#include "views/painter.h"
#include "views/screen.h"
#include "views/view.h"
#include "views/widget/widget_gtk.h"

namespace {

const int kWizardScreenWidth = 700;
const int kWizardScreenHeight = 416;

// RootView of the Widget WizardController creates. Contains the contents of the
// WizardController.
class ContentView : public views::View {
 public:
  ContentView(bool paint_background, int window_x, int window_y, int screen_w,
              int screen_h)
      : window_x_(window_x),
        window_y_(window_y),
        screen_w_(screen_w),
        screen_h_(screen_h),
        accel_account_screen_(views::Accelerator(base::VKEY_A,
                                                 false, true, true)),
        accel_login_screen_(views::Accelerator(base::VKEY_L,
                                               false, true, true)),
        accel_network_screen_(views::Accelerator(base::VKEY_N,
                                                 false, true, true)),
        accel_update_screen_(views::Accelerator(base::VKEY_U,
                                                false, true, true)) {
    if (paint_background) {
      painter_.reset(chromeos::CreateWizardPainter(
                         &chromeos::BorderDefinition::kWizardBorder));
    }

    AddAccelerator(accel_account_screen_);
    AddAccelerator(accel_login_screen_);
    AddAccelerator(accel_network_screen_);
    AddAccelerator(accel_update_screen_);
  }

  ~ContentView() {
    NotificationService::current()->Notify(
        NotificationType::WIZARD_CONTENT_VIEW_DESTROYED,
        NotificationService::AllSources(),
        NotificationService::NoDetails());
  }

  bool AcceleratorPressed(const views::Accelerator& accel) {
    WizardController* controller = WizardController::default_controller();
    if (!controller)
      return false;

    if (accel == accel_account_screen_) {
      controller->SetCurrentScreen(controller->GetAccountScreen());
    } else if (accel == accel_login_screen_) {
      controller->SetCurrentScreen(controller->GetLoginScreen());
    } else if (accel == accel_network_screen_) {
      controller->SetCurrentScreen(controller->GetNetworkScreen());
    } else if (accel == accel_update_screen_) {
      controller->SetCurrentScreen(controller->GetUpdateScreen());
    } else {
      return false;
    }

    return true;
  }

  void PaintBackground(gfx::Canvas* canvas) {
    if (painter_.get()) {
      // TODO(sky): nuke this once new login manager is in place. This needs to
      // exist because with no window manager transparency isn't really
      // supported.
      canvas->TranslateInt(-window_x_, -window_y_);
      painter_->Paint(screen_w_, screen_h_, canvas);
    }
  }

  virtual void Layout() {
    for (int i = 0; i < GetChildViewCount(); ++i) {
      views::View* cur = GetChildViewAt(i);
      if (cur->IsVisible())
        cur->SetBounds(0, 0, width(), height());
    }
  }

 private:
  scoped_ptr<views::Painter> painter_;

  const int window_x_;
  const int window_y_;
  const int screen_w_;
  const int screen_h_;

  views::Accelerator accel_account_screen_;
  views::Accelerator accel_login_screen_;
  views::Accelerator accel_network_screen_;
  views::Accelerator accel_update_screen_;

  DISALLOW_COPY_AND_ASSIGN(ContentView);
};

// Returns bounds of the screen to use for login wizard.
// The rect is centered within the default monitor and sized accordingly if
// |size| is not empty. Otherwise the whole monitor is occupied.
gfx::Rect CalculateScreenBounds(const gfx::Size& size) {
  gfx::Rect bounds(views::Screen::GetMonitorWorkAreaNearestWindow(NULL));
  if (!size.IsEmpty()) {
    int horizontal_diff = bounds.width() - size.width();
    int vertical_diff = bounds.height() - size.height();
    bounds.Inset(horizontal_diff / 2, vertical_diff / 2);
  }

  return bounds;
}

}  // namespace

const char WizardController::kNetworkScreenName[] = "network";
const char WizardController::kLoginScreenName[] = "login";
const char WizardController::kAccountScreenName[] = "account";
const char WizardController::kUpdateScreenName[] = "update";

// Passing this parameter as a "first screen" initiates full OOBE flow.
const char WizardController::kOutOfBoxScreenName[] = "oobe";

// Special test value that commands not to create any window yet.
const char WizardController::kTestNoScreenName[] = "test:nowindow";

// Initialize default controller.
// static
WizardController* WizardController::default_controller_ = NULL;

///////////////////////////////////////////////////////////////////////////////
// WizardController, public:
WizardController::WizardController()
    : widget_(NULL),
      background_widget_(NULL),
      background_view_(NULL),
      contents_(NULL),
      current_screen_(NULL),
      is_out_of_box_(false),
      observer_(NULL) {
  DCHECK(default_controller_ == NULL);
  default_controller_ = this;
}

WizardController::~WizardController() {
  // Close ends up deleting the widget.
  if (background_widget_)
    background_widget_->Close();

  if (widget_)
    widget_->Close();

  default_controller_ = NULL;
}

void WizardController::Init(const std::string& first_screen_name,
                            const gfx::Rect& screen_bounds,
                            bool paint_background) {
  DCHECK(!contents_);

  int offset_x = (screen_bounds.width() - kWizardScreenWidth) / 2;
  int offset_y = (screen_bounds.height() - kWizardScreenHeight) / 2;
  int window_x = screen_bounds.x() + offset_x;
  int window_y = screen_bounds.y() + offset_y;

  contents_ = new ContentView(paint_background,
                              offset_x, offset_y,
                              screen_bounds.width(), screen_bounds.height());

  views::WidgetGtk* window =
      new views::WidgetGtk(views::WidgetGtk::TYPE_WINDOW);
  widget_ = window;
  if (!paint_background)
    window->MakeTransparent();
  window->Init(NULL, gfx::Rect(window_x, window_y, kWizardScreenWidth,
                               kWizardScreenHeight));
  chromeos::WmIpc::instance()->SetWindowType(
      window->GetNativeView(),
      chromeos::WmIpc::WINDOW_TYPE_LOGIN_GUEST,
      NULL);
  window->SetContentsView(contents_);

  if (chromeos::UserManager::Get()->GetUsers().empty() ||
      first_screen_name == kOutOfBoxScreenName) {
    is_out_of_box_ = true;
  }

  ShowFirstScreen(first_screen_name);

  // This keeps the window from flashing at startup.
  GdkWindow* gdk_window = window->GetNativeView()->window;
  gdk_window_set_back_pixmap(gdk_window, NULL, false);
}

void WizardController::Show() {
  DCHECK(widget_);
  widget_->Show();
}

void WizardController::ShowBackground(const gfx::Rect& bounds) {
  DCHECK(!background_widget_);
  background_widget_ =
      chromeos::BackgroundView::CreateWindowContainingView(bounds,
                                                           &background_view_);
  background_widget_->Show();
}

void WizardController::OwnBackground(
    views::Widget* background_widget,
    chromeos::BackgroundView* background_view) {
  DCHECK(!background_widget_);
  background_widget_ = background_widget;
  background_view_ = background_view;
}

chromeos::NetworkScreen* WizardController::GetNetworkScreen() {
  if (!network_screen_.get())
    network_screen_.reset(new chromeos::NetworkScreen(this, is_out_of_box_));
  return network_screen_.get();
}

LoginScreen* WizardController::GetLoginScreen() {
  if (!login_screen_.get())
    login_screen_.reset(new LoginScreen(this));
  return login_screen_.get();
}

chromeos::AccountScreen* WizardController::GetAccountScreen() {
  if (!account_screen_.get())
    account_screen_.reset(new chromeos::AccountScreen(this));
  return account_screen_.get();
}

chromeos::UpdateScreen* WizardController::GetUpdateScreen() {
  if (!update_screen_.get())
    update_screen_.reset(new chromeos::UpdateScreen(this));
  return update_screen_.get();
}

void WizardController::SetCurrentScreen(WizardScreen* new_current) {
  if (current_screen_)
    current_screen_->Hide();
  current_screen_ = new_current;
  if (current_screen_) {
    current_screen_->Show();
    contents_->Layout();
  }
  contents_->SchedulePaint();
}

///////////////////////////////////////////////////////////////////////////////
// WizardController, ExitHandlers:
void WizardController::OnLoginSignInSelected() {
  // We're on the stack, so don't try and delete us now.
  MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}

void WizardController::OnLoginCreateAccount() {
  SetCurrentScreen(GetAccountScreen());
}

void WizardController::OnNetworkConnected() {
  if (is_out_of_box_) {
    SetCurrentScreen(GetUpdateScreen());
    update_screen_->StartUpdate();
  } else {
    SetCurrentScreen(GetLoginScreen());
  }
}

void WizardController::OnNetworkOffline() {
  // TODO(dpolukhin): if(is_out_of_box_) we cannot work offline and
  // should report some error message here and stay on the same screen.
  SetCurrentScreen(GetLoginScreen());
}

void WizardController::OnAccountCreateBack() {
  SetCurrentScreen(GetLoginScreen());
}

void WizardController::OnAccountCreated() {
  LoginScreen* login = GetLoginScreen();
  SetCurrentScreen(login);
  if (!username_.empty()) {
    login->view()->SetUsername(username_);
    if (!password_.empty()) {
      login->view()->SetPassword(password_);
      // TODO(dpolukhin): clear password memory for real. Now it is not
      // a problem becuase we can't extract password from the form.
      password_.clear();
      login->view()->Login();
    }
  }
}

void WizardController::OnConnectionFailed() {
  // TODO(dpolukhin): show error message before going back to network screen.
  is_out_of_box_ = false;
  SetCurrentScreen(GetNetworkScreen());
}

void WizardController::OnUpdateCompleted() {
  SetCurrentScreen(GetLoginScreen());
}

void WizardController::OnUpdateNetworkError() {
  // If network connection got interrupted while downloading the update,
  // return to network selection screen.
  // TODO(nkostylev): Show message to the user explaining update error.
  SetCurrentScreen(GetNetworkScreen());
}

///////////////////////////////////////////////////////////////////////////////
// WizardController, private:

void WizardController::OnSetUserNamePassword(const std::string& username,
                                             const std::string& password) {
  username_ = username;
  password_ = password;
}

void WizardController::ShowFirstScreen(const std::string& first_screen_name) {
  if (first_screen_name == kNetworkScreenName) {
    SetCurrentScreen(GetNetworkScreen());
  } else if (first_screen_name == kLoginScreenName) {
    SetCurrentScreen(GetLoginScreen());
  } else if (first_screen_name == kAccountScreenName) {
    SetCurrentScreen(GetAccountScreen());
  } else if (first_screen_name == kUpdateScreenName) {
    SetCurrentScreen(GetUpdateScreen());
    update_screen_->StartUpdate();
  } else if (first_screen_name != kTestNoScreenName) {
    if (is_out_of_box_) {
      SetCurrentScreen(GetNetworkScreen());
    } else {
      SetCurrentScreen(GetLoginScreen());
    }
  }
}

///////////////////////////////////////////////////////////////////////////////
// WizardController, chromeos::ScreenObserver overrides:
void WizardController::OnExit(ExitCodes exit_code) {
  switch (exit_code) {
    case LOGIN_SIGN_IN_SELECTED:
      OnLoginSignInSelected();
      break;
    case LOGIN_CREATE_ACCOUNT:
      OnLoginCreateAccount();
      break;
    case NETWORK_CONNECTED:
      OnNetworkConnected();
      break;
    case NETWORK_OFFLINE:
      OnNetworkOffline();
      break;
    case ACCOUNT_CREATE_BACK:
      OnAccountCreateBack();
      break;
    case ACCOUNT_CREATED:
      OnAccountCreated();
      break;
    case CONNECTION_FAILED:
      OnConnectionFailed();
      break;
    case UPDATE_INSTALLED:
    case UPDATE_NOUPDATE:
      OnUpdateCompleted();
      break;
    case UPDATE_NETWORK_ERROR:
    case UPDATE_OTHER_ERROR:
      OnUpdateNetworkError();
      break;
    default:
      NOTREACHED();
  }
}

///////////////////////////////////////////////////////////////////////////////
// WizardController, WizardScreen overrides:
views::View* WizardController::GetWizardView() {
  return contents_;
}

chromeos::ScreenObserver* WizardController::GetObserver(WizardScreen* screen) {
  return observer_ ? observer_ : this;
}

namespace browser {

// Declared in browser_dialogs.h so that others don't need to depend on our .h.
void ShowLoginWizard(const std::string& first_screen_name,
                     const gfx::Size& size) {
  gfx::Rect screen_bounds(CalculateScreenBounds(size));

  if (first_screen_name.empty() &&
      chromeos::CrosLibrary::Get()->EnsureLoaded() &&
      CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnableLoginImages)) {
    std::vector<chromeos::UserManager::User> users =
        chromeos::UserManager::Get()->GetUsers();
    if (!users.empty()) {
      // ExistingUserController deletes itself.
      (new chromeos::ExistingUserController(users, screen_bounds))->Init();
      return;
    }
  }

  WizardController* controller = new WizardController();
  controller->ShowBackground(screen_bounds);
  controller->Init(first_screen_name, screen_bounds, true);
  controller->Show();
  if (chromeos::CrosLibrary::Get()->EnsureLoaded())
    chromeos::CrosLibrary::Get()->GetLoginLibrary()->EmitLoginPromptReady();
}

}  // namespace browser
<|endoftext|>


<commit_before>/*
Copyright 2016 Colin Girling

Licensed 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 OCL_GUARD_TEST_TESTCLASSSHAREDDATA_HPP
#define OCL_GUARD_TEST_TESTCLASSSHAREDDATA_HPP

#include "StdioTestLog.hpp"
#include <cstddef>

namespace ocl
{

/**
 * All shared data for every test which is derived from TestClass
 * is in TestClassSharedData class.
 */
template<typename SizeType>
class TestClassSharedData
{
friend class TestClass;

public:
    TestClassSharedData()
        : m_logger(NULL)
        , m_max_member_function_length(0)
        , m_constructions(0)
        , m_logged_line(0)
        , m_total_checks(0)
        , m_total_not_tested(0)
        , m_total_failed_tests(0)
        , m_total_functions_tested(0)
        , m_total_timed_functions(0)
        , m_total_tests(0)

        // Padded to be lined up for output as columns.
        , m_success_message("SUCCESS - ")
        , m_failed_message (" FAILED - ")
        , m_not_run_message("NOT RUN - ")
        , m_timed_message  ("  TIMED - ")
    {
    }

    ~TestClassSharedData()
    {
        delete m_logger;
    }

    TestLog* GetLogger()
    {
        if (m_logger == NULL)
            m_logger = new StdioTestLog;
        return m_logger;
    }

    void SetLogger(TestLog* logger)
    {
        delete m_logger;
        m_logger = logger;
    }

    void Clear()
    {
        SetLogger(NULL);
    }

    bool IsLast() const
    {
        return m_destructions >= m_constructions;
    }

private:
    TestClassSharedData(TestClassSharedData const&);
    TestClassSharedData& operator=(TestClassSharedData const&);

// Data only available to TestClass.
private:
    // Default logger when one is not provided.
    TestLog* m_logger;

    // Track longest member function for cleaner output.
    SizeType m_max_member_function_length;

    // Count all constructions.
    SizeType m_constructions;

    // Count all the destructions, and check constructions match destructions.
    SizeType m_destructions;

    // Currently logged line number for the run test.
    SizeType m_logged_line;

    // Counts for all tests.
    SizeType m_total_checks;
    SizeType m_total_not_tested;
    SizeType m_total_failed_tests;
    SizeType m_total_functions_tested;
    SizeType m_total_timed_functions;
    SizeType m_total_tests;

    // message for start of each test.
    const char* m_success_message;
    const char* m_failed_message;
    const char* m_not_run_message;
    const char* m_timed_message;
};

} // namespace ocl

#endif // OCL_GUARD_TEST_TESTCLASSSHAREDDATA_HPP
<commit_msg>Removed obsolete code for tracking max length of function. #18<commit_after>/*
Copyright 2016 Colin Girling

Licensed 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 OCL_GUARD_TEST_TESTCLASSSHAREDDATA_HPP
#define OCL_GUARD_TEST_TESTCLASSSHAREDDATA_HPP

#include "StdioTestLog.hpp"
#include <cstddef>

namespace ocl
{

/**
 * All shared data for every test which is derived from TestClass
 * is in TestClassSharedData class.
 */
template<typename SizeType>
class TestClassSharedData
{
friend class TestClass;

public:
    TestClassSharedData()
        : m_logger(NULL)
        , m_constructions(0)
        , m_logged_line(0)
        , m_total_checks(0)
        , m_total_not_tested(0)
        , m_total_failed_tests(0)
        , m_total_functions_tested(0)
        , m_total_timed_functions(0)
        , m_total_tests(0)

        // Padded to be lined up for output as columns.
        , m_success_message("SUCCESS - ")
        , m_failed_message (" FAILED - ")
        , m_not_run_message("NOT RUN - ")
        , m_timed_message  ("  TIMED - ")
    {
    }

    ~TestClassSharedData()
    {
        delete m_logger;
    }

    TestLog* GetLogger()
    {
        if (m_logger == NULL)
            m_logger = new StdioTestLog;
        return m_logger;
    }

    void SetLogger(TestLog* logger)
    {
        delete m_logger;
        m_logger = logger;
    }

    void Clear()
    {
        SetLogger(NULL);
    }

    bool IsLast() const
    {
        return m_destructions >= m_constructions;
    }

private:
    TestClassSharedData(TestClassSharedData const&);
    TestClassSharedData& operator=(TestClassSharedData const&);

// Data only available to TestClass.
private:
    // Default logger when one is not provided.
    TestLog* m_logger;

    // Count all constructions.
    SizeType m_constructions;

    // Count all the destructions, and check constructions match destructions.
    SizeType m_destructions;

    // Currently logged line number for the run test.
    SizeType m_logged_line;

    // Counts for all tests.
    SizeType m_total_checks;
    SizeType m_total_not_tested;
    SizeType m_total_failed_tests;
    SizeType m_total_functions_tested;
    SizeType m_total_timed_functions;
    SizeType m_total_tests;

    // message for start of each test.
    const char* m_success_message;
    const char* m_failed_message;
    const char* m_not_run_message;
    const char* m_timed_message;
};

} // namespace ocl

#endif // OCL_GUARD_TEST_TESTCLASSSHAREDDATA_HPP
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007-2010, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "tbb/mutex.h"

#include "IECoreRI/SLOReader.h"

#include "IECore/Shader.h"
#include "IECore/MessageHandler.h"
#include "IECore/SimpleTypedData.h"
#include "IECore/VectorTypedData.h"
#include "IECore/FileNameParameter.h"
#include "IECore/ObjectParameter.h"
#include "IECore/NullObject.h"
#include "IECore/CompoundObject.h"

#include "slo.h"

#ifdef PRMANEXPORT
typedef POINT3D SLO_POINT;
#endif

using namespace IECore;
using namespace IECoreRI;
using namespace boost;
using namespace std;
using namespace Imath;

const Reader::ReaderDescription<SLOReader> SLOReader::m_readerDescription( "sdl" );
static tbb::mutex g_mutex;

SLOReader::SLOReader()
	:	Reader( "Reads compiled renderman shaders.", new ObjectParameter( "result", "The loaded shader", new NullObject, Shader::staticTypeId() ) )
{
}

SLOReader::SLOReader( const std::string &fileName )
	:	Reader( "Reads compiled renderman shaders.", new ObjectParameter( "result", "The loaded shader", new NullObject, Shader::staticTypeId() ) )
{
	m_fileNameParameter->setTypedValue( fileName );
}

SLOReader::~SLOReader()
{
}

bool SLOReader::canRead( const std::string &fileName )
{
	tbb::mutex::scoped_lock lock( g_mutex );

	if( Slo_SetShader( (char *)fileName.c_str() ) )
	{
		return false;
	}
	Slo_EndShader();
	return true;
}

ObjectPtr SLOReader::doOperation( const CompoundObject * operands )
{
	tbb::mutex::scoped_lock lock( g_mutex );

	if( Slo_SetShader( (char *)fileName().c_str() ) )
	{
		return 0;
	}

	string name = Slo_GetName();
	string type = Slo_TypetoStr( Slo_GetType() );
	ShaderPtr result = new Shader( name, type );

	CompoundDataPtr typeHints = new CompoundData;
	result->blindData()->writable().insert( pair<string, DataPtr>( "ri:parameterTypeHints", typeHints ) );

	int numArgs = Slo_GetNArgs();
	for( int i=1; i<=numArgs; i++ )
	{
		DataPtr data = 0;

		SLO_VISSYMDEF *arg = Slo_GetArgById( i );
		switch( arg->svd_type )
		{
			case SLO_TYPE_POINT :
			case SLO_TYPE_VECTOR :
			case SLO_TYPE_NORMAL :
				{
					if( arg->svd_arraylen==0 )
					{
						const SLO_POINT *p = arg->svd_default.pointval;
						if( p )
						{
							data = new V3fData( V3f( p->xval, p->yval, p->zval ) );
						}
						else
						{
							// 0 length and null value signifies a variable length array
							data = new V3fVectorData();
						}
					}
					else
					{
						V3fVectorDataPtr vData = new V3fVectorData();
						data = vData;
						for( int j=0; j<arg->svd_arraylen; j++ )
						{
							SLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );
							const SLO_POINT *p = a->svd_default.pointval;
							vData->writable().push_back( V3f( p->xval, p->yval, p->zval ) );
						}
					}
					typeHints->writable().insert( pair<string, DataPtr>( arg->svd_name, new StringData( Slo_TypetoStr( arg->svd_type ) ) ) );
					break;
				}

			case SLO_TYPE_COLOR :
				{
					if( arg->svd_arraylen==0 )
					{
						const SLO_POINT *p = arg->svd_default.pointval;
						if( p )
						{
							data = new Color3fData( Color3f( p->xval, p->yval, p->zval ) );
						}
						else
						{
							// 0 length and null value signifies a variable length array
							data = new Color3fVectorData();
						}
					}
					else
					{
						Color3fVectorDataPtr vData = new Color3fVectorData();
						data = vData;
						for( int j=0; j<arg->svd_arraylen; j++ )
						{
							SLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );
							const SLO_POINT *p = a->svd_default.pointval;
							vData->writable().push_back( Color3f( p->xval, p->yval, p->zval ) );
						}
					}
				}
				break;

			case SLO_TYPE_SCALAR :
				{
					if( arg->svd_arraylen==0 )
					{
						const float *value = arg->svd_default.scalarval;
						if( value )
						{
							data = new FloatData( *value );
						}
						else
						{
							// 0 length and null value signifies a variable length array
							data = new FloatVectorData();
						}
					}
					else
					{
						FloatVectorDataPtr vData = new FloatVectorData();
						data = vData;
						for( int j=0; j<arg->svd_arraylen; j++ )
						{
							SLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );
							vData->writable().push_back( *(a->svd_default.scalarval) );
						}
					}
				}
				break;

			case SLO_TYPE_STRING :
				{
					if( arg->svd_arraylen==0 )
					{
						const char *defaultValue = arg->svd_default.stringval;
						if( defaultValue )
						{
							data = new StringData( defaultValue );
						}
						else
						{
							// 0 length and null value signifies a variable length array
							data = new StringVectorData();
						}
					}
					else
					{
						StringVectorDataPtr vData = new StringVectorData();
						data = vData;
						for( int j=0; j<arg->svd_arraylen; j++ )
						{
							SLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );
							// sometimes the default value for an element of a string array can be a null pointer.
							// i'm not sure what the meaning of this is. the 3delight shaderinfo utility reports such values
							// as "(null)", so that's what we do too.
							const char *defaultValue = a->svd_default.stringval;
							vData->writable().push_back( defaultValue ? defaultValue : "(null)" );
						}
					}
				}
				break;

			case SLO_TYPE_MATRIX :
				{
					if( arg->svd_arraylen==0 )
					{
						const float *m = arg->svd_default.matrixval;
						if( m )
						{
							M44f mm(	m[0], m[1], m[2], m[3],
										m[4], m[5], m[6], m[7],
										m[8], m[9], m[10], m[11],
										m[12], m[13], m[14], m[15] 	);
							data = new M44fData( mm );
						}
						else
						{
							// 0 length and null value signifies a variable length array
							data = new M44fVectorData();
						}
					}
					else
					{
						M44fVectorDataPtr vData = new M44fVectorData();
						data = vData;
						for( int j=0; j<arg->svd_arraylen; j++ )
						{
							SLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );
							const float *m = a->svd_default.matrixval;
							M44f mm(	m[0], m[1], m[2], m[3],
										m[4], m[5], m[6], m[7],
										m[8], m[9], m[10], m[11],
										m[12], m[13], m[14], m[15] 	);
							vData->writable().push_back( mm );
						}
					}
				}
				break;

			default :

				msg( Msg::Warning, "SLOReader::read", format( "Parameter \"%s\" has unsupported type." ) % arg->svd_name );
		}

		if( data )
		{
			result->parameters().insert( CompoundDataMap::value_type( arg->svd_name, data ) );
		}

	}

	return result;
}

<commit_msg>Avoiding call to Slo_SetShader if the filename extension is not 'sdl' to prevent seg faults.<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007-2010, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "tbb/mutex.h"

#include "IECoreRI/SLOReader.h"

#include "IECore/Shader.h"
#include "IECore/MessageHandler.h"
#include "IECore/SimpleTypedData.h"
#include "IECore/VectorTypedData.h"
#include "IECore/FileNameParameter.h"
#include "IECore/ObjectParameter.h"
#include "IECore/NullObject.h"
#include "IECore/CompoundObject.h"

#include "slo.h"

#ifdef PRMANEXPORT
typedef POINT3D SLO_POINT;
#endif

using namespace IECore;
using namespace IECoreRI;
using namespace boost;
using namespace std;
using namespace Imath;

const Reader::ReaderDescription<SLOReader> SLOReader::m_readerDescription( "sdl" );
static tbb::mutex g_mutex;

SLOReader::SLOReader()
	:	Reader( "Reads compiled renderman shaders.", new ObjectParameter( "result", "The loaded shader", new NullObject, Shader::staticTypeId() ) )
{
}

SLOReader::SLOReader( const std::string &fileName )
	:	Reader( "Reads compiled renderman shaders.", new ObjectParameter( "result", "The loaded shader", new NullObject, Shader::staticTypeId() ) )
{
	m_fileNameParameter->setTypedValue( fileName );
}

SLOReader::~SLOReader()
{
}

bool SLOReader::canRead( const std::string &fileName )
{
	if ( fileName.size() < 4 || fileName.substr( fileName.size() - 5, 4 ) != ".sdl" )
	{
		return false;
	}

	tbb::mutex::scoped_lock lock( g_mutex );

	if( Slo_SetShader( (char *)fileName.c_str() ) )
	{
		return false;
	}
	Slo_EndShader();
	return true;
}

ObjectPtr SLOReader::doOperation( const CompoundObject * operands )
{
	tbb::mutex::scoped_lock lock( g_mutex );

	if( Slo_SetShader( (char *)fileName().c_str() ) )
	{
		return 0;
	}

	string name = Slo_GetName();
	string type = Slo_TypetoStr( Slo_GetType() );
	ShaderPtr result = new Shader( name, type );

	CompoundDataPtr typeHints = new CompoundData;
	result->blindData()->writable().insert( pair<string, DataPtr>( "ri:parameterTypeHints", typeHints ) );

	int numArgs = Slo_GetNArgs();
	for( int i=1; i<=numArgs; i++ )
	{
		DataPtr data = 0;

		SLO_VISSYMDEF *arg = Slo_GetArgById( i );
		switch( arg->svd_type )
		{
			case SLO_TYPE_POINT :
			case SLO_TYPE_VECTOR :
			case SLO_TYPE_NORMAL :
				{
					if( arg->svd_arraylen==0 )
					{
						const SLO_POINT *p = arg->svd_default.pointval;
						if( p )
						{
							data = new V3fData( V3f( p->xval, p->yval, p->zval ) );
						}
						else
						{
							// 0 length and null value signifies a variable length array
							data = new V3fVectorData();
						}
					}
					else
					{
						V3fVectorDataPtr vData = new V3fVectorData();
						data = vData;
						for( int j=0; j<arg->svd_arraylen; j++ )
						{
							SLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );
							const SLO_POINT *p = a->svd_default.pointval;
							vData->writable().push_back( V3f( p->xval, p->yval, p->zval ) );
						}
					}
					typeHints->writable().insert( pair<string, DataPtr>( arg->svd_name, new StringData( Slo_TypetoStr( arg->svd_type ) ) ) );
					break;
				}

			case SLO_TYPE_COLOR :
				{
					if( arg->svd_arraylen==0 )
					{
						const SLO_POINT *p = arg->svd_default.pointval;
						if( p )
						{
							data = new Color3fData( Color3f( p->xval, p->yval, p->zval ) );
						}
						else
						{
							// 0 length and null value signifies a variable length array
							data = new Color3fVectorData();
						}
					}
					else
					{
						Color3fVectorDataPtr vData = new Color3fVectorData();
						data = vData;
						for( int j=0; j<arg->svd_arraylen; j++ )
						{
							SLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );
							const SLO_POINT *p = a->svd_default.pointval;
							vData->writable().push_back( Color3f( p->xval, p->yval, p->zval ) );
						}
					}
				}
				break;

			case SLO_TYPE_SCALAR :
				{
					if( arg->svd_arraylen==0 )
					{
						const float *value = arg->svd_default.scalarval;
						if( value )
						{
							data = new FloatData( *value );
						}
						else
						{
							// 0 length and null value signifies a variable length array
							data = new FloatVectorData();
						}
					}
					else
					{
						FloatVectorDataPtr vData = new FloatVectorData();
						data = vData;
						for( int j=0; j<arg->svd_arraylen; j++ )
						{
							SLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );
							vData->writable().push_back( *(a->svd_default.scalarval) );
						}
					}
				}
				break;

			case SLO_TYPE_STRING :
				{
					if( arg->svd_arraylen==0 )
					{
						const char *defaultValue = arg->svd_default.stringval;
						if( defaultValue )
						{
							data = new StringData( defaultValue );
						}
						else
						{
							// 0 length and null value signifies a variable length array
							data = new StringVectorData();
						}
					}
					else
					{
						StringVectorDataPtr vData = new StringVectorData();
						data = vData;
						for( int j=0; j<arg->svd_arraylen; j++ )
						{
							SLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );
							// sometimes the default value for an element of a string array can be a null pointer.
							// i'm not sure what the meaning of this is. the 3delight shaderinfo utility reports such values
							// as "(null)", so that's what we do too.
							const char *defaultValue = a->svd_default.stringval;
							vData->writable().push_back( defaultValue ? defaultValue : "(null)" );
						}
					}
				}
				break;

			case SLO_TYPE_MATRIX :
				{
					if( arg->svd_arraylen==0 )
					{
						const float *m = arg->svd_default.matrixval;
						if( m )
						{
							M44f mm(	m[0], m[1], m[2], m[3],
										m[4], m[5], m[6], m[7],
										m[8], m[9], m[10], m[11],
										m[12], m[13], m[14], m[15] 	);
							data = new M44fData( mm );
						}
						else
						{
							// 0 length and null value signifies a variable length array
							data = new M44fVectorData();
						}
					}
					else
					{
						M44fVectorDataPtr vData = new M44fVectorData();
						data = vData;
						for( int j=0; j<arg->svd_arraylen; j++ )
						{
							SLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );
							const float *m = a->svd_default.matrixval;
							M44f mm(	m[0], m[1], m[2], m[3],
										m[4], m[5], m[6], m[7],
										m[8], m[9], m[10], m[11],
										m[12], m[13], m[14], m[15] 	);
							vData->writable().push_back( mm );
						}
					}
				}
				break;

			default :

				msg( Msg::Warning, "SLOReader::read", format( "Parameter \"%s\" has unsupported type." ) % arg->svd_name );
		}

		if( data )
		{
			result->parameters().insert( CompoundDataMap::value_type( arg->svd_name, data ) );
		}

	}

	return result;
}

<|endoftext|>


<commit_before>#include "STD_TabDesktop.h"

#include <SUIT_Session.h>
#include <SUIT_ViewWindow.h>
#include <SUIT_ResourceMgr.h>

#include <QtxAction.h>
#include <QtxWorkstack.h>
#include <QtxActionMenuMgr.h>
#include <QtxWorkstackAction.h>

#include <qvbox.h>
#include <qmenubar.h>
#include <qworkspace.h>
#include <qobjectlist.h>

#include <stdarg.h>

/*!Constructor.Create new instances of QVBox and QtxWorkstack.*/
STD_TabDesktop::STD_TabDesktop()
: SUIT_Desktop(),
myWorkstack( 0 ),
myWorkstackAction( 0 )
{
  QVBox* base = new QVBox( this );
  base->setFrameStyle( QFrame::Panel | QFrame::Sunken );

  setCentralWidget( base );

  myWorkstack = new QtxWorkstack( base );

  myWorkstack->setAccel(QtxWorkstack::SplitVertical,   SHIFT + Key_V);
  myWorkstack->setAccel(QtxWorkstack::SplitHorizontal, SHIFT + Key_H);
  myWorkstack->setAccel(QtxWorkstack::Close,           SHIFT + Key_C);

  connect( myWorkstack, SIGNAL( windowActivated( QWidget* ) ),
           this, SLOT( onWindowActivated( QWidget* ) ) );

  createActions();
}

/*!Destructor.*/
STD_TabDesktop::~STD_TabDesktop()
{
}

/*!\retval SUIT_ViewWindow - return const active window.*/
SUIT_ViewWindow* STD_TabDesktop::activeWindow() const
{
  SUIT_ViewWindow* wnd = 0;

  QWidget* wid = myWorkstack->activeWindow();
  if ( wid && wid->inherits( "SUIT_ViewWindow" ) )
    wnd = (SUIT_ViewWindow*)wid;

  return wnd;
}

/*!\retval QPtrList<SUIT_ViewWindow> - return const active window list.*/
QPtrList<SUIT_ViewWindow> STD_TabDesktop::windows() const
{
  QPtrList<SUIT_ViewWindow> winList;

  QWidgetList children = myWorkstack->windowList();
  for ( QWidgetListIt it( children ); it.current(); ++it )
  {
    if ( it.current()->inherits( "SUIT_ViewWindow" ) )
      winList.append( (SUIT_ViewWindow*)it.current() );
  }

  return winList;
}

/*!\retval QWidget pointer - QT work stack.*/
QWidget* STD_TabDesktop::parentArea() const
{
  return workstack();
}

/*!Call method perform for operation \a type.*/
void STD_TabDesktop::windowOperation( const int type )
{
  myWorkstackAction->perform( operationFlag( type ) );
}

/*!Sets window operations by \a first ... parameters.*/
void STD_TabDesktop::setWindowOperations( const int first, ... )
{
  va_list ints;
	va_start( ints, first );

	QValueList<int> typeList;

	int cur = first;
	while ( cur )
	{
	  typeList.append( cur );
		cur = va_arg( ints, int );
  }

	setWindowOperations( typeList );
}

/*!Sets window operations by variable \a opList - operation list.*/
void STD_TabDesktop::setWindowOperations( const QValueList<int>& opList )
{
  int flags = 0;

  for ( QValueList<int>::const_iterator it = opList.begin(); it != opList.end(); ++it )
    flags = flags | operationFlag( *it );

  myWorkstackAction->setItems( flags );
}

/*!\retval QtxWorkstack pointer - QT work stack.*/
QtxWorkstack* STD_TabDesktop::workstack() const
{
  return myWorkstack;
}

/*!Emit window activated.*/
void STD_TabDesktop::onWindowActivated( QWidget* w )
{
  if ( w && w->inherits( "SUIT_ViewWindow" ) )
    emit windowActivated( (SUIT_ViewWindow*)w );
}

/*!Create actions for window.*/
void STD_TabDesktop::createActions()
{
  if ( myWorkstackAction )
    return;

  SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
  if ( !resMgr )
    return;

  myWorkstackAction = new QtxWorkstackAction( workstack(), this );

  myWorkstackAction->setItems( QtxWorkstackAction::Split | QtxWorkstackAction::Windows );

  // Split Horizontal
  myWorkstackAction->setIconSet( QtxWorkstackAction::HSplit,
                                 resMgr->loadPixmap( "STD", tr( "ICON_DESK_WINDOW_HSPLIT" ) ) );
  myWorkstackAction->setMenuText( QtxWorkstackAction::HSplit, tr( "MEN_DESK_WINDOW_HSPLIT" ) );
  myWorkstackAction->setStatusTip( QtxWorkstackAction::HSplit, tr( "PRP_DESK_WINDOW_HSPLIT" ) );

  // Split Vertical
  myWorkstackAction->setIconSet( QtxWorkstackAction::VSplit,
                                 resMgr->loadPixmap( "STD", tr( "ICON_DESK_WINDOW_VSPLIT" ) ) );
  myWorkstackAction->setMenuText( QtxWorkstackAction::VSplit, tr( "MEN_DESK_WINDOW_VSPLIT" ) );
  myWorkstackAction->setStatusTip( QtxWorkstackAction::VSplit, tr( "PRP_DESK_WINDOW_VSPLIT" ) );

  QtxActionMenuMgr* mMgr = menuMgr();
  if ( !mMgr )
    return;

  int winMenuId = mMgr->insert( tr( "MEN_DESK_WINDOW" ), -1, 100 );
  mMgr->insert( myWorkstackAction, winMenuId, -1 );
  mMgr->insert( QtxActionMenuMgr::separator(), winMenuId, -1 );
}

/*!Convert STD_TabDesktop enumerations to QtxWorkstackAction*/
int STD_TabDesktop::operationFlag( const int type ) const
{
  int res = 0;
  switch ( type )
  {
  case VSplit:
    res = QtxWorkstackAction::VSplit;
    break;
  case HSplit:
    res = QtxWorkstackAction::HSplit;
    break;
  }
  return res;
}
<commit_msg>A minor modification: Expanding size policy is set to central QxtWorckstack.  why? - see comment in the code.<commit_after>#include "STD_TabDesktop.h"

#include <SUIT_Session.h>
#include <SUIT_ViewWindow.h>
#include <SUIT_ResourceMgr.h>

#include <QtxAction.h>
#include <QtxWorkstack.h>
#include <QtxActionMenuMgr.h>
#include <QtxWorkstackAction.h>

#include <qvbox.h>
#include <qmenubar.h>
#include <qworkspace.h>
#include <qobjectlist.h>

#include <stdarg.h>

/*!Constructor.Create new instances of QVBox and QtxWorkstack.*/
STD_TabDesktop::STD_TabDesktop()
: SUIT_Desktop(),
myWorkstack( 0 ),
myWorkstackAction( 0 )
{
  QVBox* base = new QVBox( this );
  base->setFrameStyle( QFrame::Panel | QFrame::Sunken );

  setCentralWidget( base );

  myWorkstack = new QtxWorkstack( base );
  // setting Expanding size policy for central workstack.  If there are several widgets
  // in central area of Desktop, other widgets will be added below the workstack (CATHARE, TIRPOLI modules).
  // But the workstack must occupy as much space as possible -- set Expanding for it.
  myWorkstack->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ) );

  myWorkstack->setAccel(QtxWorkstack::SplitVertical,   SHIFT + Key_V);
  myWorkstack->setAccel(QtxWorkstack::SplitHorizontal, SHIFT + Key_H);
  myWorkstack->setAccel(QtxWorkstack::Close,           SHIFT + Key_C);

  connect( myWorkstack, SIGNAL( windowActivated( QWidget* ) ),
           this, SLOT( onWindowActivated( QWidget* ) ) );

  createActions();
}

/*!Destructor.*/
STD_TabDesktop::~STD_TabDesktop()
{
}

/*!\retval SUIT_ViewWindow - return const active window.*/
SUIT_ViewWindow* STD_TabDesktop::activeWindow() const
{
  SUIT_ViewWindow* wnd = 0;

  QWidget* wid = myWorkstack->activeWindow();
  if ( wid && wid->inherits( "SUIT_ViewWindow" ) )
    wnd = (SUIT_ViewWindow*)wid;

  return wnd;
}

/*!\retval QPtrList<SUIT_ViewWindow> - return const active window list.*/
QPtrList<SUIT_ViewWindow> STD_TabDesktop::windows() const
{
  QPtrList<SUIT_ViewWindow> winList;

  QWidgetList children = myWorkstack->windowList();
  for ( QWidgetListIt it( children ); it.current(); ++it )
  {
    if ( it.current()->inherits( "SUIT_ViewWindow" ) )
      winList.append( (SUIT_ViewWindow*)it.current() );
  }

  return winList;
}

/*!\retval QWidget pointer - QT work stack.*/
QWidget* STD_TabDesktop::parentArea() const
{
  return workstack();
}

/*!Call method perform for operation \a type.*/
void STD_TabDesktop::windowOperation( const int type )
{
  myWorkstackAction->perform( operationFlag( type ) );
}

/*!Sets window operations by \a first ... parameters.*/
void STD_TabDesktop::setWindowOperations( const int first, ... )
{
  va_list ints;
	va_start( ints, first );

	QValueList<int> typeList;

	int cur = first;
	while ( cur )
	{
	  typeList.append( cur );
		cur = va_arg( ints, int );
  }

	setWindowOperations( typeList );
}

/*!Sets window operations by variable \a opList - operation list.*/
void STD_TabDesktop::setWindowOperations( const QValueList<int>& opList )
{
  int flags = 0;

  for ( QValueList<int>::const_iterator it = opList.begin(); it != opList.end(); ++it )
    flags = flags | operationFlag( *it );

  myWorkstackAction->setItems( flags );
}

/*!\retval QtxWorkstack pointer - QT work stack.*/
QtxWorkstack* STD_TabDesktop::workstack() const
{
  return myWorkstack;
}

/*!Emit window activated.*/
void STD_TabDesktop::onWindowActivated( QWidget* w )
{
  if ( w && w->inherits( "SUIT_ViewWindow" ) )
    emit windowActivated( (SUIT_ViewWindow*)w );
}

/*!Create actions for window.*/
void STD_TabDesktop::createActions()
{
  if ( myWorkstackAction )
    return;

  SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
  if ( !resMgr )
    return;

  myWorkstackAction = new QtxWorkstackAction( workstack(), this );

  myWorkstackAction->setItems( QtxWorkstackAction::Split | QtxWorkstackAction::Windows );

  // Split Horizontal
  myWorkstackAction->setIconSet( QtxWorkstackAction::HSplit,
                                 resMgr->loadPixmap( "STD", tr( "ICON_DESK_WINDOW_HSPLIT" ) ) );
  myWorkstackAction->setMenuText( QtxWorkstackAction::HSplit, tr( "MEN_DESK_WINDOW_HSPLIT" ) );
  myWorkstackAction->setStatusTip( QtxWorkstackAction::HSplit, tr( "PRP_DESK_WINDOW_HSPLIT" ) );

  // Split Vertical
  myWorkstackAction->setIconSet( QtxWorkstackAction::VSplit,
                                 resMgr->loadPixmap( "STD", tr( "ICON_DESK_WINDOW_VSPLIT" ) ) );
  myWorkstackAction->setMenuText( QtxWorkstackAction::VSplit, tr( "MEN_DESK_WINDOW_VSPLIT" ) );
  myWorkstackAction->setStatusTip( QtxWorkstackAction::VSplit, tr( "PRP_DESK_WINDOW_VSPLIT" ) );

  QtxActionMenuMgr* mMgr = menuMgr();
  if ( !mMgr )
    return;

  int winMenuId = mMgr->insert( tr( "MEN_DESK_WINDOW" ), -1, 100 );
  mMgr->insert( myWorkstackAction, winMenuId, -1 );
  mMgr->insert( QtxActionMenuMgr::separator(), winMenuId, -1 );
}

/*!Convert STD_TabDesktop enumerations to QtxWorkstackAction*/
int STD_TabDesktop::operationFlag( const int type ) const
{
  int res = 0;
  switch ( type )
  {
  case VSplit:
    res = QtxWorkstackAction::VSplit;
    break;
  case HSplit:
    res = QtxWorkstackAction::HSplit;
    break;
  }
  return res;
}
<|endoftext|>


<commit_before>// =============================================================================
// File Name: GearBox.inl
// Description: Represents a gear box with up to 3 motors and an encoder
// Author: FRC Team 3512, Spartatroniks
// =============================================================================

#include <cmath>
#include <Encoder.h>
#include <Solenoid.h>
#include <SpeedController.h>

#include <PIDController.h>

template <class T>
GearBox<T>::GearBox( unsigned int shifterChan ,
                     unsigned int encA ,
                     unsigned int encB ,
                     unsigned int motor1 ,
                     unsigned int motor2 ,
                     unsigned int motor3 ) {
    if ( encA != -1 && encB != -1 ) {
        m_encoder = new Encoder( encA , encB );
        m_pid = new PIDController( 0 , 0 , 0 , 0 , m_encoder , this );

        m_havePID = true;
    }
    else {
        m_encoder = nullptr;
        m_pid = nullptr;

        m_havePID = false;
    }

    if ( shifterChan != -1 ) {
        m_shifter = new Solenoid( shifterChan );
    }
    else {
        m_shifter = nullptr;
    }

    m_isMotorReversed = false;
    m_isEncoderReversed = false;

    m_targetGear = false;

    // Create motor controllers of specified template type
    if ( motor1 != -1 ) {
        m_motors.push_back( new T( motor1 ) );
    }
    if ( motor2 != -1 ) {
        m_motors.push_back( new T( motor2 ) );
    }
    if ( motor3 != -1 ) {
        m_motors.push_back( new T( motor3 ) );
    }
    if ( m_havePID ) {
        m_encoder->SetPIDSourceParameter( Encoder::kDistance );

        // m_pid->SetPercentTolerance( 5.f );
        m_pid->SetAbsoluteTolerance( 1 );

        m_encoder->Start();
        m_pid->Enable();
    }
}

template <class T>
GearBox<T>::~GearBox() {
    if ( m_havePID ) {
        delete m_pid;

        m_encoder->Stop();
        delete m_encoder;
    }

    if ( m_shifter != nullptr ) {
        delete m_shifter;
    }

    // Free motors
    for ( unsigned int i = 0 ; i < m_motors.size() ; i++ ) {
        delete m_motors[i];
    }
    m_motors.clear();
}

template <class T>
void GearBox<T>::setSetpoint( float setpoint ) {
    if ( m_havePID ) {
        if ( !m_pid->IsEnabled() ) {
            m_pid->Enable();
        }

        m_pid->SetSetpoint( setpoint );
    }
    else {
        // TODO emit warning since PID doesn't work (possibly through logger?)
    }
}

template <class T>
float GearBox<T>::getSetpoint() const {
    if ( m_havePID ) {
        return m_pid->GetSetpoint();
    }
    else {
        // TODO emit warning since PID doesn't work (possibly through logger?)
        return 0.f;
    }
}

template <class T>
void GearBox<T>::setManual( float value ) {
    if ( m_havePID ) {
        if ( m_pid->IsEnabled() ) {
            m_pid->Disable();
        }
    }

    PIDWrite( value );
}

template <class T>
float GearBox<T>::getManual() const {
    if ( !m_isMotorReversed ) {
        return m_motors[0]->Get();
    }
    else {
        return -m_motors[0]->Get();
    }
}

template <class T>
void GearBox<T>::setPID( float p , float i , float d ) {
    if ( m_havePID ) {
        m_pid->SetPID( p , i , d );
    }
    else {
        // TODO emit warning since PID doesn't work (possibly through logger?)
    }
}

template <class T>
void GearBox<T>::setF( float f ) {
    if ( m_havePID ) {
        m_pid->SetPID( m_pid->GetP() , m_pid->GetI() , m_pid->GetD() , f );
    }
    else {
        // TODO emit warning since PID doesn't work (possibly through logger?)
    }
}

template <class T>
void GearBox<T>::setDistancePerPulse( double distancePerPulse ) {
    if ( m_havePID ) {
        m_encoder->SetDistancePerPulse( distancePerPulse );
    }
}

template <class T>
void GearBox<T>::setPIDSourceParameter( PIDSource::PIDSourceParameter pidSource )
{
    if ( m_havePID ) {
        m_encoder->SetPIDSourceParameter( pidSource );
    }
}

template <class T>
void GearBox<T>::resetEncoder() {
    if ( m_havePID ) {
        m_encoder->Reset();
    }
    else {
        // TODO emit warning since PID doesn't work (possibly through logger?)
    }
}

template <class T>
double GearBox<T>::getDistance() const {
    if ( m_havePID ) {
        return m_encoder->GetDistance();
    }
    else {
        // TODO emit warning since PID doesn't work (possibly through logger?)
        return 0.f;
    }
}

template <class T>
double GearBox<T>::getRate() const {
    if ( m_havePID ) {
        return m_encoder->GetRate();
    }
    else {
        // TODO emit warning since PID doesn't work (possibly through logger?)
        return 0.f;
    }
}

template <class T>
void GearBox<T>::setMotorReversed( bool reverse ) {
    m_isMotorReversed = reverse;
}

template <class T>
bool GearBox<T>::isMotorReversed() const {
    return m_isMotorReversed;
}

template <class T>
void GearBox<T>::setEncoderReversed( bool reverse ) {
    m_encoder->SetReverseDirection( reverse );
}

template <class T>
bool GearBox<T>::isEncoderReversed() const {
    return m_isEncoderReversed;
}

template <class T>
void GearBox<T>::setGear( bool gear ) {
    if ( m_shifter != nullptr ) {
        m_targetGear = gear;
    }
}

template <class T>
bool GearBox<T>::getGear() const {
    if ( m_shifter != nullptr ) {
        return m_shifter->Get();
    }
    else {
        return false;
    }
}

template <class T>
void GearBox<T>::PIDWrite( float output ) {
    for ( unsigned int i = 0 ; i < m_motors.size() ; i++ ) {
        if ( !m_isMotorReversed ) {
            m_motors[i]->Set( output );
        }
        else {
            m_motors[i]->Set( -output );
        }
    }

    updateGear();
}

template <class T>
void GearBox<T>::updateGear() {
    if ( m_shifter == nullptr || m_targetGear == m_shifter->Get() ) {
        return;
    }

    for ( unsigned int i = 0 ; i < m_motors.size() ; i++ ) {
        if ( fabs( m_motors[i]->Get() ) < 0.12 ) {
            return;
        }
    }

    // if ( (m_pid->IsEnabled() && fabs(m_encoder->GetRate()) > 50) || !m_pid->IsEnabled()) {
    m_shifter->Set( m_targetGear );

    // }
}

template <class T>
bool GearBox<T>::onTarget() {
    if ( m_havePID ) {
        return m_pid->OnTarget();
    }
    else {
        return false;
    }
}

template <class T>
void GearBox<T>::resetPID() {
    m_pid->Reset();
    m_pid->Enable();
}

<commit_msg>Fixed compilation error regarding GearBox class<commit_after>// =============================================================================
// File Name: GearBox.inl
// Description: Represents a gear box with up to 3 motors and an encoder
// Author: FRC Team 3512, Spartatroniks
// =============================================================================

#include <cmath>
#include <Encoder.h>
#include <Solenoid.h>
#include <SpeedController.h>

#include <PIDController.h>

template <class T>
GearBox<T>::GearBox( int shifterChan ,
                     int encA ,
                     int encB ,
                     int motor1 ,
                     int motor2 ,
                     int motor3 ) {
    if ( encA != -1 && encB != -1 ) {
        m_encoder = new Encoder( encA , encB );
        m_pid = new PIDController( 0 , 0 , 0 , 0 , m_encoder , this );

        m_havePID = true;
    }
    else {
        m_encoder = nullptr;
        m_pid = nullptr;

        m_havePID = false;
    }

    if ( shifterChan != -1 ) {
        m_shifter = new Solenoid( shifterChan );
    }
    else {
        m_shifter = nullptr;
    }

    m_isMotorReversed = false;
    m_isEncoderReversed = false;

    m_targetGear = false;

    // Create motor controllers of specified template type
    if ( motor1 != -1 ) {
        m_motors.push_back( new T( motor1 ) );
    }
    if ( motor2 != -1 ) {
        m_motors.push_back( new T( motor2 ) );
    }
    if ( motor3 != -1 ) {
        m_motors.push_back( new T( motor3 ) );
    }
    if ( m_havePID ) {
        m_encoder->SetPIDSourceParameter( Encoder::kDistance );

        // m_pid->SetPercentTolerance( 5.f );
        m_pid->SetAbsoluteTolerance( 1 );

        m_pid->Enable();
    }
}

template <class T>
GearBox<T>::~GearBox() {
    if ( m_havePID ) {
        delete m_pid;
        delete m_encoder;
    }

    if ( m_shifter != nullptr ) {
        delete m_shifter;
    }

    // Free motors
    for ( unsigned int i = 0 ; i < m_motors.size() ; i++ ) {
        delete m_motors[i];
    }
    m_motors.clear();
}

template <class T>
void GearBox<T>::setSetpoint( float setpoint ) {
    if ( m_havePID ) {
        if ( !m_pid->IsEnabled() ) {
            m_pid->Enable();
        }

        m_pid->SetSetpoint( setpoint );
    }
    else {
        // TODO emit warning since PID doesn't work (possibly through logger?)
    }
}

template <class T>
float GearBox<T>::getSetpoint() const {
    if ( m_havePID ) {
        return m_pid->GetSetpoint();
    }
    else {
        // TODO emit warning since PID doesn't work (possibly through logger?)
        return 0.f;
    }
}

template <class T>
void GearBox<T>::setManual( float value ) {
    if ( m_havePID ) {
        if ( m_pid->IsEnabled() ) {
            m_pid->Disable();
        }
    }

    PIDWrite( value );
}

template <class T>
float GearBox<T>::getManual() const {
    if ( !m_isMotorReversed ) {
        return m_motors[0]->Get();
    }
    else {
        return -m_motors[0]->Get();
    }
}

template <class T>
void GearBox<T>::setPID( float p , float i , float d ) {
    if ( m_havePID ) {
        m_pid->SetPID( p , i , d );
    }
    else {
        // TODO emit warning since PID doesn't work (possibly through logger?)
    }
}

template <class T>
void GearBox<T>::setF( float f ) {
    if ( m_havePID ) {
        m_pid->SetPID( m_pid->GetP() , m_pid->GetI() , m_pid->GetD() , f );
    }
    else {
        // TODO emit warning since PID doesn't work (possibly through logger?)
    }
}

template <class T>
void GearBox<T>::setDistancePerPulse( double distancePerPulse ) {
    if ( m_havePID ) {
        m_encoder->SetDistancePerPulse( distancePerPulse );
    }
}

template <class T>
void GearBox<T>::setPIDSourceParameter( PIDSource::PIDSourceParameter pidSource )
{
    if ( m_havePID ) {
        m_encoder->SetPIDSourceParameter( pidSource );
    }
}

template <class T>
void GearBox<T>::resetEncoder() {
    if ( m_havePID ) {
        m_encoder->Reset();
    }
    else {
        // TODO emit warning since PID doesn't work (possibly through logger?)
    }
}

template <class T>
double GearBox<T>::getDistance() const {
    if ( m_havePID ) {
        return m_encoder->GetDistance();
    }
    else {
        // TODO emit warning since PID doesn't work (possibly through logger?)
        return 0.f;
    }
}

template <class T>
double GearBox<T>::getRate() const {
    if ( m_havePID ) {
        return m_encoder->GetRate();
    }
    else {
        // TODO emit warning since PID doesn't work (possibly through logger?)
        return 0.f;
    }
}

template <class T>
void GearBox<T>::setMotorReversed( bool reverse ) {
    m_isMotorReversed = reverse;
}

template <class T>
bool GearBox<T>::isMotorReversed() const {
    return m_isMotorReversed;
}

template <class T>
void GearBox<T>::setEncoderReversed( bool reverse ) {
    m_encoder->SetReverseDirection( reverse );
}

template <class T>
bool GearBox<T>::isEncoderReversed() const {
    return m_isEncoderReversed;
}

template <class T>
void GearBox<T>::setGear( bool gear ) {
    if ( m_shifter != nullptr ) {
        m_targetGear = gear;
    }
}

template <class T>
bool GearBox<T>::getGear() const {
    if ( m_shifter != nullptr ) {
        return m_shifter->Get();
    }
    else {
        return false;
    }
}

template <class T>
void GearBox<T>::PIDWrite( float output ) {
    for ( unsigned int i = 0 ; i < m_motors.size() ; i++ ) {
        if ( !m_isMotorReversed ) {
            m_motors[i]->Set( output );
        }
        else {
            m_motors[i]->Set( -output );
        }
    }

    updateGear();
}

template <class T>
void GearBox<T>::updateGear() {
    if ( m_shifter == nullptr || m_targetGear == m_shifter->Get() ) {
        return;
    }

    for ( unsigned int i = 0 ; i < m_motors.size() ; i++ ) {
        if ( fabs( m_motors[i]->Get() ) < 0.12 ) {
            return;
        }
    }

    // if ( (m_pid->IsEnabled() && fabs(m_encoder->GetRate()) > 50) || !m_pid->IsEnabled()) {
    m_shifter->Set( m_targetGear );

    // }
}

template <class T>
bool GearBox<T>::onTarget() {
    if ( m_havePID ) {
        return m_pid->OnTarget();
    }
    else {
        return false;
    }
}

template <class T>
void GearBox<T>::resetPID() {
    m_pid->Reset();
    m_pid->Enable();
}

<|endoftext|>


<commit_before>// BookKeeper.cpp
// Implements the BookKeeper class

#include "BookKeeper.h"

#include <string>
#include <iostream>
#include <fstream>
#include <stdlib.h>

#include "Database.h"
#include "Table.h"
#include "CycException.h"

BookKeeper* BookKeeper::instance_ = 0;
bool BookKeeper::logging_on_ = true;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
BookKeeper* BookKeeper::Instance() {
  // If we haven't created a BookKeeper yet, create and return it.
  if (0 == instance_){
    instance_ = new BookKeeper();
  }
  return instance_;
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
BookKeeper::BookKeeper() {
  dbIsOpen_ = false;
  dbExists_ = false;
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool BookKeeper::fexists(const char *filename) {
  std::ifstream ifile(filename);
  return ifile;
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BookKeeper::createDB(std::string name) {
  dbName_ = name;
  try{
    // get database name and location
    char* oPath = getenv("CYCLUS_OUTPUT_DIR");
    if (oPath==NULL) {
      std::string err = std::string("Cyclus output path - envrionment ")
	+ std::string("variable: CYCLUS_OUTPUT_DIR - not defined");
      throw CycIOException(err);
    }

    // construct output file path
    std::string out_path(oPath);
    std::string db_path = out_path + "/" + name;

    // if the file already exists, delete it
    if( fexists( db_path.c_str() ) )
      remove( db_path.c_str() );

    // create database.
    db_ = new Database(name);
    dbIsOpen_ = true;
    dbExists_ = true;
  }
  catch( CycException& error ) {
    // just throw it back for now
    // @MJG flag, do we need to change this?
    throw CycException( std::string(error.what()) );
  }
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BookKeeper::turnOffLogging() {
  logging_on_ = false;
  if ( db_->nTables() > 0 ) {
    std::string err =
      "Logging can not be turned off once a table has already been created.";
    throw CycException();
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BookKeeper::registerTable(table_ptr t) {
  if ( loggingIsOn() ){
    db_->registerTable(t);
    db_->createTable(t);
  }
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BookKeeper::tableAtThreshold(table_ptr t) {
  if ( loggingIsOn() ){
    db_->writeRows(t);
    t->flush();
  }
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BookKeeper::closeDB() {
  // have the database print and remaining commands
  for (int i = 0; i < db_->nTables(); i++) {
    table_ptr t = db_->tablePtr(i);
    if (t->nRows() > 0)
      this->tableAtThreshold(t);
  }
  // close the db
  db_->close();
}
<commit_msg>more redundancy for database existance checking.<commit_after>// BookKeeper.cpp
// Implements the BookKeeper class

#include "BookKeeper.h"

#include <string>
#include <iostream>
#include <fstream>
#include <stdlib.h>

#include "Database.h"
#include "Table.h"
#include "CycException.h"

BookKeeper* BookKeeper::instance_ = 0;
bool BookKeeper::logging_on_ = true;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
BookKeeper* BookKeeper::Instance() {
  // If we haven't created a BookKeeper yet, create and return it.
  if (0 == instance_){
    instance_ = new BookKeeper();
  }
  return instance_;
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
BookKeeper::BookKeeper() {
  dbIsOpen_ = false;
  dbExists_ = false;
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool BookKeeper::fexists(const char *filename) {
  std::ifstream ifile(filename);
  return ifile;
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BookKeeper::createDB(std::string name) {
  dbName_ = name;
  try{
    // get database name and location
    char* oPath = getenv("CYCLUS_OUTPUT_DIR");
    if (oPath==NULL) {
      std::string err = std::string("Cyclus output path - envrionment ")
	+ std::string("variable: CYCLUS_OUTPUT_DIR - not defined");
      throw CycIOException(err);
    }

    // construct output file path
    std::string out_path(oPath);
    std::string db_path = out_path + "/" + name;

    // if the file already exists, delete it
    if( fexists( db_path.c_str() ) )
      remove( db_path.c_str() );

    // create database.
    db_ = new Database(name);
    if ( db_->dbExists() ) {
      dbIsOpen_ = true;
      dbExists_ = true;
    }
  }
  catch( CycException& error ) {
    // just throw it back for now
    // @MJG flag, do we need to change this?
    throw CycException( std::string(error.what()) );
  }
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BookKeeper::turnOffLogging() {
  logging_on_ = false;
  if ( db_->nTables() > 0 ) {
    std::string err =
      "Logging can not be turned off once a table has already been created.";
    throw CycException();
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BookKeeper::registerTable(table_ptr t) {
  if ( loggingIsOn() ){
    db_->registerTable(t);
    db_->createTable(t);
  }
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BookKeeper::tableAtThreshold(table_ptr t) {
  if ( loggingIsOn() ){
    db_->writeRows(t);
    t->flush();
  }
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BookKeeper::closeDB() {
  // have the database print and remaining commands
  for (int i = 0; i < db_->nTables(); i++) {
    table_ptr t = db_->tablePtr(i);
    if (t->nRows() > 0)
      this->tableAtThreshold(t);
  }
  // close the db
  db_->close();
}
<|endoftext|>