<commit_before>/*=========================================================================

  Program:   Monteverdi2
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

//
// Configuration include.
//// Included at first position before any other ones.
#include "ConfigureMonteverdi2.h"

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

// Monteverdi includes (sorted by alphabetic order)
#include "mvdApplication.h"
#include "mvdMainWindow.h"
#include "mvdDatasetModel.h"

//
// OTB includes (sorted by alphabetic order)

//
// MAIN
//
int
main( int argc, char* argv[] )
{
  mvd::Application application( argc, argv );

  //
  // Force numeric options of locale to "C"
  // See issue #635
  //
  // TODO: Move into I18nApplication.
  setlocale( LC_NUMERIC, "C" );

  // Check if the application have a settings file already available
  bool appHasSettingsFile = application.HasSettingsFile();
  bool appHasIncorrectCacheDir(false);
  if (appHasSettingsFile)
    {
    // Read cache dir from settings
    application.ReadCacheDirFromSettings();
    // Check the cache dir
    if (!application.CheckCacheDirIsCorrect() )
      {
      appHasIncorrectCacheDir = true;
      }
    }
  else // TODO MSD: should be removed
    {
    std::cout << "Application has no settings file";
    }

  mvd::MainWindow mainWindow;

  if (!appHasSettingsFile || appHasIncorrectCacheDir)
    {
    // Loop until the directory will be correct
    while (true)
      {
      // Select a new location for the cache director
      try
        {
        // Create the cache directory
        application.MakeCacheDir(mainWindow.SelectCacheDir(appHasIncorrectCacheDir));
        break;
        }
      catch (...)
        {
        appHasIncorrectCacheDir = true;
        }
      }
    // Save the cache directory into the settings file
    application.WriteCacheDirIntoSettings();
    }

#if defined( _DEBUG )
  // Usefull when developping/debugging to avoid overlapping other windows.
  mainWindow.show();
#else
  // TODO: Correctly manage main-window state via application settings.
  mainWindow.showMaximized();
#endif

  // This code is here to propagate events from maximization to child
  // widgets, so that an image loaded from command-line will get the
  // appropriate widget size and occupy as much space as possible on screen.
  application.processEvents();

  // TODO: Move into mvd::Application.
  // Handle passing image filename from command-line
  if(argc>1)
    {
    mainWindow.OpenImage( QString(argv[1]) );
    }

  return application.exec();
}

//
// Main functions implementations.
//
<commit_msg>BUG: fix resource loading on Windows<commit_after>/*=========================================================================

  Program:   Monteverdi2
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

//
// Configuration include.
//// Included at first position before any other ones.
#include "ConfigureMonteverdi2.h"

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

// Monteverdi includes (sorted by alphabetic order)
#include "mvdApplication.h"
#include "mvdMainWindow.h"
#include "mvdDatasetModel.h"

//
// OTB includes (sorted by alphabetic order)

//
// MAIN
//
int
main( int argc, char* argv[] )
{
  Q_INIT_RESOURCE(mvdMainWindow);

  mvd::Application application( argc, argv );

  //
  // Force numeric options of locale to "C"
  // See issue #635
  //
  // TODO: Move into I18nApplication.
  setlocale( LC_NUMERIC, "C" );

  // Check if the application have a settings file already available
  bool appHasSettingsFile = application.HasSettingsFile();
  bool appHasIncorrectCacheDir(false);
  if (appHasSettingsFile)
    {
    // Read cache dir from settings
    application.ReadCacheDirFromSettings();
    // Check the cache dir
    if (!application.CheckCacheDirIsCorrect() )
      {
      appHasIncorrectCacheDir = true;
      }
    }
  else // TODO MSD: should be removed
    {
    std::cout << "Application has no settings file";
    }

  mvd::MainWindow mainWindow;

  if (!appHasSettingsFile || appHasIncorrectCacheDir)
    {
    // Loop until the directory will be correct
    while (true)
      {
      // Select a new location for the cache director
      try
        {
        // Create the cache directory
        application.MakeCacheDir(mainWindow.SelectCacheDir(appHasIncorrectCacheDir));
        break;
        }
      catch (...)
        {
        appHasIncorrectCacheDir = true;
        }
      }
    // Save the cache directory into the settings file
    application.WriteCacheDirIntoSettings();
    }

#if defined( _DEBUG )
  // Usefull when developping/debugging to avoid overlapping other windows.
  mainWindow.show();
#else
  // TODO: Correctly manage main-window state via application settings.
  mainWindow.showMaximized();
#endif

  // This code is here to propagate events from maximization to child
  // widgets, so that an image loaded from command-line will get the
  // appropriate widget size and occupy as much space as possible on screen.
  application.processEvents();

  // TODO: Move into mvd::Application.
  // Handle passing image filename from command-line
  if(argc>1)
    {
    mainWindow.OpenImage( QString(argv[1]) );
    }

  return application.exec();
}

//
// Main functions implementations.
//
<|endoftext|>


<commit_before>/*=========================================================================

Program:   ORFEO Toolbox
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbMsgReporter.h"
#include <FL/Fl_Text_Buffer.H>

namespace otb
{
  /** Initialize the singleton */
  MsgReporter::Pointer MsgReporter::m_Instance = NULL;

  /// Constructor
  MsgReporter
  ::MsgReporter()
  {
        this->Build();
        wMainWindow->show();
        Fl_Text_Buffer * buffer = new Fl_Text_Buffer();
        this->textArea->buffer(buffer);
  }

  /** Manage the singleton */
  MsgReporter::Pointer
  MsgReporter
  ::GetInstance()
  {
    if(!m_Instance)
      {
	m_Instance = MsgReporter::New();
      }
    return m_Instance;
  }
  //Show
  void
  MsgReporter
  ::Show()
  {
        this->wMainWindow->show();
  }
  //Hide
  void
  MsgReporter
  ::Hide()
  {
        this->wMainWindow->hide();
  }
  //Set title
  void
  MsgReporter
  ::SetTitle(const std::string & title)
  {
        std::string str(title);
        str = str + " message reporter window";
        this->wMainWindow->label(str.c_str());
  }
  //Send Msg
  void
  MsgReporter
  ::SendMsg(const std::string & msg)
  {
        this->textArea->insert(msg.c_str());
        this->textArea->insert("\n");
        this->textArea->show_insert_position();
        Fl::check();
  }

  //Send Error
  void
  MsgReporter
  ::SendError(const std::string & msg)
  {
        this->textArea->insert("ERROR: ");
        this->textArea->insert(msg.c_str());
        this->textArea->insert("\n");
        this->textArea->show_insert_position();
        this->Show();
        Fl::check();
  }

}
<commit_msg>STYLE: tab replaced by 2 spaces<commit_after>/*=========================================================================

Program:   ORFEO Toolbox
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbMsgReporter.h"
#include <FL/Fl_Text_Buffer.H>

namespace otb
{
  /** Initialize the singleton */
  MsgReporter::Pointer MsgReporter::m_Instance = NULL;

  /// Constructor
  MsgReporter
  ::MsgReporter()
  {
        this->Build();
        wMainWindow->show();
        Fl_Text_Buffer * buffer = new Fl_Text_Buffer();
        this->textArea->buffer(buffer);
  }

  /** Manage the singleton */
  MsgReporter::Pointer
  MsgReporter
  ::GetInstance()
  {
    if(!m_Instance)
      {
  m_Instance = MsgReporter::New();
      }
    return m_Instance;
  }
  //Show
  void
  MsgReporter
  ::Show()
  {
        this->wMainWindow->show();
  }
  //Hide
  void
  MsgReporter
  ::Hide()
  {
        this->wMainWindow->hide();
  }
  //Set title
  void
  MsgReporter
  ::SetTitle(const std::string & title)
  {
        std::string str(title);
        str = str + " message reporter window";
        this->wMainWindow->label(str.c_str());
  }
  //Send Msg
  void
  MsgReporter
  ::SendMsg(const std::string & msg)
  {
        this->textArea->insert(msg.c_str());
        this->textArea->insert("\n");
        this->textArea->show_insert_position();
        Fl::check();
  }

  //Send Error
  void
  MsgReporter
  ::SendError(const std::string & msg)
  {
        this->textArea->insert("ERROR: ");
        this->textArea->insert(msg.c_str());
        this->textArea->insert("\n");
        this->textArea->show_insert_position();
        this->Show();
        Fl::check();
  }

}
<|endoftext|>


<commit_before>/******************************************************************************

  This source file is part of the TEM tomography project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

******************************************************************************/
#include "Behaviors.h"

#include "pqAlwaysConnectedBehavior.h"
#include "pqApplicationCore.h"
#include "pqDefaultViewBehavior.h"
#include "pqInterfaceTracker.h"
#include "pqPersistentMainWindowStateBehavior.h"
#include "pqQtMessageHandlerBehavior.h"
#include "pqStandardPropertyWidgetInterface.h"
#include "pqStandardViewModules.h"
#include "pqViewFrameActionsBehavior.h"
#include "ProgressBehavior.h"

#include <QMainWindow>

namespace TEM
{
//-----------------------------------------------------------------------------
Behaviors::Behaviors(QMainWindow* mainWindow)
{
  Q_ASSERT(mainWindow);

  // Register ParaView interfaces.
  pqInterfaceTracker* pgm = pqApplicationCore::instance()->interfaceTracker();

  // * adds support for standard paraview views.
  pgm->addInterface(new pqStandardViewModules(pgm));

  // * add support for ParaView properties panel widgets.
  pgm->addInterface(new pqStandardPropertyWidgetInterface(pgm));

  // Load plugins distributed with application.
  pqApplicationCore::instance()->loadDistributedPlugins();

  new pqQtMessageHandlerBehavior(this);
  new pqViewFrameActionsBehavior(this);
  new pqDefaultViewBehavior(this);
  new pqAlwaysConnectedBehavior(this);
  new pqPersistentMainWindowStateBehavior(mainWindow);
  new TEM::ProgressBehavior(mainWindow);

  // this will trigger the logic to setup reader/writer factories, etc.
  pqApplicationCore::instance()->loadConfigurationXML("<xml/>");
}

//-----------------------------------------------------------------------------
Behaviors::~Behaviors()
{
}

} // end of namespace TEM
<commit_msg>Updates to build with ParaView/master.<commit_after>/******************************************************************************

  This source file is part of the TEM tomography project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

******************************************************************************/
#include "Behaviors.h"

#include "pqAlwaysConnectedBehavior.h"
#include "pqApplicationCore.h"
#include "pqDefaultViewBehavior.h"
#include "pqInterfaceTracker.h"
#include "pqPersistentMainWindowStateBehavior.h"
#include "pqQtMessageHandlerBehavior.h"
#include "pqStandardPropertyWidgetInterface.h"
#include "pqStandardViewFrameActionsImplementation.h"
#include "ProgressBehavior.h"

#include <QMainWindow>

namespace TEM
{
//-----------------------------------------------------------------------------
Behaviors::Behaviors(QMainWindow* mainWindow)
{
  Q_ASSERT(mainWindow);

  // Register ParaView interfaces.
  pqInterfaceTracker* pgm = pqApplicationCore::instance()->interfaceTracker();

  // * add support for ParaView properties panel widgets.
  pgm->addInterface(new pqStandardPropertyWidgetInterface(pgm));

  // * register standard types of view-frame actions.
  pgm->addInterface(new pqStandardViewFrameActionsImplementation(pgm));

  // Load plugins distributed with application.
  pqApplicationCore::instance()->loadDistributedPlugins();

  new pqQtMessageHandlerBehavior(this);
  new pqDefaultViewBehavior(this);
  new pqAlwaysConnectedBehavior(this);
  new pqPersistentMainWindowStateBehavior(mainWindow);
  new TEM::ProgressBehavior(mainWindow);

  // this will trigger the logic to setup reader/writer factories, etc.
  pqApplicationCore::instance()->loadConfigurationXML("<xml/>");
}

//-----------------------------------------------------------------------------
Behaviors::~Behaviors()
{
}

} // end of namespace TEM
<|endoftext|>


<commit_before>/*
* Copyright (C) 2004-2019 ZNC, see the NOTICE file for details.
*
* 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.
*
*
* ==================================================
*  BotStatus module by QueenElsa • Version 1.0
* --------------------------------------------------
*  Designed for use by the Undernet User-Committee
* --------------------------------------------------
*  Channel: #development @ irc.undernet.org
*  Contact: QueenElsa@undernet.org
* --------------------------------------------------
*  Announces the status of an attached bot. Based
*  of ClientNotify module.
* ==================================================
*/

#include <znc/IRCNetwork.h>
#include <znc/znc.h>
#include <znc/User.h>

using std::set;

class CBotStatus : public CModule {
protected:
	CString m_sMethod;
	bool m_bOnDisconnect{};
	bool m_bOnConnect{};

	set<CString> m_sBotsSeen;

	void SaveSettings() {
		SetNV("method", m_sMethod);
		SetNV("ondisconnect", m_bOnDisconnect ? "1" : "0");
		SetNV("onconnect", m_bOnConnect ? "1" : "0");
	}

	void SendNotification(const CString& sMessage) {
		if(m_sMethod == "message") {
			PutIRC("PRIVMSG #Arendelle :" +sMessage);
			PutIRC("PRIVMSG #Uback :" +sMessage);
		}
		else if(m_sMethod == "notice") {
			PutIRC("NOTICE #Arendelle :" +sMessage);
			PutIRC("NOTICE #Uback :" +sMessage);
		}
	}

public:
	MODCONSTRUCTOR(CBotStatus) {
		AddHelpCommand();
		AddCommand("Method", static_cast<CModCommand::ModCmdFunc>(&CBotStatus::OnMethodCommand), "<message|notice|off>", "Sets the notify method");
		AddCommand("OnDisconnect", static_cast<CModCommand::ModCmdFunc>(&CBotStatus::OnDisconnectCommand), "<on|off>", "Turns notifications on disconnect only.");
		AddCommand("OnConnect", static_cast<CModCommand::ModCmdFunc>(&CBotStatus::OnConnectCommand), "<on|off>", "Turns notifications on connect only.");
		AddCommand("Show", static_cast<CModCommand::ModCmdFunc>(&CBotStatus::OnShowCommand), "", "Show the current settings");
	}

	bool OnLoad(const CString& sArgs, CString& sMessage) override {
		m_sMethod = GetNV("method");

		if(m_sMethod != "notice" && m_sMethod != "message" && m_sMethod != "off") {
			m_sMethod = "message";
		}

		// default = off for these:

		m_bOnDisconnect = (GetNV("ondisconnect") == "0");
		m_bOnConnect = (GetNV("onconnect") == "0");

		return true;
	}

	void OnClientLogin() override {
		if(m_bOnConnect) {
			SendNotification("[ONLINE] Bot services have been restored. I will respond to commands I receive from ops.");
		}
	}

	void OnClientDisconnect() override {
		if(m_bOnDisconnect) {
			SendNotification("[OFFLINE] Bot services are unavailable. I will not respond to any commands received. Please contact a User-Com Administrator.");
		}
	}

	void OnMethodCommand(const CString& sCommand) {
		const CString& sArg = sCommand.Token(1, true).AsLower();

		if (sArg != "notice" && sArg != "message" && sArg != "off") {
			PutModule("Usage: Method <message|notice|off>");
			return;
		}

		if (sArg == "off") {
			PutModule("MESSAGE METHOD CHANGED: Off - You will not be informed if your bot goes offline.");
			PutModule("WARNING: Status updates will remain turned off until you change the method to NOTICE or MESSAGE.");
		}

		if (sArg == "notice") {
			PutModule("MESSAGE METHOD CHANGED: Notice - You will be informed if your bot has gone offline via a channel notice.");
		}

		if (sArg == "message") {
			PutModule("MESSAGE METHOD CHANGED: Message - You will be informed if your bot has gone offline via a channel message.");
		}

		m_sMethod = sArg;
		SaveSettings();
	}

	void OnDisconnectCommand(const CString& sCommand) {
		const CString& sArg = sCommand.Token(1, true).AsLower();

		if (sArg.empty()) {
			PutModule("Usage: OnDisconnect <on|off>");
			return;
		}

		if (sArg == "off") {
			PutModule("DISCONNECT NOTIFICATION CHANGED: Off - You will not be informed if your bot goes offline.");
			PutModule("WARNING: This setting will remain turned off until you manually turn it back on.");
		}

		if (sArg == "on") {
			PutModule("DISCONNECT NOTIFICATION CHANGED: On - You will be informed if your bot goes offline.");
		}

		m_bOnDisconnect = sArg.ToBool();
		SaveSettings();
		PutModule("Saved.");
	}

		void OnConnectCommand(const CString& sCommand) {
		const CString& sArg = sCommand.Token(1, true).AsLower();

		if (sArg.empty()) {
			PutModule("Usage: OnConnect <on|off>");
			return;
		}

		if (sArg == "off") {
			PutModule("CONNECT NOTIFICATION CHANGED: Off - You will not be informed if your bot comes online.");
			PutModule("WARNING: This setting will remain turned off until you manually turn it back on.");
		}

		if (sArg == "on") {
			PutModule("CONNECT NOTIFICATION CHANGED: On - You will be informed if your bot comes online.");
		}

		m_bOnConnect = sArg.ToBool();
		SaveSettings();
		PutModule("Saved.");
	}

	void OnShowCommand(const CString& sLine) {
		PutModule("Current settings: Message Method: " + m_sMethod + ", Notify if bot disconnected: " + CString(m_bOnDisconnect) + ", Notify if bot reconnects: " + CString(m_bOnConnect));
	}
};

template<> void TModInfo<CBotStatus>(CModInfo& Info) {
	Info.SetWikiPage("BotStatus");
}

USERMODULEDEFS(CBotStatus, "Notifies you when your bot has come online or gone offline. Configurable.")

<commit_msg>Delete BotStatus.cpp<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: inspagob.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 05:44:50 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _SD_INSPAGOB_HXX
#define _SD_INSPAGOB_HXX

#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _SV_DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif

#ifndef _SDTREELB_HXX
#include "sdtreelb.hxx"
#endif

class SdDrawDocument;

//------------------------------------------------------------------------

class SdInsertPagesObjsDlg : public ModalDialog
{
private:
    SdPageObjsTLB           aLbTree;
    CheckBox                aCbxLink;
    CheckBox                aCbxMasters;
    OKButton                aBtnOk;
    CancelButton            aBtnCancel;
    HelpButton              aBtnHelp;

    SfxMedium*              pMedium;
    const SdDrawDocument*   pDoc;
    const String&           rName;

    void                    Reset();
    DECL_LINK( SelectObjectHdl, void * );

public:
                SdInsertPagesObjsDlg( Window* pParent,
                                const SdDrawDocument* pDoc,
                                SfxMedium* pSfxMedium,
                                const String& rFileName );
                ~SdInsertPagesObjsDlg();

    List*       GetList( USHORT nType );
    BOOL        IsLink();
    BOOL        IsRemoveUnnessesaryMasterPages() const;
};

#endif // _SD_INSPAGOB_HXX
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.3.316); FILE MERGED 2006/11/22 12:42:04 cl 1.3.316.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: inspagob.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-12 17:44:08 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _SD_INSPAGOB_HXX
#define _SD_INSPAGOB_HXX

#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _SV_DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif

#ifndef _SDTREELB_HXX
#include "sdtreelb.hxx"
#endif

class SdDrawDocument;

//------------------------------------------------------------------------

class SdInsertPagesObjsDlg : public ModalDialog
{
private:
    SdPageObjsTLB           aLbTree;
    CheckBox                aCbxLink;
    CheckBox                aCbxMasters;
    OKButton                aBtnOk;
    CancelButton            aBtnCancel;
    HelpButton              aBtnHelp;

    SfxMedium*              pMedium;
    const SdDrawDocument*   mpDoc;
    const String&           rName;

    void                    Reset();
    DECL_LINK( SelectObjectHdl, void * );

public:
                SdInsertPagesObjsDlg( Window* pParent,
                                const SdDrawDocument* pDoc,
                                SfxMedium* pSfxMedium,
                                const String& rFileName );
                ~SdInsertPagesObjsDlg();

    List*       GetList( USHORT nType );
    BOOL        IsLink();
    BOOL        IsRemoveUnnessesaryMasterPages() const;
};

#endif // _SD_INSPAGOB_HXX
<|endoftext|>


<commit_before>//*****************************************************************************
//
// Window.cpp
//
// Class responsible for spawning, managing, and closing the OpenGL context.
//
// Copyright (c) 2015 Brandon To, Minh Mai, and Yuzhou Liu
// This code is licensed under BSD license (see LICENSE.txt for details)
//
// Created:
// December 27, 2015
//
// Modified:
// December 28, 2015
//
//*****************************************************************************
#include "Window.h"

#include <iostream>

#include <SDL.h>

//*****************************************************************************
//
//! Constructor for Window. Acquires resources for window and renderer.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
Window::Window()
    : _window(NULL), _renderer(NULL), _width(_DEFAULT_WIDTH),
      _height(_DEFAULT_HEIGHT)
{
    //
    // Initialize window
    //
    if (!_initialize())
    {
        std::cerr << "[ERROR] Window::Window(): Failed to initialize." <<
            std::endl;
        return;
    }

    //
    // Creates base hand image
    //
    _baseImage = std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_base.png"));

    //
    // Creates and add images to finger image list
    //
    _fingerImageList.push_back(std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_right_thumb.png")));
    _fingerImageList.push_back(std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_right_index.png")));
    _fingerImageList.push_back(std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_right_middle.png")));
    _fingerImageList.push_back(std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_right_ring.png")));
    _fingerImageList.push_back(std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_right_pinky.png")));

    //
    // Centre all images for aesthetic purposes
    //
    _centreImage(_baseImage);
    for (auto it = _fingerImageList.begin(); it != _fingerImageList.end(); it++)
    {
        _centreImage(*it);
    }
}

//*****************************************************************************
//
//! Destructor for Window. Releases resources used by window and renderer.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
Window::~Window()
{
    _terminate();
}

//*****************************************************************************
//
//! Updates the window. Called once every frame.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Window::update()
{
    _processInput();
    _update();
    _render();
}

//*****************************************************************************
//
//! Initializes the window.
//!
//! \param None.
//!
//! \return Returns \b true if the window was initialized successfully and
//! \b false otherwise.
//
//*****************************************************************************
bool Window::_initialize()
{
    int iRetVal = 0;

    //
    // Creates OpenGL context
    //
    _window = SDL_CreateWindow("Human Interface for Robotic Control",
        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, _width, _height,
        SDL_WINDOW_SHOWN);
    if (_window == NULL)
    {
        std::cerr << "[ERROR] Window::_initialize(): SDL_CreateWindow() "\
            "failed. SDL Error " << SDL_GetError() << std::endl;
        return false;
    }

    //
    // Creates renderer
    //
    _renderer = SDL_CreateRenderer(_window, -1, SDL_RENDERER_ACCELERATED |
        SDL_RENDERER_TARGETTEXTURE);
    if (_renderer == NULL)
    {
        std::cerr << "[ERROR] Window::_initialize(): SDL_CreateRenderer() "\
            "failed. SDL Error " << SDL_GetError() << std::endl;
        return false;
    }

    //
    // Sets renderer to default to an Opqaue White color on screen clear
    //
    iRetVal = SDL_SetRenderDrawColor(_renderer, 0xFF, 0xFF, 0xFF,
        SDL_ALPHA_OPAQUE);
    if (iRetVal < 0)
    {
        std::cerr << "[ERROR] Window::_initialize(): SDL_SetRenderDrawColor()"\
            " failed. SDL Error " << SDL_GetError() << std::endl;
        return false;
    }

    //
    // Sets a device independent resolution for rendering
    //
    iRetVal = SDL_RenderSetLogicalSize(_renderer, _width, _height);
    if (iRetVal < 0)
    {
        std::cerr << "[ERROR] Window::_initialize(): "\
            "SDL_RenderSetLogicalSize() failed. SDL Error " << SDL_GetError()
            << std::endl;
        return false;
    }

    return true;
}

//*****************************************************************************
//
//! Terminates the window.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Window::_terminate()
{
    if (_renderer != NULL)
    {
        SDL_DestroyRenderer(_renderer);
    }

    if (_window != NULL)
    {
        SDL_DestroyWindow(_window);
    }
}

//*****************************************************************************
//
//! Processes user input. Called once per frame by update().
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Window::_processInput()
{
    SDL_Event event;

    //
    // Polls the event queue for pending events
    //
    while (SDL_PollEvent(&event))
    {
        //
        // Notifies the Application class that the user wants to quit
        //
        if (event.type == SDL_QUIT)
        {
            notify(SDL_QUIT);
        }
    }
}

//*****************************************************************************
//
//! Updates program logic. Called once per frame by update().
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Window::_update()
{
    // TODO (Brandon): Implement
}

//*****************************************************************************
//
//! Renders frame. Called once per frame by update().
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Window::_render()
{
    //
    // Clears screen
    //
    SDL_RenderClear(_renderer);

    //
    // Renders all images to screen
    //
    _baseImage->onRender();
    for (auto it = _fingerImageList.begin(); it != _fingerImageList.end();
        it++)
    {
        (*it)->onRender();
    }

    //
    // Updates screen (swaps screen buffers)
    //
    SDL_RenderPresent(_renderer);
}

//*****************************************************************************
//
//! Centre the image on the screen.
//!
//! \param image the image to be centred.
//!
//! \return None.
//
//*****************************************************************************
void Window::_centreImage(const std::unique_ptr<Image> &image)
{
    SDL_Rect centredRect;
    centredRect.w = image->getWidth();
    centredRect.h = image->getHeight();
    centredRect.x = (_width - centredRect.w) / 2;
    centredRect.y = (_height - centredRect.h) / 2;
    image->setRenderRect(&centredRect);
}
<commit_msg>Changed occurrences of NULL to nullptr when dealing with pointers.<commit_after>//*****************************************************************************
//
// Window.cpp
//
// Class responsible for spawning, managing, and closing the OpenGL context.
//
// Copyright (c) 2015 Brandon To, Minh Mai, and Yuzhou Liu
// This code is licensed under BSD license (see LICENSE.txt for details)
//
// Created:
// December 27, 2015
//
// Modified:
// December 28, 2015
//
//*****************************************************************************
#include "Window.h"

#include <iostream>

#include <SDL.h>

//*****************************************************************************
//
//! Constructor for Window. Acquires resources for window and renderer.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
Window::Window()
    : _window(nullptr), _renderer(nullptr), _width(_DEFAULT_WIDTH),
      _height(_DEFAULT_HEIGHT)
{
    //
    // Initialize window
    //
    if (!_initialize())
    {
        std::cerr << "[ERROR] Window::Window(): Failed to initialize." <<
            std::endl;
        return;
    }

    //
    // Creates base hand image
    //
    _baseImage = std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_base.png"));

    //
    // Creates and add images to finger image list
    //
    _fingerImageList.push_back(std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_right_thumb.png")));
    _fingerImageList.push_back(std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_right_index.png")));
    _fingerImageList.push_back(std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_right_middle.png")));
    _fingerImageList.push_back(std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_right_ring.png")));
    _fingerImageList.push_back(std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_right_pinky.png")));

    //
    // Centre all images for aesthetic purposes
    //
    _centreImage(_baseImage);
    for (auto it = _fingerImageList.begin(); it != _fingerImageList.end(); it++)
    {
        _centreImage(*it);
    }
}

//*****************************************************************************
//
//! Destructor for Window. Releases resources used by window and renderer.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
Window::~Window()
{
    _terminate();
}

//*****************************************************************************
//
//! Updates the window. Called once every frame.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Window::update()
{
    _processInput();
    _update();
    _render();
}

//*****************************************************************************
//
//! Initializes the window.
//!
//! \param None.
//!
//! \return Returns \b true if the window was initialized successfully and
//! \b false otherwise.
//
//*****************************************************************************
bool Window::_initialize()
{
    int iRetVal = 0;

    //
    // Creates OpenGL context
    //
    _window = SDL_CreateWindow("Human Interface for Robotic Control",
        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, _width, _height,
        SDL_WINDOW_SHOWN);
    if (_window == nullptr)
    {
        std::cerr << "[ERROR] Window::_initialize(): SDL_CreateWindow() "\
            "failed. SDL Error " << SDL_GetError() << std::endl;
        return false;
    }

    //
    // Creates renderer
    //
    _renderer = SDL_CreateRenderer(_window, -1, SDL_RENDERER_ACCELERATED |
        SDL_RENDERER_TARGETTEXTURE);
    if (_renderer == nullptr)
    {
        std::cerr << "[ERROR] Window::_initialize(): SDL_CreateRenderer() "\
            "failed. SDL Error " << SDL_GetError() << std::endl;
        return false;
    }

    //
    // Sets renderer to default to an Opqaue White color on screen clear
    //
    iRetVal = SDL_SetRenderDrawColor(_renderer, 0xFF, 0xFF, 0xFF,
        SDL_ALPHA_OPAQUE);
    if (iRetVal < 0)
    {
        std::cerr << "[ERROR] Window::_initialize(): SDL_SetRenderDrawColor()"\
            " failed. SDL Error " << SDL_GetError() << std::endl;
        return false;
    }

    //
    // Sets a device independent resolution for rendering
    //
    iRetVal = SDL_RenderSetLogicalSize(_renderer, _width, _height);
    if (iRetVal < 0)
    {
        std::cerr << "[ERROR] Window::_initialize(): "\
            "SDL_RenderSetLogicalSize() failed. SDL Error " << SDL_GetError()
            << std::endl;
        return false;
    }

    return true;
}

//*****************************************************************************
//
//! Terminates the window.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Window::_terminate()
{
    if (_renderer != nullptr)
    {
        SDL_DestroyRenderer(_renderer);
    }

    if (_window != nullptr)
    {
        SDL_DestroyWindow(_window);
    }
}

//*****************************************************************************
//
//! Processes user input. Called once per frame by update().
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Window::_processInput()
{
    SDL_Event event;

    //
    // Polls the event queue for pending events
    //
    while (SDL_PollEvent(&event))
    {
        //
        // Notifies the Application class that the user wants to quit
        //
        if (event.type == SDL_QUIT)
        {
            notify(SDL_QUIT);
        }
    }
}

//*****************************************************************************
//
//! Updates program logic. Called once per frame by update().
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Window::_update()
{
    // TODO (Brandon): Implement
}

//*****************************************************************************
//
//! Renders frame. Called once per frame by update().
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Window::_render()
{
    //
    // Clears screen
    //
    SDL_RenderClear(_renderer);

    //
    // Renders all images to screen
    //
    _baseImage->onRender();
    for (auto it = _fingerImageList.begin(); it != _fingerImageList.end();
        it++)
    {
        (*it)->onRender();
    }

    //
    // Updates screen (swaps screen buffers)
    //
    SDL_RenderPresent(_renderer);
}

//*****************************************************************************
//
//! Centre the image on the screen.
//!
//! \param image the image to be centred.
//!
//! \return None.
//
//*****************************************************************************
void Window::_centreImage(const std::unique_ptr<Image> &image)
{
    SDL_Rect centredRect;
    centredRect.w = image->getWidth();
    centredRect.h = image->getHeight();
    centredRect.x = (_width - centredRect.w) / 2;
    centredRect.y = (_height - centredRect.h) / 2;
    image->setRenderRect(&centredRect);
}
<|endoftext|>


<commit_before>// OfficeXlsFile.cpp : Implementation of COfficeXlsFile

#include "stdafx.h"

#include <string>
#include <iostream>

#include <boost/uuid/uuid.hpp>
#pragma warning(push)
#pragma warning(disable : 4244)
#include <boost/uuid/random_generator.hpp>
#pragma warning(pop)

#include <boost/algorithm/string/case_conv.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/lexical_cast.hpp>
#include <boost_filesystem_version.h>

#include "source\ConvertXls2Xlsx.h"

#include "..\Common\XmlUtils.h"
#include "..\Common\ASCATLError.h"

#include "OfficeXlsFile.h"

// :     1   ,      xlsx  docx
//               0   ,          package
#ifndef STANDALONE_USE
	#define STANDALONE_USE 0//    :  (1)   (0)
#endif

//   - uuid
boost::filesystem::wpath MakeTempDirectoryName(const std::wstring & Dst)
{
    boost::uuids::random_generator gen;
    boost::uuids::uuid u = gen();
    boost::filesystem::wpath path = boost::filesystem::wpath(Dst) / boost::lexical_cast<std::wstring>(u);
    return path;
}

std::wstring bstr2wstring(BSTR str)
{
    return str ? std::wstring(&str[0], &str[::SysStringLen(str)]) : L"";
}

boost::filesystem::wpath MakeTempDirectoryName(BSTR Dst)
{
    return MakeTempDirectoryName(bstr2wstring(Dst));
}
///------------------------------------------------------------------------------------

// COfficeXlsFile
COfficeXlsFile::COfficeXlsFile()
{
#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
    office_utils_.CoCreateInstance(__uuidof(ASCOfficeUtils::COfficeUtils));
#endif
}

HRESULT COfficeXlsFile::SaveToFile(BSTR sDstFileName, BSTR sSrcPath, BSTR sXMLOptions)
{
    return E_NOTIMPL;
}

HRESULT COfficeXlsFile::LoadFromFile(BSTR sSrcFileName, BSTR sDstPath, BSTR sXMLOptions)
{
    HRESULT hr;
    if (!initialized())
        return E_FAIL;

    if (!sDstPath)
    {
        _ASSERTE(!!sDstPath);
        return E_FAIL;
    }

#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
    boost::filesystem::wpath outputDir = boost::filesystem::wpath(bstr2wstring(sDstPath)).parent_path();
#else
    boost::filesystem::wpath outputDir = boost::filesystem::wpath(bstr2wstring(sDstPath));
#endif

#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
    boost::filesystem::wpath dstTempPath = MakeTempDirectoryName(BOOST_STRING_PATH(outputDir));
#else
    boost::filesystem::wpath dstTempPath = outputDir.string();
#endif

    try
    {
#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
        //
        boost::filesystem::create_directory(dstTempPath);
#endif
        hr = LoadFromFileImpl(bstr2wstring(sSrcFileName), BOOST_STRING_PATH(dstTempPath), bstr2wstring(sDstPath));

    }
    catch(...)
    {
        hr = E_FAIL;
    }

#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
    //           (   )
    try
    {
        boost::filesystem::remove_all(dstTempPath);
    }
    catch(...)
    {
    }
#endif

    return hr;
}

HRESULT COfficeXlsFile::LoadFromFileImpl(const std::wstring & srcFileName,
                                         const std::wstring & dstTempPath,
                                         const std::wstring & dstPath)
{
    HRESULT hr = AVS_ERROR_UNEXPECTED;

	ProgressCallback ffCallBack;

	ffCallBack.OnProgress	=	OnProgressFunc;
	ffCallBack.OnProgressEx	=	OnProgressExFunc;
	ffCallBack.caller		=	this;

	hr = ConvertXls2Xlsx(srcFileName, dstTempPath, &ffCallBack);

	if (hr != S_OK)  return hr;

#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
    if FAILED(hr = office_utils_->CompressFileOrDirectory(ATL::CComBSTR(dstTempPath.c_str()), ATL::CComBSTR(dstPath.c_str()), (-1)))
        return hr;
#endif

    return S_OK;
}

bool COfficeXlsFile::initialized()
{
#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
   return (!!office_utils_);
#endif
   return true;
}

void COfficeXlsFile::OnProgressFunc (LPVOID lpParam, long nID, long nPercent)
{
	//g_oCriticalSection.Enter();

	COfficeXlsFile* pXlsFile = reinterpret_cast<COfficeXlsFile*>(lpParam);
	if (pXlsFile != NULL)
	{
		pXlsFile->OnProgress(nID, nPercent);
	}

	//g_oCriticalSection.Leave();
}

void COfficeXlsFile::OnProgressExFunc (LPVOID lpParam, long nID, long nPercent, short* pStop)
{
	//g_oCriticalSection.Enter();

	COfficeXlsFile* pXlsFile = reinterpret_cast<COfficeXlsFile*>(lpParam);
	if (pXlsFile != NULL)
	{
		pXlsFile->OnProgressEx(nID, nPercent, pStop);
	}

	//g_oCriticalSection.Leave();
}
<commit_msg>            <commit_after>// OfficeXlsFile.cpp : Implementation of COfficeXlsFile

#include "stdafx.h"

#include <string>
#include <iostream>

#include <boost/uuid/uuid.hpp>
#pragma warning(push)
#pragma warning(disable : 4244)
#include <boost/uuid/random_generator.hpp>
#pragma warning(pop)

#include <boost/algorithm/string/case_conv.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/lexical_cast.hpp>
#include "../Common/boost_filesystem_version.h"

#include "source/ConvertXls2Xlsx.h"

#include "../Common/XmlUtils.h"
#include "../Common/ASCATLError.h"

#include "OfficeXlsFile.h"

// :     1   ,      xlsx  docx
//               0   ,          package
#ifndef STANDALONE_USE
	#define STANDALONE_USE 0//    :  (1)   (0)
#endif

//   - uuid
boost::filesystem::wpath MakeTempDirectoryName(const std::wstring & Dst)
{
    boost::uuids::random_generator gen;
    boost::uuids::uuid u = gen();
    boost::filesystem::wpath path = boost::filesystem::wpath(Dst) / boost::lexical_cast<std::wstring>(u);
    return path;
}

std::wstring bstr2wstring(BSTR str)
{
    return str ? std::wstring(&str[0], &str[::SysStringLen(str)]) : L"";
}

boost::filesystem::wpath MakeTempDirectoryName(BSTR Dst)
{
    return MakeTempDirectoryName(bstr2wstring(Dst));
}
///------------------------------------------------------------------------------------

// COfficeXlsFile
COfficeXlsFile::COfficeXlsFile()
{
#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
    office_utils_.CoCreateInstance(__uuidof(ASCOfficeUtils::COfficeUtils));
#endif
}

HRESULT COfficeXlsFile::SaveToFile(BSTR sDstFileName, BSTR sSrcPath, BSTR sXMLOptions)
{
    return E_NOTIMPL;
}

HRESULT COfficeXlsFile::LoadFromFile(BSTR sSrcFileName, BSTR sDstPath, BSTR sXMLOptions)
{
    HRESULT hr;
    if (!initialized())
        return E_FAIL;

    if (!sDstPath)
    {
        _ASSERTE(!!sDstPath);
        return E_FAIL;
    }

#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
    boost::filesystem::wpath outputDir = boost::filesystem::wpath(bstr2wstring(sDstPath)).parent_path();
#else
    boost::filesystem::wpath outputDir = boost::filesystem::wpath(bstr2wstring(sDstPath));
#endif

#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
    boost::filesystem::wpath dstTempPath = MakeTempDirectoryName(BOOST_STRING_PATH(outputDir));
#else
    boost::filesystem::wpath dstTempPath = outputDir.string();
#endif

    try
    {
#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
        //
        boost::filesystem::create_directory(dstTempPath);
#endif
        hr = LoadFromFileImpl(bstr2wstring(sSrcFileName), BOOST_STRING_PATH(dstTempPath), bstr2wstring(sDstPath));

    }
    catch(...)
    {
        hr = E_FAIL;
    }

#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
    //           (   )
    try
    {
        boost::filesystem::remove_all(dstTempPath);
    }
    catch(...)
    {
    }
#endif

    return hr;
}

HRESULT COfficeXlsFile::LoadFromFileImpl(const std::wstring & srcFileName,
                                         const std::wstring & dstTempPath,
                                         const std::wstring & dstPath)
{
    HRESULT hr = AVS_ERROR_UNEXPECTED;

	ProgressCallback ffCallBack;

	ffCallBack.OnProgress	=	OnProgressFunc;
	ffCallBack.OnProgressEx	=	OnProgressExFunc;
	ffCallBack.caller		=	this;

	hr = ConvertXls2Xlsx(srcFileName, dstTempPath, &ffCallBack);

	if (hr != S_OK)  return hr;

#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
    if FAILED(hr = office_utils_->CompressFileOrDirectory(ATL::CComBSTR(dstTempPath.c_str()), ATL::CComBSTR(dstPath.c_str()), (-1)))
        return hr;
#endif

    return S_OK;
}

bool COfficeXlsFile::initialized()
{
#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
   return (!!office_utils_);
#endif
   return true;
}

void COfficeXlsFile::OnProgressFunc (LPVOID lpParam, long nID, long nPercent)
{
	//g_oCriticalSection.Enter();

	COfficeXlsFile* pXlsFile = reinterpret_cast<COfficeXlsFile*>(lpParam);
	if (pXlsFile != NULL)
	{
		pXlsFile->OnProgress(nID, nPercent);
	}

	//g_oCriticalSection.Leave();
}

void COfficeXlsFile::OnProgressExFunc (LPVOID lpParam, long nID, long nPercent, short* pStop)
{
	//g_oCriticalSection.Enter();

	COfficeXlsFile* pXlsFile = reinterpret_cast<COfficeXlsFile*>(lpParam);
	if (pXlsFile != NULL)
	{
		pXlsFile->OnProgressEx(nID, nPercent, pStop);
	}

	//g_oCriticalSection.Leave();
}
<|endoftext|>


<commit_before>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* BSD 3-Clause License
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Code by Cassius Fiorin - cafiorin@gmail.com
http://pinballhomemade.blogspot.com.br
* * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#include "Utils.h"

void myStrcpy(char *str1, const char *str2)
{
	int bufsize = sizeof(str1);
	int len = (int) strlen(str2);
	if (len < bufsize)
	{
		strcpy(str1, str2);
	}
	else
	{
		strncpy(str1, str2, bufsize);
		str1[bufsize - 1] = 0;
	}

}

#ifdef ARDUINO
long Millis()
{
	return millis();
}

#endif

#ifdef DOS
clock_t Millis()
{
	return clock();
}

long timediff(clock_t t2, clock_t t1)
{
	long elapsed;
	elapsed = ((double)t2 - t1) / CLOCKS_PER_SEC * 1000;
	return elapsed;
}

void gotoxy(int x, int y)
{
	COORD coord;
	coord.X = x;
	coord.Y = y;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

void getCursorXY(int &x, int&y)
{
	CONSOLE_SCREEN_BUFFER_INFO csbi;

	if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
	{
		x = csbi.dwCursorPosition.X;
		y = csbi.dwCursorPosition.Y;
	}
}

void setcolor(WORD color)
{
	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
	return;
}

void clrscr()
{
	COORD coordScreen = { 0, 0 };
	DWORD cCharsWritten;
	CONSOLE_SCREEN_BUFFER_INFO csbi;
	DWORD dwConSize;
	HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

	GetConsoleScreenBufferInfo(hConsole, &csbi);
	dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
	FillConsoleOutputCharacter(hConsole, TEXT(' '), dwConSize, coordScreen, &cCharsWritten);
	GetConsoleScreenBufferInfo(hConsole, &csbi);
	FillConsoleOutputAttribute(hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten);
	SetConsoleCursorPosition(hConsole, coordScreen);
	return;
}

void box(unsigned x, unsigned y, unsigned sx, unsigned sy, unsigned char col, unsigned char col2, char text_[])
{
	unsigned i, j, m;
	{

		m = (sx - x);                       //differential
		j = m / 8;                          //adjust
		j = j - 1;                          //more adjustment
		gotoxy(x, y); cprintf("┌");         //Top left corner of box
		gotoxy(sx, y); cprintf("¬");        //Top right corner of box
		gotoxy(x, sy); cprintf("└");        //Bottom left corner of box
		gotoxy(sx, sy); cprintf("┌");       //Bottom right corner of box

		for (i = x + 1; i<sx; i++)
		{
			gotoxy(i, y); cprintf("-");     // Top horizontol line
			gotoxy(i, sy); cprintf("-");    // Bottom Horizontal line
		}

		for (i = y + 1; i<sy; i++)
		{
			gotoxy(x, i); cprintf("|");     //Left Vertical line
			gotoxy(sx, i); cprintf("|");    //Right Vertical Line
		}

		gotoxy(x + j, y); cprintf(text_); //put Title
		gotoxy(1, 24);
	}
}

void clrbox(unsigned char x1, unsigned char y1, unsigned char x2, unsigned char y2, unsigned char bkcol)
{
	int x, y;
	setcolor(bkcol);                       //Set to color bkcol

	for (y = y1; y<y2; y++)                    //Fill Y Region Loop
	{
		for (x = x1; x<x2; x++)               //Fill X region Loop
		{
			gotoxy(x, y); cprintf(" ");       //Draw Solid space
		}
	}
}

void putbox(unsigned x, unsigned y, unsigned sx, unsigned sy,unsigned char col, unsigned char col2, unsigned char bkcol, char text_[])
{
	clrbox(x, y, sx, sy, bkcol);
	box(x, y, sx, sy, col, col2, text_);
}

void txtPlot(unsigned char x, unsigned char y, unsigned char Color)
{
	setcolor(Color);
	gotoxy(x, y); cprintf(".");
}

void delay(unsigned int milliseconds)
{
	clock_t ticks1, ticks2;
	unsigned int tic1 = 0, tic2 = 0, tick = 0;

	ticks1 = clock();
	while (tick<milliseconds)
	{
		ticks2 = clock();
		tic1 = ticks2 / CLOCKS_PER_SEC - ticks1;
		tic2 = ticks1 / CLOCKS_PER_SEC;
		tick = ticks2 - ticks1;
	}
	ticks2 = clock();
}

#endif

<commit_msg>Fixed square<commit_after>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* BSD 3-Clause License
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Code by Cassius Fiorin - cafiorin@gmail.com
http://pinballhomemade.blogspot.com.br
* * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#include "Utils.h"

#pragma execution_character_set("utf-8")

void myStrcpy(char *str1, const char *str2)
{
	int bufsize = sizeof(str1);
	int len = (int) strlen(str2);
	if (len < bufsize)
	{
		strcpy(str1, str2);
	}
	else
	{
		strncpy(str1, str2, bufsize);
		str1[bufsize - 1] = 0;
	}

}

#ifdef ARDUINO
long Millis()
{
	return millis();
}

#endif

#ifdef DOS
clock_t Millis()
{
	return clock();
}

long timediff(clock_t t2, clock_t t1)
{
	long elapsed;
	elapsed = (long) ((double)t2 - t1) / CLOCKS_PER_SEC * 1000;
	return elapsed;
}

void gotoxy(int x, int y)
{
	COORD coord;
	coord.X = x;
	coord.Y = y;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

void getCursorXY(int &x, int&y)
{
	CONSOLE_SCREEN_BUFFER_INFO csbi;

	if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
	{
		x = csbi.dwCursorPosition.X;
		y = csbi.dwCursorPosition.Y;
	}
}

void setcolor(WORD color)
{
	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
	return;
}

void clrscr()
{
	COORD coordScreen = { 0, 0 };
	DWORD cCharsWritten;
	CONSOLE_SCREEN_BUFFER_INFO csbi;
	DWORD dwConSize;
	HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

	GetConsoleScreenBufferInfo(hConsole, &csbi);
	dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
	FillConsoleOutputCharacter(hConsole, TEXT(' '), dwConSize, coordScreen, &cCharsWritten);
	GetConsoleScreenBufferInfo(hConsole, &csbi);
	FillConsoleOutputAttribute(hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten);
	SetConsoleCursorPosition(hConsole, coordScreen);
	return;
}

void box(unsigned x, unsigned y, unsigned sx, unsigned sy, unsigned char col, unsigned char col2, char text_[])
{
	unsigned i, j, m;
	{

		m = (sx - x);                       //differential
		j = m / 8;                          //adjust
		j = j - 1;                          //more adjustment
		gotoxy(x, y); cprintf("*"); //   ┌       //Top left corner of box
		gotoxy(sx, y); cprintf("*"); //  ┐       //Top right corner of box
		gotoxy(x, sy); cprintf("*"); //  └       //Bottom left corner of box
		gotoxy(sx, sy); cprintf("*"); // ┘       //Bottom right corner of box

		for (i = x + 1; i<sx; i++)
		{
			gotoxy(i, y); cprintf("-");     // Top horizontol line
			gotoxy(i, sy); cprintf("-");    // Bottom Horizontal line
		}

		for (i = y + 1; i<sy; i++)
		{
			gotoxy(x, i); cprintf("|");     //Left Vertical line
			gotoxy(sx, i); cprintf("|");    //Right Vertical Line
		}

		gotoxy(x + j, y); cprintf(text_); //put Title
		gotoxy(1, 24);
	}
}

void clrbox(unsigned char x1, unsigned char y1, unsigned char x2, unsigned char y2, unsigned char bkcol)
{
	int x, y;
	setcolor(bkcol);                       //Set to color bkcol

	for (y = y1; y<y2; y++)                    //Fill Y Region Loop
	{
		for (x = x1; x<x2; x++)               //Fill X region Loop
		{
			gotoxy(x, y); cprintf(" ");       //Draw Solid space
		}
	}
}

void putbox(unsigned x, unsigned y, unsigned sx, unsigned sy,unsigned char col, unsigned char col2, unsigned char bkcol, char text_[])
{
	clrbox(x, y, sx, sy, bkcol);
	box(x, y, sx, sy, col, col2, text_);
}

void txtPlot(unsigned char x, unsigned char y, unsigned char Color)
{
	setcolor(Color);
	gotoxy(x, y); cprintf(".");
}

void delay(unsigned int milliseconds)
{
	clock_t ticks1, ticks2;
	unsigned int tic1 = 0, tic2 = 0, tick = 0;

	ticks1 = clock();
	while (tick<milliseconds)
	{
		ticks2 = clock();
		tic1 = ticks2 / CLOCKS_PER_SEC - ticks1;
		tic2 = ticks1 / CLOCKS_PER_SEC;
		tick = ticks2 - ticks1;
	}
	ticks2 = clock();
}

#endif

<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "QtHttpAssetProvider.h"
#include "ConfigurationManager.h"
#include "EventManager.h"
#include "AssetModule.h"

#include "RexAsset.h"
#include "AssetMetadataInterface.h"
#include "AssetServiceInterface.h"
#include "AssetEvents.h"

#include <QUuid>
#include <QNetworkReply>
#include <QByteArray>

#include <QDebug>
#include <QStringList>

#define MAX_HTTP_CONNECTIONS 10000 // Basically means no limit to parallel connections

namespace Asset
{
    QtHttpAssetProvider::QtHttpAssetProvider(Foundation::Framework *framework) :
        QObject(),
        framework_(framework),
        event_manager_(framework->GetEventManager().get()),
        name_("QtHttpAssetProvider"),
        network_manager_(new QNetworkAccessManager()),
        filling_stack_(false),
        get_texture_cap_(QUrl())
    {
		asset_timeout_ = framework_->GetDefaultConfig().DeclareSetting("AssetSystem", "http_timeout", 120.0);
        if (event_manager_)
            asset_event_category_ = event_manager_->QueryEventCategory("Asset");
        if (!asset_event_category_)
            AssetModule::LogWarning("QtHttpAssetProvider >> Could not get event category for Asset events");

        connect(network_manager_, SIGNAL(finished(QNetworkReply*)), SLOT(TranferCompleted(QNetworkReply*)));

        AssetModule::LogWarning(QString("QtHttpAssetProvider >> Initialized with max %1 parallel HTTP connections").arg(QString::number(MAX_HTTP_CONNECTIONS)).toStdString());
    }

    QtHttpAssetProvider::~QtHttpAssetProvider()
    {
        SAFE_DELETE(network_manager_);
    }

    void QtHttpAssetProvider::SetGetTextureCap(std::string url)
    {
        get_texture_cap_ = QUrl(QString::fromStdString(url));
    }

    // Interface implementation

    void QtHttpAssetProvider::Update(f64 frametime)
    {
        StartTransferFromQueue();
    }

    const std::string& QtHttpAssetProvider::Name()
    {
        return name_;
    }

    bool QtHttpAssetProvider::IsValidId(const std::string& asset_id, const std::string& asset_type)
    {
        // Textures over http with the GetTexture cap
        if (IsAcceptableAssetType(asset_type))
            if (RexUUID::IsValid(asset_id) && get_texture_cap_.isValid())
                return true;

        QString id(asset_id.c_str());
        if (!id.startsWith("http://"))
            return false;

        QUrl asset_url(id);
        if (asset_url.isValid())
            return true;
        else
            return false;
    }

    bool QtHttpAssetProvider::RequestAsset(const std::string& asset_id, const std::string& asset_type, request_tag_t tag)
    {
        if (!IsValidId(asset_id, asset_type))
            return false;

        QString asset_id_qstring = QString::fromStdString(asset_id);
        if (assetid_to_transfer_map_.contains(asset_id_qstring))
        {
            assetid_to_transfer_map_[asset_id_qstring]->GetTranferInfo().AddTag(tag);
        }
        else
        {
            asset_type_t asset_type_int = RexTypes::GetAssetTypeFromTypeName(asset_type);
            QtHttpAssetTransfer *transfer = 0;

            if (IsAcceptableAssetType(asset_type))
            {
                // Http texture via cap url
                QString texture_url_string = get_texture_cap_.toString() + "?texture_id=" + asset_id_qstring;
                QUrl texture_url(texture_url_string);
                transfer = new QtHttpAssetTransfer(texture_url, asset_id_qstring, asset_type_int, tag);
            }
            else
            {
                // Normal http get
                QUrl asset_url = CreateUrl(asset_id_qstring);
                transfer = new QtHttpAssetTransfer(asset_url, asset_id_qstring, asset_type_int, tag);
            }

            if (!transfer)
                return false;

            transfer->setOriginatingObject(transfer);
            if (assetid_to_transfer_map_.count() <= MAX_HTTP_CONNECTIONS)
            {
                assetid_to_transfer_map_[asset_id_qstring] = transfer;
                network_manager_->get(*transfer);
                AssetModule::LogDebug("New HTTP asset request: " + asset_id + " type: " + asset_type);
            }
            else
                pending_request_queue_.append(transfer);
        }
        return true;
    }

    bool QtHttpAssetProvider::InProgress(const std::string& asset_id)
    {
        QString qt_asset_id = QString::fromStdString(asset_id);
        if (assetid_to_transfer_map_.contains(qt_asset_id) || CheckRequestQueue(qt_asset_id))
            return true;
        else
            return false;
    }

    bool QtHttpAssetProvider::QueryAssetStatus(const std::string& asset_id, uint& size, uint& received, uint& received_continuous)
    {
        if (InProgress(asset_id))
        {
            // We dont know, QNetworkAccessManager handles these
            size = 0;
            received = 0;
            received_continuous = 0;
            return true;
        }
        else
            return false;
    }

    Foundation::AssetPtr QtHttpAssetProvider::GetIncompleteAsset(const std::string& asset_id, const std::string& asset_type, uint received)
    {
        return Foundation::AssetPtr();
    }

    Foundation::AssetTransferInfoVector QtHttpAssetProvider::GetTransferInfo()
    {
        Foundation::AssetTransferInfoVector info_vector;
        foreach (QtHttpAssetTransfer *transfer, assetid_to_transfer_map_.values())
        {
            HttpAssetTransferInfo iter_info = transfer->GetTranferInfo();
            // What we know
            Foundation::AssetTransferInfo info;
            info.id_ = iter_info.id.toStdString();
            info.type_ = RexTypes::GetAssetTypeString(iter_info.type);
            info.provider_ = Name();
            // The following we dont know, QNetworkAccessManager handles these
            info.size_ = 0;
            info.received_ = 0;
            info.received_continuous_ = 0;
            info_vector.push_back(info);
        }
        return info_vector;
    }

    // Private

    QUrl QtHttpAssetProvider::CreateUrl(QString assed_id)
    {
        if (!assed_id.startsWith("http://") && !assed_id.startsWith("https://"))
            assed_id = "http://" + assed_id;
        return QUrl(assed_id);
    }

    void QtHttpAssetProvider::TranferCompleted(QNetworkReply *reply)
    {
        fake_metadata_fetch_ = false;
        QtHttpAssetTransfer *transfer = dynamic_cast<QtHttpAssetTransfer*>(reply->request().originatingObject());

        /**** THIS IS A DATA REQUEST REPLY AND IT FAILED ****/
        if (reply->error() != QNetworkReply::NoError && transfer)
        {
            // Send asset canceled events
            HttpAssetTransferInfo error_transfer_data = transfer->GetTranferInfo();
            Events::AssetCanceled *data = new Events::AssetCanceled(error_transfer_data.id.toStdString(), RexTypes::GetAssetTypeString(error_transfer_data.type));
            Foundation::EventDataPtr data_ptr(data);
            event_manager_->SendDelayedEvent(asset_event_category_, Events::ASSET_CANCELED, data_ptr, 0);

            // Clean up
            RemoveFinishedTransfers(error_transfer_data.id, reply->url());
            StartTransferFromQueue();

            AssetModule::LogDebug("HTTP asset " + error_transfer_data.id.toStdString() + " canceled");
            reply->deleteLater();
            return;
        }

        /**** THIS IS A /data REQUEST REPLY ****/
        if (transfer)
        {
            // Create asset pointer
            HttpAssetTransferInfo tranfer_info = transfer->GetTranferInfo();
            std::string id = tranfer_info.id.toStdString();
            std::string type = RexTypes::GetTypeNameFromAssetType(tranfer_info.type);
            Foundation::AssetPtr asset_ptr = Foundation::AssetPtr(new RexAsset(id, type));

            // Fill asset data with reply data
            RexAsset::AssetDataVector& data_vector = checked_static_cast<RexAsset*>(asset_ptr.get())->GetDataInternal();
            QByteArray data_array = reply->readAll();
            for (int index = 0; index < data_array.count(); ++index)
                data_vector.push_back(data_array.at(index));

            // Get metadata if available
            QString url_path = tranfer_info.url.path();
            if (url_path.endsWith("/data") || url_path.endsWith("/data/"))
            {
                // Generate metada url
                int clip_count;
                if (url_path.endsWith("/data"))
                    clip_count = 5;
                else if (url_path.endsWith("/data/"))
                    clip_count = 6;
                else
                {
                    reply->deleteLater();
                    return;
                }

                QUrl metadata_url = tranfer_info.url;
                url_path = url_path.left(url_path.count()-clip_count);
                url_path = url_path + "/metadata";
                metadata_url.setPath(url_path);
                tranfer_info.url = metadata_url;

                QNetworkRequest *metada_request = new QNetworkRequest(metadata_url);

                // Store tranfer data and asset data pointer internally
                QPair<HttpAssetTransferInfo, Foundation::AssetPtr> data_pair;
                data_pair.first = tranfer_info;
                data_pair.second = asset_ptr;
                metadata_to_assetptr_[metada_request->url()] = data_pair;

                // Send metadata network request
                //network_manager_->get(*metada_request);

                // HACK to avoid metadata fetch for now
                fake_metadata_url_ = metada_request->url();
                fake_metadata_fetch_ = true;
            }
            // Asset data feched, lets store
            else
            {
                // Store asset
                boost::shared_ptr<Foundation::AssetServiceInterface> asset_service = framework_->GetServiceManager()->GetService<Foundation::AssetServiceInterface>(Foundation::Service::ST_Asset).lock();
                if (asset_service)
                    asset_service->StoreAsset(asset_ptr);

                // Send asset ready events
                foreach (request_tag_t tag, tranfer_info.tags)
                {
                    Events::AssetReady event_data(asset_ptr.get()->GetId(), asset_ptr.get()->GetType(), asset_ptr, tag);
                    event_manager_->SendEvent(asset_event_category_, Events::ASSET_READY, &event_data);
                }

                RemoveFinishedTransfers(tranfer_info.id, QUrl());
                StartTransferFromQueue();
                AssetModule::LogDebug("HTTP asset " + tranfer_info.id.toStdString() + " completed");
            }
        }

        // Complete /data and /metadata sequence, fake is here as long as we dont have xml parser for metadata
        // or actually we dont use metadata in naali so thats the main reason its not fetched
        if (fake_metadata_fetch_)
        {
            /**** THIS IS A /metadata REQUEST REPLY ****/
            if (metadata_to_assetptr_.contains(fake_metadata_url_))
            {
                // Pull out transfer data and asset pointer assosiated with this reply url
                QUrl metadata_transfer_url = fake_metadata_url_;
                HttpAssetTransferInfo transfer_data = metadata_to_assetptr_[metadata_transfer_url].first;
                Foundation::AssetPtr ready_asset_ptr = metadata_to_assetptr_[metadata_transfer_url].second;
                if (!ready_asset_ptr)
                {
                    reply->deleteLater();
                    return;
                }

                // Fill metadata
                /*
                const QByteArray &inbound_metadata = reply->readAll();
                QString decoded_metadata = QString::fromUtf8(inbound_metadata.data());
                #if defined(__GNUC__)
                RexAssetMetadata *m = dynamic_cast<RexAssetMetadata*>(ready_asset_ptr.get()->GetMetadata());
                #else
                Foundation::AssetMetadataInterface *metadata = ready_asset_ptr.get()->GetMetadata();
                RexAssetMetadata *m = static_cast<RexAssetMetadata*>(metadata);
                #endif
                std::string std_md(decoded_metadata.toStdString());

                m->DesesrializeFromJSON(std_md); // TODO: implement a xml based metadata parser.
                */

                // Store asset
                boost::shared_ptr<Foundation::AssetServiceInterface> asset_service = framework_->GetServiceManager()->GetService<Foundation::AssetServiceInterface>(Foundation::Service::ST_Asset).lock();
                if (asset_service)
                    asset_service->StoreAsset(ready_asset_ptr);

                // Send asset ready events
                foreach (request_tag_t tag, transfer_data.tags)
                {
                    Events::AssetReady event_data(ready_asset_ptr.get()->GetId(), ready_asset_ptr.get()->GetType(), ready_asset_ptr, tag);
                    event_manager_->SendEvent(asset_event_category_, Events::ASSET_READY, &event_data);
                }

                RemoveFinishedTransfers(transfer_data.id, metadata_transfer_url);
                StartTransferFromQueue();
                AssetModule::LogDebug("HTTP asset " + transfer_data.id.toStdString() + " completed with metadata");
            }
        }
        reply->deleteLater();
    }

    void QtHttpAssetProvider::RemoveFinishedTransfers(QString asset_transfer_key, QUrl metadata_transfer_key)
    {
        QtHttpAssetTransfer *remove_transfer = assetid_to_transfer_map_[asset_transfer_key];
        assetid_to_transfer_map_.remove(asset_transfer_key);
        if (metadata_transfer_key.isValid())
            metadata_to_assetptr_.remove(metadata_transfer_key);
        SAFE_DELETE(remove_transfer);
    }

    void QtHttpAssetProvider::ClearAllTransfers()
    {
        foreach (QtHttpAssetTransfer *transfer, assetid_to_transfer_map_.values())
            SAFE_DELETE(transfer);
        assetid_to_transfer_map_.clear();

        foreach (QtHttpAssetTransfer *transfer, pending_request_queue_)
            SAFE_DELETE(transfer);
        pending_request_queue_.clear();
    }

    void QtHttpAssetProvider::StartTransferFromQueue()
    {
        if (pending_request_queue_.count() == 0)
            return;

        // If the whole map is empty then go and start new MAX_HTTP_CONNECTIONS amount of http gets
        if (assetid_to_transfer_map_.count() == 0)
            filling_stack_ = true;

        if (!filling_stack_)
            return;

        if (assetid_to_transfer_map_.count() <= MAX_HTTP_CONNECTIONS && pending_request_queue_.count() > 0)
        {
            if (assetid_to_transfer_map_.count() == MAX_HTTP_CONNECTIONS || pending_request_queue_.count() == 0)
                filling_stack_ = false;
            else
            {
                QtHttpAssetTransfer *new_transfer = pending_request_queue_.takeAt(0);
                assetid_to_transfer_map_[new_transfer->GetTranferInfo().id] = new_transfer;
                network_manager_->get(*new_transfer);

                AssetModule::LogDebug("New HTTP asset request from queue: " + new_transfer->GetTranferInfo().id.toStdString() + " type: " + RexTypes::GetAssetTypeString(new_transfer->GetTranferInfo().type));
                StartTransferFromQueue(); // Recursivly fill the transfer map
            }
        }
    }

    bool QtHttpAssetProvider::CheckRequestQueue(QString assed_id)
    {
        foreach (QtHttpAssetTransfer *transfer, pending_request_queue_)
            if (transfer->GetTranferInfo().id == assed_id)
                return true;
        return false;
    }

    bool QtHttpAssetProvider::IsAcceptableAssetType(const std::string& asset_type)
    {
        using namespace RexTypes;

        bool accepted = false;
        switch (GetAssetTypeFromTypeName(asset_type))
        {
            case RexAT_Texture:
            case RexAT_Mesh:
                accepted = true;
                break;
            default:
                accepted = false;
                break;
        }
        return accepted;
    }
}<commit_msg>Bug fix to handle urls properly if caps url not set (modrex addurls etc). Printing a info line to console if server has http assets enabled.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "QtHttpAssetProvider.h"
#include "ConfigurationManager.h"
#include "EventManager.h"
#include "AssetModule.h"

#include "RexAsset.h"
#include "AssetMetadataInterface.h"
#include "AssetServiceInterface.h"
#include "AssetEvents.h"

#include <QUuid>
#include <QNetworkReply>
#include <QByteArray>

#include <QDebug>
#include <QStringList>

#define MAX_HTTP_CONNECTIONS 10000 // Basically means no limit to parallel connections

namespace Asset
{
    QtHttpAssetProvider::QtHttpAssetProvider(Foundation::Framework *framework) :
        QObject(),
        framework_(framework),
        event_manager_(framework->GetEventManager().get()),
        name_("QtHttpAssetProvider"),
        network_manager_(new QNetworkAccessManager()),
        filling_stack_(false),
        get_texture_cap_(QUrl())
    {
		asset_timeout_ = framework_->GetDefaultConfig().DeclareSetting("AssetSystem", "http_timeout", 120.0);
        if (event_manager_)
            asset_event_category_ = event_manager_->QueryEventCategory("Asset");
        if (!asset_event_category_)
            AssetModule::LogWarning("QtHttpAssetProvider >> Could not get event category for Asset events");

        connect(network_manager_, SIGNAL(finished(QNetworkReply*)), SLOT(TranferCompleted(QNetworkReply*)));

        AssetModule::LogWarning(QString("QtHttpAssetProvider >> Initialized with max %1 parallel HTTP connections").arg(QString::number(MAX_HTTP_CONNECTIONS)).toStdString());
    }

    QtHttpAssetProvider::~QtHttpAssetProvider()
    {
        SAFE_DELETE(network_manager_);
    }

    void QtHttpAssetProvider::SetGetTextureCap(std::string url)
    {
        get_texture_cap_ = QUrl(QString::fromStdString(url));
        if (get_texture_cap_.isValid())
            AssetModule::LogInfo("Server supports HTTP assets: using HTTP to fetch textures and meshes.");
    }

    // Interface implementation

    void QtHttpAssetProvider::Update(f64 frametime)
    {
        StartTransferFromQueue();
    }

    const std::string& QtHttpAssetProvider::Name()
    {
        return name_;
    }

    bool QtHttpAssetProvider::IsValidId(const std::string& asset_id, const std::string& asset_type)
    {
        // Textures over http with the GetTexture cap
        if (IsAcceptableAssetType(asset_type))
            if (RexUUID::IsValid(asset_id) && get_texture_cap_.isValid())
                return true;

        QString id(asset_id.c_str());
        if (!id.startsWith("http://"))
            return false;

        QUrl asset_url(id);
        if (asset_url.isValid())
            return true;
        else
            return false;
    }

    bool QtHttpAssetProvider::RequestAsset(const std::string& asset_id, const std::string& asset_type, request_tag_t tag)
    {
        if (!IsValidId(asset_id, asset_type))
            return false;

        QString asset_id_qstring = QString::fromStdString(asset_id);
        if (assetid_to_transfer_map_.contains(asset_id_qstring))
        {
            assetid_to_transfer_map_[asset_id_qstring]->GetTranferInfo().AddTag(tag);
        }
        else
        {
            asset_type_t asset_type_int = RexTypes::GetAssetTypeFromTypeName(asset_type);
            QtHttpAssetTransfer *transfer = 0;

            if (IsAcceptableAssetType(asset_type) && RexUUID::IsValid(asset_id) && get_texture_cap_.isValid())
            {
                // Http texture/meshes via cap url
                QString texture_url_string = get_texture_cap_.toString() + "?texture_id=" + asset_id_qstring;
                QUrl texture_url(texture_url_string);
                transfer = new QtHttpAssetTransfer(texture_url, asset_id_qstring, asset_type_int, tag);
            }
            else
            {
                // Normal http get
                QUrl asset_url = CreateUrl(asset_id_qstring);
                transfer = new QtHttpAssetTransfer(asset_url, asset_id_qstring, asset_type_int, tag);
            }

            if (!transfer)
                return false;

            transfer->setOriginatingObject(transfer);
            if (assetid_to_transfer_map_.count() <= MAX_HTTP_CONNECTIONS)
            {
                assetid_to_transfer_map_[asset_id_qstring] = transfer;
                network_manager_->get(*transfer);
                AssetModule::LogDebug("New HTTP asset request: " + asset_id + " type: " + asset_type);
            }
            else
                pending_request_queue_.append(transfer);
        }
        return true;
    }

    bool QtHttpAssetProvider::InProgress(const std::string& asset_id)
    {
        QString qt_asset_id = QString::fromStdString(asset_id);
        if (assetid_to_transfer_map_.contains(qt_asset_id) || CheckRequestQueue(qt_asset_id))
            return true;
        else
            return false;
    }

    bool QtHttpAssetProvider::QueryAssetStatus(const std::string& asset_id, uint& size, uint& received, uint& received_continuous)
    {
        if (InProgress(asset_id))
        {
            // We dont know, QNetworkAccessManager handles these
            size = 0;
            received = 0;
            received_continuous = 0;
            return true;
        }
        else
            return false;
    }

    Foundation::AssetPtr QtHttpAssetProvider::GetIncompleteAsset(const std::string& asset_id, const std::string& asset_type, uint received)
    {
        return Foundation::AssetPtr();
    }

    Foundation::AssetTransferInfoVector QtHttpAssetProvider::GetTransferInfo()
    {
        Foundation::AssetTransferInfoVector info_vector;
        foreach (QtHttpAssetTransfer *transfer, assetid_to_transfer_map_.values())
        {
            HttpAssetTransferInfo iter_info = transfer->GetTranferInfo();
            // What we know
            Foundation::AssetTransferInfo info;
            info.id_ = iter_info.id.toStdString();
            info.type_ = RexTypes::GetAssetTypeString(iter_info.type);
            info.provider_ = Name();
            // The following we dont know, QNetworkAccessManager handles these
            info.size_ = 0;
            info.received_ = 0;
            info.received_continuous_ = 0;
            info_vector.push_back(info);
        }
        return info_vector;
    }

    // Private

    QUrl QtHttpAssetProvider::CreateUrl(QString assed_id)
    {
        if (!assed_id.startsWith("http://") && !assed_id.startsWith("https://"))
            assed_id = "http://" + assed_id;
        return QUrl(assed_id);
    }

    void QtHttpAssetProvider::TranferCompleted(QNetworkReply *reply)
    {
        fake_metadata_fetch_ = false;
        QtHttpAssetTransfer *transfer = dynamic_cast<QtHttpAssetTransfer*>(reply->request().originatingObject());

        /**** THIS IS A DATA REQUEST REPLY AND IT FAILED ****/
        if (reply->error() != QNetworkReply::NoError && transfer)
        {
            // Send asset canceled events
            HttpAssetTransferInfo error_transfer_data = transfer->GetTranferInfo();
            Events::AssetCanceled *data = new Events::AssetCanceled(error_transfer_data.id.toStdString(), RexTypes::GetAssetTypeString(error_transfer_data.type));
            Foundation::EventDataPtr data_ptr(data);
            event_manager_->SendDelayedEvent(asset_event_category_, Events::ASSET_CANCELED, data_ptr, 0);

            // Clean up
            RemoveFinishedTransfers(error_transfer_data.id, reply->url());
            StartTransferFromQueue();

            AssetModule::LogDebug("HTTP asset " + error_transfer_data.id.toStdString() + " canceled");
            reply->deleteLater();
            return;
        }

        /**** THIS IS A /data REQUEST REPLY ****/
        if (transfer)
        {
            // Create asset pointer
            HttpAssetTransferInfo tranfer_info = transfer->GetTranferInfo();
            std::string id = tranfer_info.id.toStdString();
            std::string type = RexTypes::GetTypeNameFromAssetType(tranfer_info.type);
            Foundation::AssetPtr asset_ptr = Foundation::AssetPtr(new RexAsset(id, type));

            // Fill asset data with reply data
            RexAsset::AssetDataVector& data_vector = checked_static_cast<RexAsset*>(asset_ptr.get())->GetDataInternal();
            QByteArray data_array = reply->readAll();
            for (int index = 0; index < data_array.count(); ++index)
                data_vector.push_back(data_array.at(index));

            // Get metadata if available
            QString url_path = tranfer_info.url.path();
            if (url_path.endsWith("/data") || url_path.endsWith("/data/"))
            {
                // Generate metada url
                int clip_count;
                if (url_path.endsWith("/data"))
                    clip_count = 5;
                else if (url_path.endsWith("/data/"))
                    clip_count = 6;
                else
                {
                    reply->deleteLater();
                    return;
                }

                QUrl metadata_url = tranfer_info.url;
                url_path = url_path.left(url_path.count()-clip_count);
                url_path = url_path + "/metadata";
                metadata_url.setPath(url_path);
                tranfer_info.url = metadata_url;

                QNetworkRequest *metada_request = new QNetworkRequest(metadata_url);

                // Store tranfer data and asset data pointer internally
                QPair<HttpAssetTransferInfo, Foundation::AssetPtr> data_pair;
                data_pair.first = tranfer_info;
                data_pair.second = asset_ptr;
                metadata_to_assetptr_[metada_request->url()] = data_pair;

                // Send metadata network request
                //network_manager_->get(*metada_request);

                // HACK to avoid metadata fetch for now
                fake_metadata_url_ = metada_request->url();
                fake_metadata_fetch_ = true;
            }
            // Asset data feched, lets store
            else
            {
                // Store asset
                boost::shared_ptr<Foundation::AssetServiceInterface> asset_service = framework_->GetServiceManager()->GetService<Foundation::AssetServiceInterface>(Foundation::Service::ST_Asset).lock();
                if (asset_service)
                    asset_service->StoreAsset(asset_ptr);

                // Send asset ready events
                foreach (request_tag_t tag, tranfer_info.tags)
                {
                    Events::AssetReady event_data(asset_ptr.get()->GetId(), asset_ptr.get()->GetType(), asset_ptr, tag);
                    event_manager_->SendEvent(asset_event_category_, Events::ASSET_READY, &event_data);
                }

                RemoveFinishedTransfers(tranfer_info.id, QUrl());
                StartTransferFromQueue();
                AssetModule::LogDebug("HTTP asset " + tranfer_info.id.toStdString() + " completed");
            }
        }

        // Complete /data and /metadata sequence, fake is here as long as we dont have xml parser for metadata
        // or actually we dont use metadata in naali so thats the main reason its not fetched
        if (fake_metadata_fetch_)
        {
            /**** THIS IS A /metadata REQUEST REPLY ****/
            if (metadata_to_assetptr_.contains(fake_metadata_url_))
            {
                // Pull out transfer data and asset pointer assosiated with this reply url
                QUrl metadata_transfer_url = fake_metadata_url_;
                HttpAssetTransferInfo transfer_data = metadata_to_assetptr_[metadata_transfer_url].first;
                Foundation::AssetPtr ready_asset_ptr = metadata_to_assetptr_[metadata_transfer_url].second;
                if (!ready_asset_ptr)
                {
                    reply->deleteLater();
                    return;
                }

                // Fill metadata
                /*
                const QByteArray &inbound_metadata = reply->readAll();
                QString decoded_metadata = QString::fromUtf8(inbound_metadata.data());
                #if defined(__GNUC__)
                RexAssetMetadata *m = dynamic_cast<RexAssetMetadata*>(ready_asset_ptr.get()->GetMetadata());
                #else
                Foundation::AssetMetadataInterface *metadata = ready_asset_ptr.get()->GetMetadata();
                RexAssetMetadata *m = static_cast<RexAssetMetadata*>(metadata);
                #endif
                std::string std_md(decoded_metadata.toStdString());

                m->DesesrializeFromJSON(std_md); // TODO: implement a xml based metadata parser.
                */

                // Store asset
                boost::shared_ptr<Foundation::AssetServiceInterface> asset_service = framework_->GetServiceManager()->GetService<Foundation::AssetServiceInterface>(Foundation::Service::ST_Asset).lock();
                if (asset_service)
                    asset_service->StoreAsset(ready_asset_ptr);

                // Send asset ready events
                foreach (request_tag_t tag, transfer_data.tags)
                {
                    Events::AssetReady event_data(ready_asset_ptr.get()->GetId(), ready_asset_ptr.get()->GetType(), ready_asset_ptr, tag);
                    event_manager_->SendEvent(asset_event_category_, Events::ASSET_READY, &event_data);
                }

                RemoveFinishedTransfers(transfer_data.id, metadata_transfer_url);
                StartTransferFromQueue();
                AssetModule::LogDebug("HTTP asset " + transfer_data.id.toStdString() + " completed with metadata");
            }
        }
        reply->deleteLater();
    }

    void QtHttpAssetProvider::RemoveFinishedTransfers(QString asset_transfer_key, QUrl metadata_transfer_key)
    {
        QtHttpAssetTransfer *remove_transfer = assetid_to_transfer_map_[asset_transfer_key];
        assetid_to_transfer_map_.remove(asset_transfer_key);
        if (metadata_transfer_key.isValid())
            metadata_to_assetptr_.remove(metadata_transfer_key);
        SAFE_DELETE(remove_transfer);
    }

    void QtHttpAssetProvider::ClearAllTransfers()
    {
        foreach (QtHttpAssetTransfer *transfer, assetid_to_transfer_map_.values())
            SAFE_DELETE(transfer);
        assetid_to_transfer_map_.clear();

        foreach (QtHttpAssetTransfer *transfer, pending_request_queue_)
            SAFE_DELETE(transfer);
        pending_request_queue_.clear();
    }

    void QtHttpAssetProvider::StartTransferFromQueue()
    {
        if (pending_request_queue_.count() == 0)
            return;

        // If the whole map is empty then go and start new MAX_HTTP_CONNECTIONS amount of http gets
        if (assetid_to_transfer_map_.count() == 0)
            filling_stack_ = true;

        if (!filling_stack_)
            return;

        if (assetid_to_transfer_map_.count() <= MAX_HTTP_CONNECTIONS && pending_request_queue_.count() > 0)
        {
            if (assetid_to_transfer_map_.count() == MAX_HTTP_CONNECTIONS || pending_request_queue_.count() == 0)
                filling_stack_ = false;
            else
            {
                QtHttpAssetTransfer *new_transfer = pending_request_queue_.takeAt(0);
                assetid_to_transfer_map_[new_transfer->GetTranferInfo().id] = new_transfer;
                network_manager_->get(*new_transfer);

                AssetModule::LogDebug("New HTTP asset request from queue: " + new_transfer->GetTranferInfo().id.toStdString() + " type: " + RexTypes::GetAssetTypeString(new_transfer->GetTranferInfo().type));
                StartTransferFromQueue(); // Recursivly fill the transfer map
            }
        }
    }

    bool QtHttpAssetProvider::CheckRequestQueue(QString assed_id)
    {
        foreach (QtHttpAssetTransfer *transfer, pending_request_queue_)
            if (transfer->GetTranferInfo().id == assed_id)
                return true;
        return false;
    }

    bool QtHttpAssetProvider::IsAcceptableAssetType(const std::string& asset_type)
    {
        using namespace RexTypes;

        bool accepted = false;
        switch (GetAssetTypeFromTypeName(asset_type))
        {
            case RexAT_Texture:
            case RexAT_Mesh:
                accepted = true;
                break;
            default:
                accepted = false;
                break;
        }
        return accepted;
    }
}<|endoftext|>


<commit_before>/*
 * IcarusFitnessCalculator.cpp
 *
 *  Created on: 26/03/2015
 *      Author: Vitor
 */

#include "IcarusFitnessCalculator.h"

double IcarusFitnessCalculator::fitness() {
	gerar_arquivo_top();
	if (system("iverilog top.v genetico.v -o individuo") == -1) {
		std::cerr << "Erro na chamada iverilog.\n";
		exit(1);
	}
	FILE* simulador = popen("vvp individuo", "r");
	if (simulador == nullptr) {
		std::cerr << "Nao consegui executar o simulador vvp.\n";
		std::exit(1);
	}

	auto parsed_output = parse_output(simulador);

	pclose(simulador);

	return fitness_calculator(parsed_output);
}

void IcarusFitnessCalculator::gerar_arquivo_top() {
	std::ofstream top;
	top.open("top.v");

	top << "module top();\n\n";
	top << "\tinteger i;\n";
	top << "\treg [" << num_inputs - 1 << ":0] in;\n";
	top << "\twire [" << num_outputs - 1 << ":0] out;\n\n";
	top << "initial begin\n";
	top << "\t$monitor(\"";
	for (int i = 0; i < num_inputs; i++) {
		top << "%b";
	}
	top << " ";
	for (int i = 0; i < num_outputs; i++) {
		top << "%b";
	}
	top << "\", ";
	for (int i = num_inputs - 1; i >= 0; i--) {
		top << "in[" << i << "], ";
	}
	for (int i = num_outputs - 1; i >= 1; i--) {
		top << "out[" << i << "], ";
	}
	top << "out);\n";
	top << "\tfor (i = 0; i < " << (int) pow(2, num_inputs)
			<< "; i = i + 1) begin\n";
	top << "\t\t#5 in = i;\n";
	top << "\tend\n";
	top << "end\n\n";
	top << "genetico genetico(\n";
	top << "\t.in(in),\n";
	top << "\t.out(out)\n";
	top << ");\n\n";
	top << "endmodule";
}

std::vector<std::vector<std::bitset<8>>>
	IcarusFitnessCalculator::parse_output(FILE* simulador) {
	std::vector<std::vector<std::bitset<8>>> results;
	char entrada[100];
	char saida[100];

	// Ignorando os x's
	fscanf(simulador, "%s", entrada);
	fscanf(simulador, "%s", saida);

	for (int i = 0; i < (int) pow(2, num_inputs); i++) {
		fscanf(simulador, "%s", entrada);
		fscanf(simulador, "%s", saida);
		results.push_back(std::vector<std::bitset<8>>());
		results[i].push_back(std::bitset<8>(saida));
	}
	return results;
}
<commit_msg>Adicionado logic_e.v na linha de compilacao do individuo.<commit_after>/*
 * IcarusFitnessCalculator.cpp
 *
 *  Created on: 26/03/2015
 *      Author: Vitor
 */

#include "IcarusFitnessCalculator.h"

double IcarusFitnessCalculator::fitness() {
	gerar_arquivo_top();
	if (system("iverilog top.v genetico.v logic_e.v -o individuo") == -1) {
		std::cerr << "Erro na chamada iverilog.\n";
		exit(1);
	}
	FILE* simulador = popen("vvp individuo", "r");
	if (simulador == nullptr) {
		std::cerr << "Nao consegui executar o simulador vvp.\n";
		std::exit(1);
	}

	auto parsed_output = parse_output(simulador);

	pclose(simulador);

	return fitness_calculator(parsed_output);
}

void IcarusFitnessCalculator::gerar_arquivo_top() {
	std::ofstream top;
	top.open("top.v");

	top << "module top();\n\n";
	top << "\tinteger i;\n";
	top << "\treg [" << num_inputs - 1 << ":0] in;\n";
	top << "\twire [" << num_outputs - 1 << ":0] out;\n\n";
	top << "initial begin\n";
	top << "\t$monitor(\"";
	for (int i = 0; i < num_inputs; i++) {
		top << "%b";
	}
	top << " ";
	for (int i = 0; i < num_outputs; i++) {
		top << "%b";
	}
	top << "\", ";
	for (int i = num_inputs - 1; i >= 0; i--) {
		top << "in[" << i << "], ";
	}
	for (int i = num_outputs - 1; i >= 1; i--) {
		top << "out[" << i << "], ";
	}
	top << "out);\n";
	top << "\tfor (i = 0; i < " << (int) pow(2, num_inputs)
			<< "; i = i + 1) begin\n";
	top << "\t\t#5 in = i;\n";
	top << "\tend\n";
	top << "end\n\n";
	top << "genetico genetico(\n";
	top << "\t.in(in),\n";
	top << "\t.out(out)\n";
	top << ");\n\n";
	top << "endmodule";
}

std::vector<std::vector<std::bitset<8>>>
	IcarusFitnessCalculator::parse_output(FILE* simulador) {
	std::vector<std::vector<std::bitset<8>>> results;
	char entrada[100];
	char saida[100];

	// Ignorando os x's
	fscanf(simulador, "%s", entrada);
	fscanf(simulador, "%s", saida);

	for (int i = 0; i < (int) pow(2, num_inputs); i++) {
		fscanf(simulador, "%s", entrada);
		fscanf(simulador, "%s", saida);
		results.push_back(std::vector<std::bitset<8>>());
		results[i].push_back(std::bitset<8>(saida));
	}
	return results;
}
<|endoftext|>