<commit_before>/*************************************************************************
 *
 *  $RCSfile: galmisc.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2004-08-31 14:52:03 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SVX_GALMISC_HXX_
#define _SVX_GALMISC_HXX_

#include <sot/storage.hxx>
#include <tools/urlobj.hxx>
#include <svtools/imap.hxx>
#include <svtools/hint.hxx>
#include <svtools/transfer.hxx>
#include "svdio.hxx"
#include "svdobj.hxx"
#include "galobj.hxx"

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_AWT_XPROGRESSMONITOR_HPP
#include <com/sun/star/awt/XProgressMonitor.hpp>
#endif

// -----------
// - Defines -
// -----------

#define IV_IMAPINFO             (UINT32('S')*0x00000001+UINT32('D')*0x00000100+UINT32('U')*0x00010000+UINT32('D')*0x01000000)
#define ID_IMAPINFO             2

#define USERDATA_HDL()          (LINK(this,SgaUserDataFactory,MakeUserData))

#define GAL_RESID( nId )        ResId( nId, GetGalleryResMgr() )
#define STREAMBUF_SIZE          16384L

#define SGA_IMPORT_NONE         0x0000
#define SGA_IMPORT_FILE         0x0001
#define SGA_IMPORT_INET         0x0002

#define GALLERY_PROGRESS_RANGE  10000

#define GALLERY_FG_COLOR        Application::GetSettings().GetStyleSettings().GetWindowTextColor()
#define GALLERY_BG_COLOR        Application::GetSettings().GetStyleSettings().GetWindowColor()
#define GALLERY_DLG_COLOR       Application::GetSettings().GetStyleSettings().GetDialogColor()

// -------------
// - Functions -
// -------------

class ResMgr;
class String;
class SvStream;
class Graphic;
class FmFormModel;
class ImageMap;
class Gallery;

ResMgr*         GetGalleryResMgr();
USHORT          GalleryGraphicImport( const INetURLObject& rURL, Graphic& rGraphic, String& rFilterName, BOOL bShowProgress = FALSE );
BOOL            GallerySvDrawImport( SvStream& rIStm, FmFormModel& rModel );
BOOL            CreateIMapGraphic( const FmFormModel& rModel, Graphic& rGraphic, ImageMap& rImageMap );
String          GetReducedString( const INetURLObject& rURL, ULONG nMaxLen );
String          GetSvDrawStreamNameFromURL( const INetURLObject& rSvDrawObjURL );

BOOL            FileExists( const INetURLObject& rURL );
BOOL            CreateDir(  const INetURLObject& rURL );
BOOL            CopyFile(  const INetURLObject& rSrcURL, const INetURLObject& rDstURL );
BOOL            KillFile( const INetURLObject& rURL );

// ---------------
// - SgaIMapInfo -
// ---------------

class SgaIMapInfo : public SdrObjUserData, public SfxListener
{
    ImageMap                aImageMap;

public:
                            SgaIMapInfo() : SdrObjUserData( IV_IMAPINFO, ID_IMAPINFO, 0 ) {};

                            SgaIMapInfo( const ImageMap& rImageMap) :
                                SdrObjUserData( IV_IMAPINFO, ID_IMAPINFO, 0 ),
                                aImageMap( rImageMap ) {};

    virtual                 ~SgaIMapInfo() {};

    virtual SdrObjUserData* Clone( SdrObject* pObj ) const
                            {
                                SgaIMapInfo* pInfo = new SgaIMapInfo;
                                pInfo->aImageMap = aImageMap;
                                return pInfo;
                            }

    virtual void            ReadData( SvStream& rIStm )
                            {
                                SdrObjUserData::ReadData( rIStm );
                                SdrDownCompat   aIO( rIStm, STREAM_READ, TRUE );
                                UINT16          nVer;
                                rIStm >> nVer;
                                rIStm >> aImageMap;
                            }

    virtual void            WriteData( SvStream& rOStm )
                            {
                                SdrObjUserData::WriteData( rOStm );
                                SdrDownCompat   aIO( rOStm, STREAM_WRITE, TRUE );
                                const UINT16    nVer = 1;
                                rOStm << nVer;
                                rOStm << aImageMap;
                            }

    const ImageMap&         GetImageMap() const { return aImageMap; }
};

// ----------------------
// - SgaUserDataFactory -
// ----------------------

class SgaUserDataFactory
{
public:
        SgaUserDataFactory() { SdrObjFactory::InsertMakeUserDataHdl( USERDATA_HDL() ); }
        ~SgaUserDataFactory() { SdrObjFactory::RemoveMakeUserDataHdl( USERDATA_HDL() ); }

        DECL_LINK( MakeUserData, SdrObjFactory* );
};

// -------------------
// - GalleryProgress -
// -------------------

class GraphicFilter;

class GalleryProgress
{
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XProgressBar > mxProgressBar;
    GraphicFilter*                                                          mpFilter;

                                    DECL_LINK( Update, GraphicFilter * );

    public:

                                    GalleryProgress( GraphicFilter* pFilter = NULL );
                                    ~GalleryProgress();

    void                            Update( ULONG nVal, ULONG nMaxVal );
};

// -----------------------
// - GalleryTransferable -
// -----------------------

class Gallery;
class GalleryTheme;
class GraphicObject;

class GalleryTransferable : public TransferableHelper
{
friend class GalleryTheme;

private:

    GalleryTheme*                   mpTheme;
    SgaObjKind                      meObjectKind;
    sal_uInt32                      mnObjectPos;
    SotStorageStreamRef             mxModelStream;
    GraphicObject*                  mpGraphicObject;
    ImageMap*                       mpImageMap;
    INetURLObject*                  mpURL;
    sal_Bool                        mbInitialized;

protected:

                                    GalleryTransferable( GalleryTheme* pTheme, ULONG nObjectPos );
                                    ~GalleryTransferable();

    void                            InitData();

    // TransferableHelper
    virtual void                    AddSupportedFormats();
    virtual sal_Bool                GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor );
    virtual sal_Bool                WriteObject( SotStorageStreamRef& rxOStm, void* pUserObject, sal_uInt32 nUserObjectId, const ::com::sun::star::datatransfer::DataFlavor& rFlavor );
    virtual void                    DragFinished( sal_Int8 nDropAction );
    virtual void                    ObjectReleased();

    void                            CopyToClipboard( Window* pWindow );
    void                            StartDrag( Window* pWindow, sal_Int8 nDragSourceActions,
                                               sal_Int32 nDragPointer = DND_POINTER_NONE,
                                               sal_Int32 nDragImage = DND_IMAGE_NONE );
};

// ---------------
// - GalleryHint -
// ---------------

#define GALLERY_HINT_NONE               0x00000000
#define GALLERY_HINT_CLOSE_THEME        0x00000001
#define GALLERY_HINT_THEME_REMOVED      0x00000002
#define GALLERY_HINT_THEME_RENAMED      0x00000004
#define GALLERY_HINT_THEME_CREATED      0x00000008
#define GALLERY_HINT_THEME_UPDATEVIEW   0x00000010
#define GALLERY_HINT_CLOSE_OBJECT       0x00000020
#define GALLERY_HINT_OBJECT_REMOVED     0x00000040

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

class GalleryHint : public SfxHint
{
private:

    ULONG           mnType;
    String          maThemeName;
    String          maStringData;
    ULONG           mnData1;
    ULONG           mnData2;

public:

                    GalleryHint( ULONG nType, const String& rThemeName, ULONG nData1 = 0UL, ULONG nData2 = 0UL ) :
                        mnType( nType ), maThemeName( rThemeName ), mnData1( nData1 ), mnData2( nData2 ) {}

                    GalleryHint( ULONG nType, const String& rThemeName, const String& rStringData, ULONG nData1 = 0UL, ULONG nData2 = 0UL ) :
                        mnType( nType ), maThemeName( rThemeName ), maStringData( rStringData ), mnData1( nData1 ), mnData2( nData2 ) {}

    ULONG           GetType() const { return mnType; }
    const String&   GetThemeName() const { return maThemeName; }
    const String&   GetStringData() const { return maStringData; }
    ULONG           GetData1() const { return mnData1; }
    ULONG           GetData2() const { return mnData2; }
};

    #endif
<commit_msg>INTEGRATION: CWS aw019 (1.4.24); FILE MERGED 2004/09/28 15:52:02 aw 1.4.24.1: #i11190#<commit_after>/*************************************************************************
 *
 *  $RCSfile: galmisc.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: pjunck $ $Date: 2004-11-03 10:08:44 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SVX_GALMISC_HXX_
#define _SVX_GALMISC_HXX_

#include <sot/storage.hxx>
#include <tools/urlobj.hxx>
#include <svtools/imap.hxx>
#include <svtools/hint.hxx>
#include <svtools/transfer.hxx>
#include "svdio.hxx"
#include "svdobj.hxx"
#include "galobj.hxx"

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_AWT_XPROGRESSMONITOR_HPP
#include <com/sun/star/awt/XProgressMonitor.hpp>
#endif

// -----------
// - Defines -
// -----------

#define IV_IMAPINFO             (UINT32('S')*0x00000001+UINT32('D')*0x00000100+UINT32('U')*0x00010000+UINT32('D')*0x01000000)
#define ID_IMAPINFO             2

#define USERDATA_HDL()          (LINK(this,SgaUserDataFactory,MakeUserData))

#define GAL_RESID( nId )        ResId( nId, GetGalleryResMgr() )
#define STREAMBUF_SIZE          16384L

#define SGA_IMPORT_NONE         0x0000
#define SGA_IMPORT_FILE         0x0001
#define SGA_IMPORT_INET         0x0002

#define GALLERY_PROGRESS_RANGE  10000

#define GALLERY_FG_COLOR        Application::GetSettings().GetStyleSettings().GetWindowTextColor()
#define GALLERY_BG_COLOR        Application::GetSettings().GetStyleSettings().GetWindowColor()
#define GALLERY_DLG_COLOR       Application::GetSettings().GetStyleSettings().GetDialogColor()

// -------------
// - Functions -
// -------------

class ResMgr;
class String;
class SvStream;
class Graphic;
class FmFormModel;
class ImageMap;
class Gallery;

ResMgr*         GetGalleryResMgr();
USHORT          GalleryGraphicImport( const INetURLObject& rURL, Graphic& rGraphic, String& rFilterName, BOOL bShowProgress = FALSE );
BOOL            GallerySvDrawImport( SvStream& rIStm, FmFormModel& rModel );
BOOL            CreateIMapGraphic( const FmFormModel& rModel, Graphic& rGraphic, ImageMap& rImageMap );
String          GetReducedString( const INetURLObject& rURL, ULONG nMaxLen );
String          GetSvDrawStreamNameFromURL( const INetURLObject& rSvDrawObjURL );

BOOL            FileExists( const INetURLObject& rURL );
BOOL            CreateDir(  const INetURLObject& rURL );
BOOL            CopyFile(  const INetURLObject& rSrcURL, const INetURLObject& rDstURL );
BOOL            KillFile( const INetURLObject& rURL );

// ---------------
// - SgaIMapInfo -
// ---------------

class SgaIMapInfo : public SdrObjUserData, public SfxListener
{
    ImageMap                aImageMap;

public:
                            SgaIMapInfo() : SdrObjUserData( IV_IMAPINFO, ID_IMAPINFO, 0 ) {};

                            SgaIMapInfo( const ImageMap& rImageMap) :
                                SdrObjUserData( IV_IMAPINFO, ID_IMAPINFO, 0 ),
                                aImageMap( rImageMap ) {};

    virtual                 ~SgaIMapInfo() {};

    virtual SdrObjUserData* Clone( SdrObject* pObj ) const
                            {
                                SgaIMapInfo* pInfo = new SgaIMapInfo;
                                pInfo->aImageMap = aImageMap;
                                return pInfo;
                            }

    //BFS01virtual void         ReadData( SvStream& rIStm )
    //BFS01                     {
    //BFS01                         SdrObjUserData::ReadData( rIStm );
    //BFS01                         SdrDownCompat   aIO( rIStm, STREAM_READ, TRUE );
    //BFS01                         UINT16          nVer;
    //BFS01                         rIStm >> nVer;
    //BFS01                         rIStm >> aImageMap;
    //BFS01                     }

    //BFS01virtual void         WriteData( SvStream& rOStm )
    //BFS01                     {
    //BFS01                         SdrObjUserData::WriteData( rOStm );
    //BFS01                         SdrDownCompat   aIO( rOStm, STREAM_WRITE, TRUE );
    //BFS01                         const UINT16    nVer = 1;
    //BFS01                         rOStm << nVer;
    //BFS01                         rOStm << aImageMap;
    //BFS01                     }

    const ImageMap&         GetImageMap() const { return aImageMap; }
};

// ----------------------
// - SgaUserDataFactory -
// ----------------------

class SgaUserDataFactory
{
public:
        SgaUserDataFactory() { SdrObjFactory::InsertMakeUserDataHdl( USERDATA_HDL() ); }
        ~SgaUserDataFactory() { SdrObjFactory::RemoveMakeUserDataHdl( USERDATA_HDL() ); }

        DECL_LINK( MakeUserData, SdrObjFactory* );
};

// -------------------
// - GalleryProgress -
// -------------------

class GraphicFilter;

class GalleryProgress
{
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XProgressBar > mxProgressBar;
    GraphicFilter*                                                          mpFilter;

                                    DECL_LINK( Update, GraphicFilter * );

    public:

                                    GalleryProgress( GraphicFilter* pFilter = NULL );
                                    ~GalleryProgress();

    void                            Update( ULONG nVal, ULONG nMaxVal );
};

// -----------------------
// - GalleryTransferable -
// -----------------------

class Gallery;
class GalleryTheme;
class GraphicObject;

class GalleryTransferable : public TransferableHelper
{
friend class GalleryTheme;

private:

    GalleryTheme*                   mpTheme;
    SgaObjKind                      meObjectKind;
    sal_uInt32                      mnObjectPos;
    SotStorageStreamRef             mxModelStream;
    GraphicObject*                  mpGraphicObject;
    ImageMap*                       mpImageMap;
    INetURLObject*                  mpURL;
    sal_Bool                        mbInitialized;

protected:

                                    GalleryTransferable( GalleryTheme* pTheme, ULONG nObjectPos );
                                    ~GalleryTransferable();

    void                            InitData();

    // TransferableHelper
    virtual void                    AddSupportedFormats();
    virtual sal_Bool                GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor );
    virtual sal_Bool                WriteObject( SotStorageStreamRef& rxOStm, void* pUserObject, sal_uInt32 nUserObjectId, const ::com::sun::star::datatransfer::DataFlavor& rFlavor );
    virtual void                    DragFinished( sal_Int8 nDropAction );
    virtual void                    ObjectReleased();

    void                            CopyToClipboard( Window* pWindow );
    void                            StartDrag( Window* pWindow, sal_Int8 nDragSourceActions,
                                               sal_Int32 nDragPointer = DND_POINTER_NONE,
                                               sal_Int32 nDragImage = DND_IMAGE_NONE );
};

// ---------------
// - GalleryHint -
// ---------------

#define GALLERY_HINT_NONE               0x00000000
#define GALLERY_HINT_CLOSE_THEME        0x00000001
#define GALLERY_HINT_THEME_REMOVED      0x00000002
#define GALLERY_HINT_THEME_RENAMED      0x00000004
#define GALLERY_HINT_THEME_CREATED      0x00000008
#define GALLERY_HINT_THEME_UPDATEVIEW   0x00000010
#define GALLERY_HINT_CLOSE_OBJECT       0x00000020
#define GALLERY_HINT_OBJECT_REMOVED     0x00000040

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

class GalleryHint : public SfxHint
{
private:

    ULONG           mnType;
    String          maThemeName;
    String          maStringData;
    ULONG           mnData1;
    ULONG           mnData2;

public:

                    GalleryHint( ULONG nType, const String& rThemeName, ULONG nData1 = 0UL, ULONG nData2 = 0UL ) :
                        mnType( nType ), maThemeName( rThemeName ), mnData1( nData1 ), mnData2( nData2 ) {}

                    GalleryHint( ULONG nType, const String& rThemeName, const String& rStringData, ULONG nData1 = 0UL, ULONG nData2 = 0UL ) :
                        mnType( nType ), maThemeName( rThemeName ), maStringData( rStringData ), mnData1( nData1 ), mnData2( nData2 ) {}

    ULONG           GetType() const { return mnType; }
    const String&   GetThemeName() const { return maThemeName; }
    const String&   GetStringData() const { return maStringData; }
    ULONG           GetData1() const { return mnData1; }
    ULONG           GetData2() const { return mnData2; }
};

    #endif
<|endoftext|>


<commit_before>#pragma once
/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/

#ifndef _QI_MESSAGING_SESSION_HPP_
#define _QI_MESSAGING_SESSION_HPP_

#include <qi/api.hpp>
#include <qi/messaging/serviceinfo.hpp>
#include <qi/messaging/authproviderfactory.hpp>
#include <qi/messaging/clientauthenticatorfactory.hpp>
#include <qi/future.hpp>
#include <qi/anyobject.hpp>
#include <boost/shared_ptr.hpp>
#include <vector>
#include <string>

#ifdef _MSC_VER
#  pragma warning( push )
#  pragma warning( disable: 4251 )
#endif

namespace qi {

  class SessionPrivate;
  class AuthProvider;
  typedef boost::shared_ptr<AuthProvider> AuthProviderPtr;
  typedef std::map<std::string, AnyValue> CapabilityMap;

  /** A Session allows you to interconnect services on the same machine or over
   * the network.
   *
   * \includename{qi/session.hpp}
   */
  class QI_API Session : boost::noncopyable, public ::boost::enable_shared_from_this<Session> {
  public:
    Session(bool enforceAuthentication = false);
    virtual ~Session();

    enum ServiceLocality {
      ServiceLocality_All    = 0,
      ServiceLocality_Local  = 1,
      ServiceLocality_Remote = 2
    };

    //Client
    qi::FutureSync<void> connect(const char* serviceDirectoryURL);
    qi::FutureSync<void> connect(const std::string &serviceDirectoryURL);
    qi::FutureSync<void> connect(const qi::Url &serviceDirectoryURL);
    bool isConnected() const;
    qi::Url url() const;

    qi::FutureSync< std::vector<ServiceInfo> > services(ServiceLocality locality = ServiceLocality_All);

    qi::FutureSync< qi::AnyObject > service(const std::string &aservice)
    {
      return service(aservice, "");
    }

    qi::FutureSync< qi::AnyObject > service(const std::string &service,
                                            const std::string &protocol);

    //Server
    qi::FutureSync<void> listen(const qi::Url &address);
    std::vector<qi::Url> endpoints() const;
    bool    setIdentity(const std::string& key, const std::string& crt);

    //close both client and server side
    qi::FutureSync<void>    close();

    //this create a listen and create a service directory
    qi::FutureSync<void> listenStandalone(const qi::Url &address);

    qi::FutureSync<unsigned int> registerService(const std::string &name, AnyObject object);
    qi::FutureSync<void>         unregisterService(unsigned int serviceId);

    void setAuthProviderFactory(AuthProviderFactoryPtr);
    void setClientAuthenticatorFactory(ClientAuthenticatorFactoryPtr);

    /** Load a module and register the specified object on the session
     *
     * Tries to call the factory with (this, args...) if possible, otherwise it
     * calls it with (args...) only.
     */
    void loadService(const std::string& moduleName, const std::string &renameModule = "",
        const AnyReferenceVector& args = AnyReferenceVector());

    /** Load a module and call the specified function asynchronously
     *
     * Tries to call the function with (this, args...) if possible, otherwise it
     * calls it with (args...) only.
     */
    template <typename T>
    qi::Future<T> callModule(const std::string& moduleName, const AnyReferenceVector& args = AnyReferenceVector())
    {
      qi::Promise<T> promise(qi::PromiseNoop<T>);
      qi::Future<qi::AnyValue> future = _callModule(moduleName, args, qi::MetaCallType_Queued);
      qi::detail::futureAdapterVal(future, promise);
      return promise.future();
    }

#define pushi(z, n, _) params.push_back(p ## n);
#define genCall(n, ATYPEDECL, ATYPES, ADECL, AUSE, comma)             \
  void loadService(                                                   \
      const std::string& moduleName, const std::string& renameModule, \
      qi::AutoAnyReference pp0 comma                                  \
      QI_GEN_ARGSDECLSAMETYPE(n, qi::AutoAnyReference))               \
  {                                                                   \
    std::vector<qi::AnyReference> params;                             \
    params.reserve(n+1);                                              \
    params.push_back(pp0);                                            \
    BOOST_PP_REPEAT(n, pushi, _)                                      \
    loadService(moduleName, renameModule, params);                    \
  }                                                                   \
  template <typename T>                                               \
  qi::Future<T> callModule(                                           \
      const std::string& moduleName,                                  \
      qi::AutoAnyReference pp0 comma                                  \
      QI_GEN_ARGSDECLSAMETYPE(n, qi::AutoAnyReference))               \
  {                                                                   \
    std::vector<qi::AnyReference> params;                             \
    params.reserve(n+1);                                              \
    params.push_back(pp0);                                            \
    BOOST_PP_REPEAT(n, pushi, _)                                      \
    return callModule<T>(moduleName, params);                         \
  }
QI_GEN(genCall)
#undef genCall
#undef pushi

    /** Waits for a service to become available. The future is set immediately
     * if the service is already available.
     */
    qi::FutureSync<void> waitForService(const std::string& service);

  public:
    qi::Signal<unsigned int, std::string> serviceRegistered;
    qi::Signal<unsigned int, std::string> serviceUnregistered;
    // C4251
    qi::Signal<>                          connected;
    // C4251
    qi::Signal<std::string>               disconnected;

  protected:
    friend class SessionPrivate;
    boost::shared_ptr<SessionPrivate>    _p;

  private:
    qi::Future<AnyValue> _callModule(const std::string& moduleName,
        const AnyReferenceVector& args,
        qi::MetaCallType metacallType);
  };

  typedef boost::shared_ptr<Session> SessionPtr;

  inline SessionPtr makeSession() { return boost::make_shared<qi::Session>(); }
}

QI_TYPE_ENUM(qi::Session::ServiceLocality);

#ifdef _MSC_VER
#  pragma warning( pop )
#endif

#endif  // _QIMESSAGING_SESSION_HPP_
<commit_msg>Session.callModule: return a FutureSync<commit_after>#pragma once
/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/

#ifndef _QI_MESSAGING_SESSION_HPP_
#define _QI_MESSAGING_SESSION_HPP_

#include <qi/api.hpp>
#include <qi/messaging/serviceinfo.hpp>
#include <qi/messaging/authproviderfactory.hpp>
#include <qi/messaging/clientauthenticatorfactory.hpp>
#include <qi/future.hpp>
#include <qi/anyobject.hpp>
#include <boost/shared_ptr.hpp>
#include <vector>
#include <string>

#ifdef _MSC_VER
#  pragma warning( push )
#  pragma warning( disable: 4251 )
#endif

namespace qi {

  class SessionPrivate;
  class AuthProvider;
  typedef boost::shared_ptr<AuthProvider> AuthProviderPtr;
  typedef std::map<std::string, AnyValue> CapabilityMap;

  /** A Session allows you to interconnect services on the same machine or over
   * the network.
   *
   * \includename{qi/session.hpp}
   */
  class QI_API Session : boost::noncopyable, public ::boost::enable_shared_from_this<Session> {
  public:
    Session(bool enforceAuthentication = false);
    virtual ~Session();

    enum ServiceLocality {
      ServiceLocality_All    = 0,
      ServiceLocality_Local  = 1,
      ServiceLocality_Remote = 2
    };

    //Client
    qi::FutureSync<void> connect(const char* serviceDirectoryURL);
    qi::FutureSync<void> connect(const std::string &serviceDirectoryURL);
    qi::FutureSync<void> connect(const qi::Url &serviceDirectoryURL);
    bool isConnected() const;
    qi::Url url() const;

    qi::FutureSync< std::vector<ServiceInfo> > services(ServiceLocality locality = ServiceLocality_All);

    qi::FutureSync< qi::AnyObject > service(const std::string &aservice)
    {
      return service(aservice, "");
    }

    qi::FutureSync< qi::AnyObject > service(const std::string &service,
                                            const std::string &protocol);

    //Server
    qi::FutureSync<void> listen(const qi::Url &address);
    std::vector<qi::Url> endpoints() const;
    bool    setIdentity(const std::string& key, const std::string& crt);

    //close both client and server side
    qi::FutureSync<void>    close();

    //this create a listen and create a service directory
    qi::FutureSync<void> listenStandalone(const qi::Url &address);

    qi::FutureSync<unsigned int> registerService(const std::string &name, AnyObject object);
    qi::FutureSync<void>         unregisterService(unsigned int serviceId);

    void setAuthProviderFactory(AuthProviderFactoryPtr);
    void setClientAuthenticatorFactory(ClientAuthenticatorFactoryPtr);

    /** Load a module and register the specified object on the session
     *
     * Tries to call the factory with (this, args...) if possible, otherwise it
     * calls it with (args...) only.
     */
    void loadService(const std::string& moduleName, const std::string &renameModule = "",
        const AnyReferenceVector& args = AnyReferenceVector());

    /** Load a module and call the specified function asynchronously
     *
     * Tries to call the function with (this, args...) if possible, otherwise it
     * calls it with (args...) only.
     */
    template <typename T>
    qi::FutureSync<T> callModule(const std::string& moduleName, const AnyReferenceVector& args = AnyReferenceVector())
    {
      qi::Promise<T> promise(qi::PromiseNoop<T>);
      qi::Future<qi::AnyValue> future = _callModule(moduleName, args, qi::MetaCallType_Queued);
      qi::detail::futureAdapterVal(future, promise);
      return promise.future();
    }

#define pushi(z, n, _) params.push_back(p ## n);
#define genCall(n, ATYPEDECL, ATYPES, ADECL, AUSE, comma)             \
  void loadService(                                                   \
      const std::string& moduleName, const std::string& renameModule, \
      qi::AutoAnyReference pp0 comma                                  \
      QI_GEN_ARGSDECLSAMETYPE(n, qi::AutoAnyReference))               \
  {                                                                   \
    std::vector<qi::AnyReference> params;                             \
    params.reserve(n+1);                                              \
    params.push_back(pp0);                                            \
    BOOST_PP_REPEAT(n, pushi, _)                                      \
    loadService(moduleName, renameModule, params);                    \
  }                                                                   \
  template <typename T>                                               \
  qi::FutureSync<T> callModule(                                       \
      const std::string& moduleName,                                  \
      qi::AutoAnyReference pp0 comma                                  \
      QI_GEN_ARGSDECLSAMETYPE(n, qi::AutoAnyReference))               \
  {                                                                   \
    std::vector<qi::AnyReference> params;                             \
    params.reserve(n+1);                                              \
    params.push_back(pp0);                                            \
    BOOST_PP_REPEAT(n, pushi, _)                                      \
    return callModule<T>(moduleName, params);                         \
  }
QI_GEN(genCall)
#undef genCall
#undef pushi

    /** Waits for a service to become available. The future is set immediately
     * if the service is already available.
     */
    qi::FutureSync<void> waitForService(const std::string& service);

  public:
    qi::Signal<unsigned int, std::string> serviceRegistered;
    qi::Signal<unsigned int, std::string> serviceUnregistered;
    // C4251
    qi::Signal<>                          connected;
    // C4251
    qi::Signal<std::string>               disconnected;

  protected:
    friend class SessionPrivate;
    boost::shared_ptr<SessionPrivate>    _p;

  private:
    qi::Future<AnyValue> _callModule(const std::string& moduleName,
        const AnyReferenceVector& args,
        qi::MetaCallType metacallType);
  };

  typedef boost::shared_ptr<Session> SessionPtr;

  inline SessionPtr makeSession() { return boost::make_shared<qi::Session>(); }
}

QI_TYPE_ENUM(qi::Session::ServiceLocality);

#ifdef _MSC_VER
#  pragma warning( pop )
#endif

#endif  // _QIMESSAGING_SESSION_HPP_
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <bitset>
using namespace std;

class Crypto {

protected:
	int value;
	string ClearText;
	string CypherText;
	const string Pad = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
	const string HexPad = "0123456789ABCDEF";
	vector<bool> Bin;

public:
	Crypto() :value(0) {};
	Crypto(const string s) :ClearText(s) {};

	// Print the clear text on screen
	void GetClearText(void) {
		cout << ClearText << endl;
	}

	// Returns an array with the indexes of the pad
	void Str2Bin() {
		this -> Bin.resize(ClearText.length() * 8, 0);
		int c = 0;
		vector<bool>::reverse_iterator v = Bin.rbegin();
		for (string::reverse_iterator it = ClearText.rbegin(); it < ClearText.rend();++it) {
			int n = *it;
			while (n != 0) { *(++v) = (n % 2 == 0 ? 0 : 1); n /= 2;	++c; }
			if (c%8 != 0) {v += (c%8)-1;}
		}
	}

	// Convert from binary to base64
	void Bin2Base64() {

	}
};

int main() {
  Crypto PWD("c");
  PWD.GetClearText();
  PWD.Str2Bin();
  return 0;
}
<commit_msg>Delete challenge_1_1.cpp<commit_after><|endoftext|>


<commit_before>/* bzflag
* Copyright (c) 1993 - 2008 Tim Riker
*
* This package is free software;  you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/

#include "plugin_HTTPVDIR.h"
#include "plugin_utils.h"
#include "plugin_groups.h"
#include <algorithm>

BZFSHTTPVDir::BZFSHTTPVDir()
{
  bz_loadPlugin("HTTPServer",NULL);
}

void BZFSHTTPVDir::registerVDir ( void )
{
  bz_callCallback("RegisterHTTPDVDir",this);
}

BZFSHTTPVDir::~BZFSHTTPVDir()
{
  bz_callCallback("RemoveHTTPDVDir",this);
}
std::string BZFSHTTPVDir::getBaseURL ( void )
{
  std::string URL = "http://";
  std::string host = "localhost";
  if (bz_getPublicAddr().size())
    host = bz_getPublicAddr().c_str();

  // make sure it has the port
  if ( strrchr(host.c_str(),':') == NULL )
    host += format(":%d",bz_getPublicPort());

  URL += host +"/";
  URL += getVDir();
  URL += "/";

  return URL;
}

bool HTTPRequest::getParam ( const char* param, std::string &val ) const
{
  val = "";
  if (!param)
    return false;

  std::map<std::string, std::string>::const_iterator itr = paramaters.find(tolower(std::string(param)));
  if ( itr != paramaters.end() )
  {
    val = itr->second;
    return true;
  }
  return false;
}

bool HTTPRequest::getParam ( const std::string &param, std::string &val ) const
{
  val = "";

  std::map<std::string, std::string>::const_iterator itr = paramaters.find(tolower(param));
  if ( itr != paramaters.end() )
  {
    val = itr->second;
    return true;
  }
  return false;
}

class PendingTokenTask : public bz_BaseURLHandler
{
public:
  PendingTokenTask():requestID(-1){};

  virtual void done ( const char* /*URL*/, void * data, unsigned int size, bool complete );
  virtual void timeout ( const char* /*URL*/, int /*errorCode*/ );
  virtual void error ( const char* /*URL*/, int /*errorCode*/, const char * /*errorString*/ );

  int requestID;
  std::string URL;
  std::vector<std::string> groups;

  std::string data;
};

std::map<int,PendingTokenTask*> pendingTokenTasks;

void PendingTokenTask::done ( const char* /*URL*/, void * inData, unsigned int size, bool complete )
{
  char *t = (char*)malloc(size+1);
  memcpy(t,inData,size);
  t[size] = 0;
  data += t;
  free(t);

  if (complete)
  {
    // parse out the info

    data = replace_all(data,std::string("\r\n"),"\n");
    data = replace_all(data,std::string("\r"),"\n");

    std::vector<std::string> lines = tokenize(data,std::string("\n"),0,false);

    groups.clear();

    for (size_t i = 0; i < lines.size(); i++)
    {
      std::string &line = lines[i];

      if (line.size())
      {
	if (strstr(line.c_str(),"TOKGOOD") != NULL)
	{
	  groups = tokenize(line,std::string(":"),0,false);

	  if(groups.size() > 1)	// yank the first 2 since that is the sign and the name
	    groups.erase(groups.begin(),groups.begin()+1);
	}
      }
    }
    pendingTokenTasks[requestID] = this;
  }
}

void PendingTokenTask::timeout ( const char* /*URL*/, int /*errorCode*/ )
{
  groups.clear();
  pendingTokenTasks[requestID] = this;
}

void PendingTokenTask::error ( const char* /*URL*/, int /*errorCode*/, const char * /*errorString*/ )
{
  groups.clear();
  pendingTokenTasks[requestID] = this;
}

BZFSHTTPVDirAuth::BZFSHTTPVDirAuth():BZFSHTTPVDir(),sessionTimeout(300)
{
}

void BZFSHTTPVDirAuth::setupAuth ( void )
{
  authPage = "
Please Login
";

  std::string returnURL;
  if (getBaseURL().size())
    returnURL += format("http://localhost:%d/%s/",bz_getPublicPort(),getVDir());
  else
    returnURL += getBaseURL();
  returnURL += "?action=login&token=%TOKEN%&user=%USERNAME%";

  tsCallback.URL = "http://my.bzflag.org/weblogin.php?action=weblogin&url=";
  tsCallback.URL += url_encode(returnURL);

  templateSystem.addKey("WebAuthURL",&tsCallback);
}

void BZFSHTTPVDirAuth::TSURLCallback::keyCallback(std::string &data, const std::string &key)
{
  if(compare_nocase(key,"WebAuthURL") == 0)
    data += URL;
}

bool BZFSHTTPVDirAuth::verifyToken ( const HTTPRequest &request, HTTPReply &reply )
{
  // build up the groups list
  std::string token,user;
  request.getParam("token",token);
  request.getParam("user",user);

  std::vector<std::string> groups;

  std::map<int, std::vector<std::string> >::iterator itr = authLevels.begin();

  while (itr != authLevels.end())
  {
    for (size_t i = 0; i < itr->second.size();i++)
    {
      std::string &perm = itr->second[i];

      std::vector<std::string> groupsWithPerm;

      if (compare_nocase(perm,"ADMIN")==0)
	groupsWithPerm = findGroupsWithAdmin();
      else
	groupsWithPerm = findGroupsWithPerm(perm);

      groups.insert(groups.end(),groupsWithPerm.begin(),groupsWithPerm.end());
    }
    itr++;
  }

  PendingTokenTask *task = new PendingTokenTask;

  if (!user.size() || !token.size())
  {
    reply.body += "Invalid response";
    reply.docType = HTTPReply::eText;
    return true;
  }
  task->requestID = request.requestID;
  task->URL = "http://my.bzflag.org/db/";
  task->URL += "?action=CHECKTOKENS&checktokens=" + url_encode(user) + "@";
  task->URL += request.ip;
  task->URL += "%3D" + token;

  task->URL += "&groups=";
  for (size_t g = 0; g < groups.size(); g++)
  {
    task->URL += groups[g];
    if ( g+1 < groups.size())
      task->URL += "%0D%0A";
  }

  // give the task to bzfs and let it do it, when it's done it'll be processed
  bz_addURLJob(task->URL.c_str(),task);

  return false;
}

bool BZFSHTTPVDirAuth::handleRequest ( const HTTPRequest &request, HTTPReply &reply )
{
  flushTasks();
  int sessionID = request.sessionID;
  reply.docType = HTTPReply::eHTML;

  std::map<int,AuthInfo>::iterator authItr = authedSessions.find(sessionID);
  if ( authItr != authedSessions.end() )  // it is one of our authorized users, be nice and forward the request to our child
  {
    // put this back to the default
    reply.docType = HTTPReply::eText;

    authItr->second.time = bz_getCurrentTime();
    bool complete = handleAuthedRequest(authItr->second.level,request,reply);

    if (!complete)
      defferedAuthedRequests.push_back(request.requestID);

    return complete;
  }
  else	// they are not fully authorized yet
  {
    std::map<int,PendingTokenTask*>::iterator pendingItr = pendingTokenTasks.find(request.requestID);
    if (pendingItr != pendingTokenTasks.end())	// they have a token, check it
    {
      AuthInfo info;
      info.time = bz_getCurrentTime();
      info.level = getLevelFromGroups(pendingItr->second->groups);
      if (info.level >= 0)
	authedSessions[request.sessionID] = info;

      delete(pendingItr->second);
      pendingTokenTasks.erase(pendingItr);
    }
    else
    {
      std::string action,user,token;
      request.getParam("action",action);
      request.getParam("user",user);
      request.getParam("token",token);
      if (compare_nocase(action,"login") == 0 && user.size() && token.size()) // it's a response from weblogin
	return verifyToken(request,reply);
      else
      {
	// it's someone we know NOTHING about, send them the login
	templateSystem.startTimer();
	size_t s = authPage.find_last_of('.');
	if (s != std::string::npos)
	{
	  if (compare_nocase(authPage.c_str()+s,".tmpl") == 0)
	  {
	    if(!templateSystem.processTemplateFile(reply.body,authPage.c_str()))
	      templateSystem.processTemplate(reply.body,authPage);
	  }
	  else
	    templateSystem.processTemplate(reply.body,authPage);
	}
	else
	  templateSystem.processTemplate(reply.body,authPage);
      }
    }
  }

  return true;
}

bool BZFSHTTPVDirAuth::resumeTask (  int requestID )
{
  // it's token job that is done, go for it
  if(pendingTokenTasks.find(requestID) != pendingTokenTasks.end())
    return true;

  // our child differed
  std::vector<int>::iterator itr = std::find(defferedAuthedRequests.begin(),defferedAuthedRequests.end(),requestID);
  if (itr != defferedAuthedRequests.end())
  {
    if(resumeAuthedTask(requestID)) // they are done, move on
    {
      defferedAuthedRequests.erase(itr);
      return true;
    }
  }
  return false;
}

bool stringInList ( const std::string &str, const std::vector<std::string> stringList )
{
  for (std::vector<std::string>::const_iterator itr = stringList.begin(); itr != stringList.end(); itr++)
  {
    if (compare_nocase(str,*itr) == 0)
      return true;
  }
  return false;
}

void BZFSHTTPVDirAuth::addPermToLevel ( int level, const std::string &perm )
{
  if (level < 0)
    return;

   if(authLevels.find(level)== authLevels.end())
   {
     std::vector<std::string> t;
     authLevels[level] = t;
   }
   authLevels[level].push_back(perm);
}

int BZFSHTTPVDirAuth::getLevelFromGroups (const std::vector<std::string> &groups )
{
  std::map<int,std::vector<std::string> >::reverse_iterator itr = authLevels.rbegin();

  while (itr != authLevels.rend())
  {
    for (size_t s = 0; s < itr->second.size(); s++ )
    {
      std::string &perm = itr->second[s];

      std::vector<std::string> groupsWithPerm;

      if (compare_nocase(perm,"ADMIN")==0)
	groupsWithPerm = findGroupsWithAdmin();
      else
	groupsWithPerm = findGroupsWithPerm(perm);

      // check the input groups, and see if any of the them are in the groups with this perm
      for (std::vector<std::string>::const_iterator group = groups.begin(); group != groups.end(); group++)
      {
	if (stringInList(*group,groupsWithPerm))
	  return itr->first;
      }
    }
    itr++;
  }
  return -1;
}

void BZFSHTTPVDirAuth::flushTasks ( void )
{
  std::map<int,AuthInfo>::iterator authItr = authedSessions.begin();

  double now = bz_getCurrentTime();
  while (authedSessions.size() && authItr != authedSessions.end())
  {
    if (sessionTimeout + authItr->second.time < now)
    {
      std::map<int,AuthInfo>::iterator t = authItr;
      t++;
      authedSessions.erase(authItr);
      authItr = t;
    }
  }
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>call the derived class after we auth to get the actual content.<commit_after>/* bzflag
* Copyright (c) 1993 - 2008 Tim Riker
*
* This package is free software;  you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/

#include "plugin_HTTPVDIR.h"
#include "plugin_utils.h"
#include "plugin_groups.h"
#include <algorithm>

BZFSHTTPVDir::BZFSHTTPVDir()
{
  bz_loadPlugin("HTTPServer",NULL);
}

void BZFSHTTPVDir::registerVDir ( void )
{
  bz_callCallback("RegisterHTTPDVDir",this);
}

BZFSHTTPVDir::~BZFSHTTPVDir()
{
  bz_callCallback("RemoveHTTPDVDir",this);
}
std::string BZFSHTTPVDir::getBaseURL ( void )
{
  std::string URL = "http://";
  std::string host = "localhost";
  if (bz_getPublicAddr().size())
    host = bz_getPublicAddr().c_str();

  // make sure it has the port
  if ( strrchr(host.c_str(),':') == NULL )
    host += format(":%d",bz_getPublicPort());

  URL += host +"/";
  URL += getVDir();
  URL += "/";

  return URL;
}

bool HTTPRequest::getParam ( const char* param, std::string &val ) const
{
  val = "";
  if (!param)
    return false;

  std::map<std::string, std::string>::const_iterator itr = paramaters.find(tolower(std::string(param)));
  if ( itr != paramaters.end() )
  {
    val = itr->second;
    return true;
  }
  return false;
}

bool HTTPRequest::getParam ( const std::string &param, std::string &val ) const
{
  val = "";

  std::map<std::string, std::string>::const_iterator itr = paramaters.find(tolower(param));
  if ( itr != paramaters.end() )
  {
    val = itr->second;
    return true;
  }
  return false;
}

class PendingTokenTask : public bz_BaseURLHandler
{
public:
  PendingTokenTask():requestID(-1){};

  virtual void done ( const char* /*URL*/, void * data, unsigned int size, bool complete );
  virtual void timeout ( const char* /*URL*/, int /*errorCode*/ );
  virtual void error ( const char* /*URL*/, int /*errorCode*/, const char * /*errorString*/ );

  int requestID;
  std::string URL;
  std::vector<std::string> groups;

  std::string data;
};

std::map<int,PendingTokenTask*> pendingTokenTasks;

void PendingTokenTask::done ( const char* /*URL*/, void * inData, unsigned int size, bool complete )
{
  char *t = (char*)malloc(size+1);
  memcpy(t,inData,size);
  t[size] = 0;
  data += t;
  free(t);

  if (complete)
  {
    // parse out the info

    data = replace_all(data,std::string("\r\n"),"\n");
    data = replace_all(data,std::string("\r"),"\n");

    std::vector<std::string> lines = tokenize(data,std::string("\n"),0,false);

    groups.clear();

    for (size_t i = 0; i < lines.size(); i++)
    {
      std::string &line = lines[i];

      if (line.size())
      {
	if (strstr(line.c_str(),"TOKGOOD") != NULL)
	{
	  groups = tokenize(line,std::string(":"),0,false);

	  if(groups.size() > 1)	// yank the first 2 since that is the sign and the name
	    groups.erase(groups.begin(),groups.begin()+1);
	}
      }
    }
    pendingTokenTasks[requestID] = this;
  }
}

void PendingTokenTask::timeout ( const char* /*URL*/, int /*errorCode*/ )
{
  groups.clear();
  pendingTokenTasks[requestID] = this;
}

void PendingTokenTask::error ( const char* /*URL*/, int /*errorCode*/, const char * /*errorString*/ )
{
  groups.clear();
  pendingTokenTasks[requestID] = this;
}

BZFSHTTPVDirAuth::BZFSHTTPVDirAuth():BZFSHTTPVDir(),sessionTimeout(300)
{
}

void BZFSHTTPVDirAuth::setupAuth ( void )
{
  authPage = "
Please Login
";

  std::string returnURL;
  if (getBaseURL().size())
    returnURL += format("http://localhost:%d/%s/",bz_getPublicPort(),getVDir());
  else
    returnURL += getBaseURL();
  returnURL += "?action=login&token=%TOKEN%&user=%USERNAME%";

  tsCallback.URL = "http://my.bzflag.org/weblogin.php?action=weblogin&url=";
  tsCallback.URL += url_encode(returnURL);

  templateSystem.addKey("WebAuthURL",&tsCallback);
}

void BZFSHTTPVDirAuth::TSURLCallback::keyCallback(std::string &data, const std::string &key)
{
  if(compare_nocase(key,"WebAuthURL") == 0)
    data += URL;
}

bool BZFSHTTPVDirAuth::verifyToken ( const HTTPRequest &request, HTTPReply &reply )
{
  // build up the groups list
  std::string token,user;
  request.getParam("token",token);
  request.getParam("user",user);

  std::vector<std::string> groups;

  std::map<int, std::vector<std::string> >::iterator itr = authLevels.begin();

  while (itr != authLevels.end())
  {
    for (size_t i = 0; i < itr->second.size();i++)
    {
      std::string &perm = itr->second[i];

      std::vector<std::string> groupsWithPerm;

      if (compare_nocase(perm,"ADMIN")==0)
	groupsWithPerm = findGroupsWithAdmin();
      else
	groupsWithPerm = findGroupsWithPerm(perm);

      groups.insert(groups.end(),groupsWithPerm.begin(),groupsWithPerm.end());
    }
    itr++;
  }

  PendingTokenTask *task = new PendingTokenTask;

  if (!user.size() || !token.size())
  {
    reply.body += "Invalid response";
    reply.docType = HTTPReply::eText;
    return true;
  }
  task->requestID = request.requestID;
  task->URL = "http://my.bzflag.org/db/";
  task->URL += "?action=CHECKTOKENS&checktokens=" + url_encode(user) + "@";
  task->URL += request.ip;
  task->URL += "%3D" + token;

  task->URL += "&groups=";
  for (size_t g = 0; g < groups.size(); g++)
  {
    task->URL += groups[g];
    if ( g+1 < groups.size())
      task->URL += "%0D%0A";
  }

  // give the task to bzfs and let it do it, when it's done it'll be processed
  bz_addURLJob(task->URL.c_str(),task);

  return false;
}

bool BZFSHTTPVDirAuth::handleRequest ( const HTTPRequest &request, HTTPReply &reply )
{
  flushTasks();
  int sessionID = request.sessionID;
  reply.docType = HTTPReply::eHTML;

  std::map<int,AuthInfo>::iterator authItr = authedSessions.find(sessionID);
  if ( authItr != authedSessions.end() )  // it is one of our authorized users, be nice and forward the request to our child
  {
    // put this back to the default
    reply.docType = HTTPReply::eText;

    authItr->second.time = bz_getCurrentTime();
    bool complete = handleAuthedRequest(authItr->second.level,request,reply);

    if (!complete)
      defferedAuthedRequests.push_back(request.requestID);

    return complete;
  }
  else	// they are not fully authorized yet
  {
    std::map<int,PendingTokenTask*>::iterator pendingItr = pendingTokenTasks.find(request.requestID);
    if (pendingItr != pendingTokenTasks.end())	// they have a token, check it
    {
      AuthInfo info;
      info.time = bz_getCurrentTime();
      info.level = getLevelFromGroups(pendingItr->second->groups);
      if (info.level >= 0)
	authedSessions[request.sessionID] = info;

      delete(pendingItr->second);
      pendingTokenTasks.erase(pendingItr);

      // put this back to the default
      reply.docType = HTTPReply::eText;

      bool complete = handleAuthedRequest(info.level,request,reply);

      if (!complete)
	defferedAuthedRequests.push_back(request.requestID);

      return complete;
    }
    else
    {
      std::string action,user,token;
      request.getParam("action",action);
      request.getParam("user",user);
      request.getParam("token",token);
      if (compare_nocase(action,"login") == 0 && user.size() && token.size()) // it's a response from weblogin
	return verifyToken(request,reply);
      else
      {
	// it's someone we know NOTHING about, send them the login
	templateSystem.startTimer();
	size_t s = authPage.find_last_of('.');
	if (s != std::string::npos)
	{
	  if (compare_nocase(authPage.c_str()+s,".tmpl") == 0)
	  {
	    if(!templateSystem.processTemplateFile(reply.body,authPage.c_str()))
	      templateSystem.processTemplate(reply.body,authPage);
	  }
	  else
	    templateSystem.processTemplate(reply.body,authPage);
	}
	else
	  templateSystem.processTemplate(reply.body,authPage);
      }
    }
  }

  return true;
}

bool BZFSHTTPVDirAuth::resumeTask (  int requestID )
{
  // it's token job that is done, go for it
  if(pendingTokenTasks.find(requestID) != pendingTokenTasks.end())
    return true;

  // our child differed
  std::vector<int>::iterator itr = std::find(defferedAuthedRequests.begin(),defferedAuthedRequests.end(),requestID);
  if (itr != defferedAuthedRequests.end())
  {
    if(resumeAuthedTask(requestID)) // they are done, move on
    {
      defferedAuthedRequests.erase(itr);
      return true;
    }
  }
  return false;
}

bool stringInList ( const std::string &str, const std::vector<std::string> stringList )
{
  for (std::vector<std::string>::const_iterator itr = stringList.begin(); itr != stringList.end(); itr++)
  {
    if (compare_nocase(str,*itr) == 0)
      return true;
  }
  return false;
}

void BZFSHTTPVDirAuth::addPermToLevel ( int level, const std::string &perm )
{
  if (level < 0)
    return;

   if(authLevels.find(level)== authLevels.end())
   {
     std::vector<std::string> t;
     authLevels[level] = t;
   }
   authLevels[level].push_back(perm);
}

int BZFSHTTPVDirAuth::getLevelFromGroups (const std::vector<std::string> &groups )
{
  std::map<int,std::vector<std::string> >::reverse_iterator itr = authLevels.rbegin();

  while (itr != authLevels.rend())
  {
    for (size_t s = 0; s < itr->second.size(); s++ )
    {
      std::string &perm = itr->second[s];

      std::vector<std::string> groupsWithPerm;

      if (compare_nocase(perm,"ADMIN")==0)
	groupsWithPerm = findGroupsWithAdmin();
      else
	groupsWithPerm = findGroupsWithPerm(perm);

      // check the input groups, and see if any of the them are in the groups with this perm
      for (std::vector<std::string>::const_iterator group = groups.begin(); group != groups.end(); group++)
      {
	if (stringInList(*group,groupsWithPerm))
	  return itr->first;
      }
    }
    itr++;
  }
  return -1;
}

void BZFSHTTPVDirAuth::flushTasks ( void )
{
  std::map<int,AuthInfo>::iterator authItr = authedSessions.begin();

  double now = bz_getCurrentTime();
  while (authedSessions.size() && authItr != authedSessions.end())
  {
    if (sessionTimeout + authItr->second.time < now)
    {
      std::map<int,AuthInfo>::iterator t = authItr;
      t++;
      authedSessions.erase(authItr);
      authItr = t;
    }
  }
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: OLEHandler.cxx,v $
 * $Revision: 1.2 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#include <OLEHandler.hxx>
#include <PropertyMap.hxx>
#include <doctok/resourceids.hxx>
#include <ooxml/resourceids.hxx>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/document/XEmbeddedObjectResolver.hpp>
#include <com/sun/star/document/XStorageBasedDocument.hpp>
#include <com/sun/star/embed/XEmbeddedObject.hpp>
#include <com/sun/star/embed/XEmbedObjectCreator.hpp>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/text/XTextDocument.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>

namespace writerfilter {
namespace dmapper {

using namespace ::com::sun::star;
/*-- 23.04.2008 10:46:14---------------------------------------------------

  -----------------------------------------------------------------------*/
OLEHandler::OLEHandler()
{
}
/*-- 23.04.2008 10:46:14---------------------------------------------------

  -----------------------------------------------------------------------*/
OLEHandler::~OLEHandler()
{
}
/*-- 23.04.2008 10:46:14---------------------------------------------------

  -----------------------------------------------------------------------*/
void OLEHandler::attribute(Id rName, Value & rVal)
{
    rtl::OUString sStringValue = rVal.getString();
    (void)rName;
    /* WRITERFILTERSTATUS: table: OLEHandler_attributedata */
    switch( rName )
    {
        /* WRITERFILTERSTATUS: done: 1, planned: 0, spent: 0 */
        case NS_ooxml::LN_CT_OLEObject_Type:
            m_sObjectType = sStringValue;
        break;
        case NS_ooxml::LN_CT_OLEObject_ProgID:
            m_sProgId = sStringValue;
        break;
        case NS_ooxml::LN_CT_OLEObject_ShapeID:
            m_sShapeId = sStringValue;
        break;
        case NS_ooxml::LN_CT_OLEObject_DrawAspect:
            m_sDrawAspect = sStringValue;
        break;
        case NS_ooxml::LN_CT_OLEObject_ObjectID:
            m_sObjectId = sStringValue;
        break;
        case NS_ooxml::LN_CT_OLEObject_r_id:
            m_sr_id = sStringValue;
        break;
        case NS_ooxml::LN_inputstream:
            rVal.getAny() >>= m_xInputStream;
        break;
        default:
            OSL_ENSURE( false, "unknown attribute");
    }
}
/*-- 23.04.2008 10:46:14---------------------------------------------------

  -----------------------------------------------------------------------*/
void OLEHandler::sprm(Sprm & rSprm)
{
    (void)rSprm;
}
/*-- 23.04.2008 11:15:19---------------------------------------------------

  -----------------------------------------------------------------------*/
::rtl::OUString OLEHandler::copyOLEOStream( uno::Reference< text::XTextDocument > xTextDocument )
{
    ::rtl::OUString sRet;
    if( !m_xInputStream.is() )
        return sRet;
    try{
        uno::Reference < lang::XMultiServiceFactory > xFactory(xTextDocument, uno::UNO_QUERY_THROW);
        uno::Reference< document::XEmbeddedObjectResolver > xEmbeddedResolver(
            xFactory->createInstance(
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.document.ImportEmbeddedObjectResolver" ))), uno::UNO_QUERY_THROW );
        //hack to work with the ImportEmbeddedObjectResolver
        static sal_Int32 nObjectCount = 100;
        uno::Reference< container::XNameAccess > xNA( xEmbeddedResolver, uno::UNO_QUERY_THROW );
        ::rtl::OUString aURL(RTL_CONSTASCII_USTRINGPARAM("Obj" ));
        aURL += ::rtl::OUString::valueOf( nObjectCount++ );
        uno::Reference < io::XOutputStream > xOLEStream;
        if( (xNA->getByName( aURL ) >>= xOLEStream) && xOLEStream.is() )
        {
            const sal_Int32 nReadRequest = 0x1000;
            uno::Sequence< sal_Int8 > aData;

            while( true )
            {
                sal_Int32 nRead = m_xInputStream->readBytes( aData, nReadRequest );
                xOLEStream->writeBytes( aData );
                if( nRead < nReadRequest )
                {
                    xOLEStream->closeOutput();
                    break;
                }
            }

            static const ::rtl::OUString sProtocol = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("vnd.sun.star.EmbeddedObject:" ));
            ::rtl::OUString aPersistName( xEmbeddedResolver->resolveEmbeddedObjectURL( aURL ) );
            sRet = aPersistName.copy( sProtocol.getLength() );

        }
        uno::Reference< lang::XComponent > xComp( xEmbeddedResolver, uno::UNO_QUERY_THROW );
        xComp->dispose();
    }
    catch( const uno::Exception& rEx)
    {
        (void)rEx;
        OSL_ENSURE(false, "exception in OLEHandler::createOLEObject");
    }
    return sRet;
}

} //namespace dmapper
} //namespace writerfilter
<commit_msg>INTEGRATION: CWS xmlfilter06 (1.1.4); FILE MERGED 2008/06/13 11:37:02 os 1.1.4.3: OleObjects and Shapes combined 2008/05/27 11:36:08 dr 1.1.4.2: joined changes from CWS xmlfilter05 2008/04/24 06:45:45 dr 1.1.4.1: file OLEHandler.cxx was added on branch cws_dev300_xmlfilter06 on 2008-05-27 11:36:08 +0000<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: OLEHandler.cxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#include <OLEHandler.hxx>
#include <PropertyMap.hxx>
#include <doctok/resourceids.hxx>
#include <ooxml/resourceids.hxx>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/document/XEmbeddedObjectResolver.hpp>
#include <com/sun/star/document/XStorageBasedDocument.hpp>
#include <com/sun/star/drawing/XShape.hpp>
#include <com/sun/star/embed/XEmbeddedObject.hpp>
#include <com/sun/star/embed/XEmbedObjectCreator.hpp>
#include <com/sun/star/graphic/XGraphic.hpp>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/text/XTextDocument.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>

namespace writerfilter {
namespace dmapper {

using namespace ::com::sun::star;
/*-- 23.04.2008 10:46:14---------------------------------------------------

  -----------------------------------------------------------------------*/
OLEHandler::OLEHandler() :
    m_nDxaOrig(0),
    m_nDyaOrig(0)
{
}
/*-- 23.04.2008 10:46:14---------------------------------------------------

  -----------------------------------------------------------------------*/
OLEHandler::~OLEHandler()
{
}
/*-- 23.04.2008 10:46:14---------------------------------------------------

  -----------------------------------------------------------------------*/
void OLEHandler::attribute(Id rName, Value & rVal)
{
    rtl::OUString sStringValue = rVal.getString();
    (void)rName;
    /* WRITERFILTERSTATUS: table: OLEHandler_attributedata */
    switch( rName )
    {
        /* WRITERFILTERSTATUS: done: 1, planned: 0, spent: 0 */
        case NS_ooxml::LN_CT_OLEObject_Type:
            m_sObjectType = sStringValue;
        break;
        case NS_ooxml::LN_CT_OLEObject_ProgID:
            m_sProgId = sStringValue;
        break;
        case NS_ooxml::LN_CT_OLEObject_ShapeID:
            m_sShapeId = sStringValue;
        break;
        case NS_ooxml::LN_CT_OLEObject_DrawAspect:
            m_sDrawAspect = sStringValue;
        break;
        case NS_ooxml::LN_CT_OLEObject_ObjectID:
            m_sObjectId = sStringValue;
        break;
        case NS_ooxml::LN_CT_OLEObject_r_id:
            m_sr_id = sStringValue;
        break;
        case NS_ooxml::LN_inputstream:
            rVal.getAny() >>= m_xInputStream;
        break;
        case NS_ooxml::LN_CT_Object_dxaOrig:
            m_nDxaOrig = rVal.getInt();
        break;
        case NS_ooxml::LN_CT_Object_dyaOrig:
            m_nDyaOrig = rVal.getInt();
        break;
        case NS_ooxml::LN_shape:
        /* WRITERFILTERSTATUS: done: 0, planned: 0.5, spent: 0 */
        {
            uno::Reference< drawing::XShape > xTempShape;
            rVal.getAny() >>= xTempShape;
            if( xTempShape.is() )
            {
                m_aShapeSize = xTempShape->getSize();
                m_aShapePosition = xTempShape->getPosition();
                try
                {
                    uno::Reference< beans::XPropertySet > xShapeProps( xTempShape, uno::UNO_QUERY_THROW );
                    xShapeProps->getPropertyValue( PropertyNameSupplier::GetPropertyNameSupplier().GetName( PROP_BITMAP ) ) >>= m_xReplacement;
                }
                catch( const uno::Exception& )
                {
                }
            }
        }
        break;
        default:
            OSL_ENSURE( false, "unknown attribute");
    }
}
/*-- 23.04.2008 10:46:14---------------------------------------------------

  -----------------------------------------------------------------------*/
void OLEHandler::sprm(Sprm & rSprm)
{
    sal_uInt32 nSprmId = rSprm.getId();
    switch( nSprmId )
    {
        case NS_ooxml::LN_OLEObject_OLEObject:
        {
            writerfilter::Reference<Properties>::Pointer_t pProperties = rSprm.getProps();
            if( pProperties.get())
            {
                pProperties->resolve(*this);
            }
        }
        break;
        default:
            OSL_ENSURE( false, "unknown attribute");
    }
}
/*-- 23.04.2008 11:15:19---------------------------------------------------

  -----------------------------------------------------------------------*/
::rtl::OUString OLEHandler::copyOLEOStream( uno::Reference< text::XTextDocument > xTextDocument )
{
    ::rtl::OUString sRet;
    if( !m_xInputStream.is() )
        return sRet;
    try{
        uno::Reference < lang::XMultiServiceFactory > xFactory(xTextDocument, uno::UNO_QUERY_THROW);
        uno::Reference< document::XEmbeddedObjectResolver > xEmbeddedResolver(
            xFactory->createInstance(
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.document.ImportEmbeddedObjectResolver" ))), uno::UNO_QUERY_THROW );
        //hack to work with the ImportEmbeddedObjectResolver
        static sal_Int32 nObjectCount = 100;
        uno::Reference< container::XNameAccess > xNA( xEmbeddedResolver, uno::UNO_QUERY_THROW );
        ::rtl::OUString aURL(RTL_CONSTASCII_USTRINGPARAM("Obj" ));
        aURL += ::rtl::OUString::valueOf( nObjectCount++ );
        uno::Reference < io::XOutputStream > xOLEStream;
        if( (xNA->getByName( aURL ) >>= xOLEStream) && xOLEStream.is() )
        {
            const sal_Int32 nReadRequest = 0x1000;
            uno::Sequence< sal_Int8 > aData;

            while( true )
            {
                sal_Int32 nRead = m_xInputStream->readBytes( aData, nReadRequest );
                xOLEStream->writeBytes( aData );
                if( nRead < nReadRequest )
                {
                    xOLEStream->closeOutput();
                    break;
                }
            }

            static const ::rtl::OUString sProtocol = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("vnd.sun.star.EmbeddedObject:" ));
            ::rtl::OUString aPersistName( xEmbeddedResolver->resolveEmbeddedObjectURL( aURL ) );
            sRet = aPersistName.copy( sProtocol.getLength() );

        }
        uno::Reference< lang::XComponent > xComp( xEmbeddedResolver, uno::UNO_QUERY_THROW );
        xComp->dispose();
    }
    catch( const uno::Exception& rEx)
    {
        (void)rEx;
        OSL_ENSURE(false, "exception in OLEHandler::createOLEObject");
    }
    return sRet;
}

} //namespace dmapper
} //namespace writerfilter
<|endoftext|>


<commit_before>#include "ride/wx.h"
#include <wx/stc/stc.h>
#include <wx/aui/aui.h>
#include <wx/filename.h>

#include "ride/mainwindow.h"
#include "ride/fileedit.h"

#include "ride/settingsdlg.h"

enum
{
  ID_FIRST = wxID_HIGHEST,
  ID_FILE_RIDE_SETTINGS,

  ID_EDIT_MATCH_BRACE,
  ID_EDIT_SELECT_BRACE,
  ID_EDIT_GOTO_LINE,
  ID_EDIT_SELECT_LINE,
  ID_EDIT_TOUPPER,
  ID_EDIT_TOLOWER,
  ID_EDIT_MOVELINESUP,
  ID_EDIT_MOVELINESDOWN,

  ID_PROJECT_NEW,
  ID_PROJECT_OPEN,
  ID_PROJECT_SETTINGS,
  ID_PROJECT_BUILD,
  ID_PROJECT_CLEAN,
  ID_PROJECT_REBUILD,
  ID_PROJECT_DOC,
  ID_PROJECT_RUN,
  ID_PROJECT_TEST,
  ID_PROJECT_BENCH,
  ID_PROJECT_UPDATE
};

wxBEGIN_EVENT_TABLE(MainWindow, wxFrame)
EVT_MENU(wxID_OPEN, MainWindow::OnOpen)
EVT_MENU(wxID_EXIT, MainWindow::OnExit)
EVT_MENU(ID_FILE_RIDE_SETTINGS, MainWindow::ShowSettings)
EVT_MENU(wxID_SAVE, MainWindow::OnSave)
EVT_MENU(wxID_SAVEAS, MainWindow::OnSaveAs)

EVT_MENU(wxID_UNDO, MainWindow::OnUndo)
EVT_MENU(wxID_REDO, MainWindow::OnRedo)
EVT_MENU(wxID_CUT, MainWindow::OnCut)
EVT_MENU(wxID_COPY, MainWindow::OnCopy)
EVT_MENU(wxID_PASTE, MainWindow::OnPaste)
EVT_MENU(wxID_DUPLICATE, MainWindow::OnDuplicate)
EVT_MENU(wxID_DELETE, MainWindow::OnDelete)
EVT_MENU(wxID_FIND, MainWindow::OnFind)
EVT_MENU(wxID_REPLACE, MainWindow::OnReplace)
EVT_MENU(ID_EDIT_MATCH_BRACE, MainWindow::OnMatchBrace)
EVT_MENU(ID_EDIT_SELECT_BRACE, MainWindow::OnSelectBrace)
EVT_MENU(ID_EDIT_GOTO_LINE, MainWindow::OnGotoLine)
EVT_MENU(wxID_INDENT, MainWindow::OnIndent)
EVT_MENU(wxID_UNINDENT, MainWindow::OnUnIndent)
EVT_MENU(wxID_SELECTALL, MainWindow::OnSelectAll)
EVT_MENU(ID_EDIT_SELECT_LINE, MainWindow::OnSelectLine)
EVT_MENU(ID_EDIT_TOUPPER, MainWindow::OnToUpper)
EVT_MENU(ID_EDIT_TOLOWER, MainWindow::OnToLower)
EVT_MENU(ID_EDIT_MOVELINESUP, MainWindow::OnMoveLinesUp)
EVT_MENU(ID_EDIT_MOVELINESDOWN, MainWindow::OnMoveLinesDown)

EVT_MENU(ID_PROJECT_NEW       , MainWindow::OnProjectNew     )
EVT_MENU(ID_PROJECT_OPEN      , MainWindow::OnProjectOpen    )
EVT_MENU(ID_PROJECT_SETTINGS  , MainWindow::OnProjectSettings)
EVT_MENU(ID_PROJECT_BUILD     , MainWindow::OnProjectBuild   )
EVT_MENU(ID_PROJECT_CLEAN     , MainWindow::OnProjectClean   )
EVT_MENU(ID_PROJECT_REBUILD   , MainWindow::OnProjectRebuild )
EVT_MENU(ID_PROJECT_DOC       , MainWindow::OnProjectDoc     )
EVT_MENU(ID_PROJECT_RUN       , MainWindow::OnProjectRun     )
EVT_MENU(ID_PROJECT_TEST      , MainWindow::OnProjectTest    )
EVT_MENU(ID_PROJECT_BENCH     , MainWindow::OnProjectBench   )
EVT_MENU(ID_PROJECT_UPDATE    , MainWindow::OnProjectUpdate  )

EVT_MENU(wxID_ABOUT, MainWindow::OnAbout)

EVT_CLOSE(MainWindow::OnClose)

EVT_AUINOTEBOOK_PAGE_CLOSE(wxID_ANY, MainWindow::OnNotebookPageClose)
EVT_AUINOTEBOOK_PAGE_CLOSED(wxID_ANY, MainWindow::OnNotebookPageClosed)
wxEND_EVENT_TABLE()

MainWindow::MainWindow(const wxString& title, const wxPoint& pos, const wxSize& size)
: wxFrame(NULL, wxID_ANY, title, pos, size)
{
  aui.SetManagedWindow(this);

  LoadSettings(settings);

  //////////////////////////////////////////////////////////////////////////
  wxMenu *menuFile = new wxMenu;
  menuFile->Append(wxID_OPEN, "&Open...\tCtrl-O", "Open a file");
  menuFile->Append(wxID_SAVE, "&Save...\tCtrl-S", "Save the file");
  menuFile->Append(wxID_SAVEAS, "Save &as...\tCtrl-Shift-S", "Save the file as a new file");
  menuFile->AppendSeparator();
  menuFile->Append(ID_FILE_RIDE_SETTINGS, "S&ettings...", "Change the settings of RIDE");
  menuFile->AppendSeparator();
  menuFile->Append(wxID_EXIT);

  //////////////////////////////////////////////////////////////////////////
  wxMenu *menuEdit = new wxMenu;
  menuEdit->Append(wxID_UNDO, "Undo\tCtrl-Z", "");
  menuEdit->Append(wxID_REDO, "Redo\tCtrl-Shift-Z", "");
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_CUT, "Cut\tCtrl-X", "");
  menuEdit->Append(wxID_COPY, "Copy\tCtrl-C", "");
  menuEdit->Append(wxID_PASTE, "Paste\tCtrl-V", "");
  menuEdit->Append(wxID_DUPLICATE, "Duplicate selection or line\tCtrl-D", "");
  menuEdit->Append(wxID_DELETE, "Delete\tDel", "");
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_FIND, "Find\tCtrl-F", "");
  // menuEdit->Append(wxID_OPEN, "Find next\tF3", "");
  menuEdit->Append(wxID_REPLACE, "Replace\tCtrl-H", "");
  // menuEdit->Append(wxID_OPEN, "Replace again\tShift-F4", "");
  menuEdit->AppendSeparator();
  menuEdit->Append(ID_EDIT_MATCH_BRACE, "Match brace\tCtrl-M", "");
  menuEdit->Append(ID_EDIT_SELECT_BRACE, "Select to matching brace\tCtrl-Shift-M", "");
  menuEdit->Append(ID_EDIT_GOTO_LINE, "Goto line\tCtrl-G", "");
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_INDENT, "Increase indent\tTab", "");
  menuEdit->Append(wxID_UNINDENT, "Reduce indent\tShift-Tab", "");
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_SELECTALL, "Select all\tCtrl-A", "");
  menuEdit->Append(ID_EDIT_SELECT_LINE, "Select line\tCtrl-L", "");
  menuEdit->AppendSeparator();
  menuEdit->Append(ID_EDIT_TOUPPER, "Make UPPERCASE\tCtrl-Shift-U", "");
  menuEdit->Append(ID_EDIT_TOLOWER, "Make lowercase\tCtrl-U", "");
  menuEdit->AppendSeparator();
  menuEdit->Append(ID_EDIT_MOVELINESUP, "Move selected lines up\tAlt-Up", "");
  menuEdit->Append(ID_EDIT_MOVELINESDOWN, "Move selected lines down\tAlt-Down", "");

  //////////////////////////////////////////////////////////////////////////

  wxMenu *menuProject = new wxMenu;
  menuProject->Append(ID_PROJECT_NEW, "New project...", "Create a new cargo project");
  menuProject->Append(ID_PROJECT_OPEN, "Open project...", "Open a existing cargo or ride project");
  menuProject->Append(ID_PROJECT_SETTINGS, "Project settings...", "Change the ride project settings");
  menuProject->AppendSeparator();
  menuProject->Append(ID_PROJECT_BUILD, "Build\tCtrl-B", "Compile the current project");
  menuProject->Append(ID_PROJECT_CLEAN, "Clean", "Remove the target directory");
  menuProject->Append(ID_PROJECT_REBUILD, "Rebuild\tCtrl-Shift-B", "Clean + Build");
  menuProject->Append(ID_PROJECT_DOC, "Doc", "Build this project's and its dependencies' documentation");
  menuProject->Append(ID_PROJECT_RUN, "Run\tF5", "Build and execute src/main.rs");
  menuProject->Append(ID_PROJECT_TEST, "Test", "Run the tests");
  menuProject->Append(ID_PROJECT_BENCH, "Bench", "Run the benchmarks");
  menuProject->Append(ID_PROJECT_UPDATE, "Update", "Update dependencies listed in Cargo.lock");

  //////////////////////////////////////////////////////////////////////////
  wxMenu *menuHelp = new wxMenu;
  menuHelp->Append(wxID_ABOUT);

  //////////////////////////////////////////////////////////////////////////
  wxMenuBar *menuBar = new wxMenuBar;
  menuBar->Append(menuFile, "&File");
  menuBar->Append(menuEdit, "&Edit");
  menuBar->Append(menuProject, "&Project");
  menuBar->Append(menuHelp, "&Help");
  SetMenuBar(menuBar);
  CreateStatusBar();
  SetStatusText("");
  createNotebook();

  aui.Update();
}

void MainWindow::createNotebook() {
  wxSize client_size = GetClientSize();
  wxAuiNotebook* ctrl = new wxAuiNotebook(this, wxID_ANY,
    wxPoint(client_size.x, client_size.y),
    wxSize(430, 200),
    wxAUI_NB_DEFAULT_STYLE | wxAUI_NB_TAB_EXTERNAL_MOVE | wxNO_BORDER);
  ctrl->Freeze();
  ctrl->Thaw();
  notebook = ctrl;

  aui.AddPane(notebook, wxAuiPaneInfo().Name(wxT("notebook_content")).PaneBorder(false).CloseButton(false).Movable(false) );
}

const ride::Settings& MainWindow::getSettings() const {
  return settings;
}

MainWindow::~MainWindow() {
  aui.UnInit();
}

void MainWindow::OnExit(wxCommandEvent& event)
{
  Close(true);
}

void MainWindow::OnAbout(wxCommandEvent& event)
{
  wxMessageBox("Ride is a Rust IDE. It's named after concatenating R from rust and IDE.\nFor more information: https://github.com/madeso/ride", "About Ride", wxOK | wxICON_INFORMATION);
}

void MainWindow::OnOpen(wxCommandEvent& event)
{
  wxFileDialog
    openFileDialog(this, _("Open file"), "", "",
    FILE_PATTERN, wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE );
  if (openFileDialog.ShowModal() == wxID_CANCEL)
    return;

  wxArrayString paths;
  openFileDialog.GetPaths(paths);
  for (wxArrayString::iterator path = paths.begin(); path != paths.end(); ++path) {
    wxFileName w(*path);
    w.Normalize();
    new FileEdit(notebook, this, "", w.GetFullPath());
  }
}

FileEdit* MainWindow::getSelectedEditorNull() {
  const int selected = notebook->GetSelection();
  if (selected == -1) {
    return NULL;
  }
  wxWindow* window = notebook->GetPage(selected);
  if (window->IsKindOf(CLASSINFO(FileEdit))) {
    FileEdit* edit = reinterpret_cast<FileEdit*>(window);
    return edit;
  }
  else {
    return NULL;
  }
}

void MainWindow::OnNotebookPageClose(wxAuiNotebookEvent& evt) {
  wxWindow* window = notebook->GetPage(evt.GetSelection());
  if (window->IsKindOf(CLASSINFO(FileEdit))) {
    FileEdit* edit = reinterpret_cast<FileEdit*>(window);
    if (edit->canClose(true) == false) {
      evt.Veto();
    }
  }
}

void MainWindow::OnClose(wxCloseEvent& evt) {
  for (unsigned int i = 0; i < notebook->GetPageCount(); ++i) {
    wxWindow* window = notebook->GetPage(i);
    if (window->IsKindOf(CLASSINFO(FileEdit))) {
      FileEdit* edit = reinterpret_cast<FileEdit*>(window);
      const bool canAbort = evt.CanVeto();
      if (edit->canClose(canAbort) == false) {
        evt.Veto();
        return;
      }
    }
  }

  // shutdown protobuf now, to avoid spewing out memory leaks...
  google::protobuf::ShutdownProtobufLibrary();
  evt.Skip();
}

void MainWindow::setSettings(const ride::Settings& settings) {
  assert(this);
  this->settings = settings;
  updateAllEdits();
}

void MainWindow::OnNotebookPageClosed(wxAuiNotebookEvent& evt) {
}

void MainWindow::updateAllEdits() {
  for (unsigned int i = 0; i < notebook->GetPageCount(); ++i) {
    wxWindow* window = notebook->GetPage(i);
    if (window->IsKindOf(CLASSINFO(FileEdit))) {
      FileEdit* edit = reinterpret_cast<FileEdit*>(window);
      edit->UpdateTextControl();
    }
  }
}

void MainWindow::ShowSettings(wxCommandEvent& event) {
  SettingsDlg settingsdlg(this, this);
  settingsdlg.ShowModal();
}

//////////////////////////////////////////////////////////////////////////
#define MEM_FUN(X) \
  void MainWindow::On ## X(wxCommandEvent& event) {\
    FileEdit* selected = getSelectedEditorNull();\
    if (selected == NULL) return;\
    selected->X();\
  }

MEM_FUN(Save)
MEM_FUN(SaveAs)
MEM_FUN(Undo)
MEM_FUN(Redo)
MEM_FUN(Cut)
MEM_FUN(Copy)
MEM_FUN(Paste)
MEM_FUN(Duplicate)
MEM_FUN(Delete)
MEM_FUN(Find)
MEM_FUN(Replace)
MEM_FUN(MatchBrace)
MEM_FUN(SelectBrace)
MEM_FUN(GotoLine)
MEM_FUN(Indent)
MEM_FUN(UnIndent)
MEM_FUN(SelectAll)
MEM_FUN(SelectLine)
MEM_FUN(ToUpper)
MEM_FUN(ToLower)
MEM_FUN(MoveLinesUp)
MEM_FUN(MoveLinesDown)
#undef MEM_FUN
//////////////////////////////////////////////////////////////////////////

void MainWindow::OnProjectNew(wxCommandEvent& event) {
}

void MainWindow::OnProjectOpen(wxCommandEvent& event) {
}

#define MEM_FUN(X) \
  void MainWindow::OnProject ## X(wxCommandEvent& event) {\
  }

MEM_FUN(Settings)
MEM_FUN(Build   )
MEM_FUN(Clean   )
MEM_FUN(Rebuild )
MEM_FUN(Doc     )
MEM_FUN(Run     )
MEM_FUN(Test    )
MEM_FUN(Bench   )
MEM_FUN(Update  )
#undef MEM_FUN<commit_msg>Lining up event table<commit_after>#include "ride/wx.h"
#include <wx/stc/stc.h>
#include <wx/aui/aui.h>
#include <wx/filename.h>

#include "ride/mainwindow.h"
#include "ride/fileedit.h"

#include "ride/settingsdlg.h"

enum
{
  ID_FIRST = wxID_HIGHEST,
  ID_FILE_RIDE_SETTINGS,

  ID_EDIT_MATCH_BRACE,
  ID_EDIT_SELECT_BRACE,
  ID_EDIT_GOTO_LINE,
  ID_EDIT_SELECT_LINE,
  ID_EDIT_TOUPPER,
  ID_EDIT_TOLOWER,
  ID_EDIT_MOVELINESUP,
  ID_EDIT_MOVELINESDOWN,

  ID_PROJECT_NEW,
  ID_PROJECT_OPEN,
  ID_PROJECT_SETTINGS,
  ID_PROJECT_BUILD,
  ID_PROJECT_CLEAN,
  ID_PROJECT_REBUILD,
  ID_PROJECT_DOC,
  ID_PROJECT_RUN,
  ID_PROJECT_TEST,
  ID_PROJECT_BENCH,
  ID_PROJECT_UPDATE
};

wxBEGIN_EVENT_TABLE(MainWindow, wxFrame)
  EVT_MENU(wxID_OPEN              , MainWindow::OnOpen)
  EVT_MENU(wxID_EXIT              , MainWindow::OnExit)
  EVT_MENU(ID_FILE_RIDE_SETTINGS  , MainWindow::ShowSettings)
  EVT_MENU(wxID_SAVE              , MainWindow::OnSave)
  EVT_MENU(wxID_SAVEAS            , MainWindow::OnSaveAs)

  EVT_MENU(wxID_UNDO              , MainWindow::OnUndo)
  EVT_MENU(wxID_REDO              , MainWindow::OnRedo)
  EVT_MENU(wxID_CUT               , MainWindow::OnCut)
  EVT_MENU(wxID_COPY              , MainWindow::OnCopy)
  EVT_MENU(wxID_PASTE             , MainWindow::OnPaste)
  EVT_MENU(wxID_DUPLICATE         , MainWindow::OnDuplicate)
  EVT_MENU(wxID_DELETE            , MainWindow::OnDelete)
  EVT_MENU(wxID_FIND              , MainWindow::OnFind)
  EVT_MENU(wxID_REPLACE           , MainWindow::OnReplace)
  EVT_MENU(ID_EDIT_MATCH_BRACE    , MainWindow::OnMatchBrace)
  EVT_MENU(ID_EDIT_SELECT_BRACE   , MainWindow::OnSelectBrace)
  EVT_MENU(ID_EDIT_GOTO_LINE      , MainWindow::OnGotoLine)
  EVT_MENU(wxID_INDENT            , MainWindow::OnIndent)
  EVT_MENU(wxID_UNINDENT          , MainWindow::OnUnIndent)
  EVT_MENU(wxID_SELECTALL         , MainWindow::OnSelectAll)
  EVT_MENU(ID_EDIT_SELECT_LINE    , MainWindow::OnSelectLine)
  EVT_MENU(ID_EDIT_TOUPPER        , MainWindow::OnToUpper)
  EVT_MENU(ID_EDIT_TOLOWER        , MainWindow::OnToLower)
  EVT_MENU(ID_EDIT_MOVELINESUP    , MainWindow::OnMoveLinesUp)
  EVT_MENU(ID_EDIT_MOVELINESDOWN  , MainWindow::OnMoveLinesDown)

  EVT_MENU(ID_PROJECT_NEW         , MainWindow::OnProjectNew     )
  EVT_MENU(ID_PROJECT_OPEN        , MainWindow::OnProjectOpen    )
  EVT_MENU(ID_PROJECT_SETTINGS    , MainWindow::OnProjectSettings)
  EVT_MENU(ID_PROJECT_BUILD       , MainWindow::OnProjectBuild   )
  EVT_MENU(ID_PROJECT_CLEAN       , MainWindow::OnProjectClean   )
  EVT_MENU(ID_PROJECT_REBUILD     , MainWindow::OnProjectRebuild )
  EVT_MENU(ID_PROJECT_DOC         , MainWindow::OnProjectDoc     )
  EVT_MENU(ID_PROJECT_RUN         , MainWindow::OnProjectRun     )
  EVT_MENU(ID_PROJECT_TEST        , MainWindow::OnProjectTest    )
  EVT_MENU(ID_PROJECT_BENCH       , MainWindow::OnProjectBench   )
  EVT_MENU(ID_PROJECT_UPDATE      , MainWindow::OnProjectUpdate  )

  EVT_MENU(wxID_ABOUT             , MainWindow::OnAbout)

  EVT_CLOSE(MainWindow::OnClose)

  EVT_AUINOTEBOOK_PAGE_CLOSE(wxID_ANY, MainWindow::OnNotebookPageClose)
  EVT_AUINOTEBOOK_PAGE_CLOSED(wxID_ANY, MainWindow::OnNotebookPageClosed)
wxEND_EVENT_TABLE()

MainWindow::MainWindow(const wxString& title, const wxPoint& pos, const wxSize& size)
: wxFrame(NULL, wxID_ANY, title, pos, size)
{
  aui.SetManagedWindow(this);

  LoadSettings(settings);

  //////////////////////////////////////////////////////////////////////////
  wxMenu *menuFile = new wxMenu;
  menuFile->Append(wxID_OPEN, "&Open...\tCtrl-O", "Open a file");
  menuFile->Append(wxID_SAVE, "&Save...\tCtrl-S", "Save the file");
  menuFile->Append(wxID_SAVEAS, "Save &as...\tCtrl-Shift-S", "Save the file as a new file");
  menuFile->AppendSeparator();
  menuFile->Append(ID_FILE_RIDE_SETTINGS, "S&ettings...", "Change the settings of RIDE");
  menuFile->AppendSeparator();
  menuFile->Append(wxID_EXIT);

  //////////////////////////////////////////////////////////////////////////
  wxMenu *menuEdit = new wxMenu;
  menuEdit->Append(wxID_UNDO, "Undo\tCtrl-Z", "");
  menuEdit->Append(wxID_REDO, "Redo\tCtrl-Shift-Z", "");
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_CUT, "Cut\tCtrl-X", "");
  menuEdit->Append(wxID_COPY, "Copy\tCtrl-C", "");
  menuEdit->Append(wxID_PASTE, "Paste\tCtrl-V", "");
  menuEdit->Append(wxID_DUPLICATE, "Duplicate selection or line\tCtrl-D", "");
  menuEdit->Append(wxID_DELETE, "Delete\tDel", "");
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_FIND, "Find\tCtrl-F", "");
  // menuEdit->Append(wxID_OPEN, "Find next\tF3", "");
  menuEdit->Append(wxID_REPLACE, "Replace\tCtrl-H", "");
  // menuEdit->Append(wxID_OPEN, "Replace again\tShift-F4", "");
  menuEdit->AppendSeparator();
  menuEdit->Append(ID_EDIT_MATCH_BRACE, "Match brace\tCtrl-M", "");
  menuEdit->Append(ID_EDIT_SELECT_BRACE, "Select to matching brace\tCtrl-Shift-M", "");
  menuEdit->Append(ID_EDIT_GOTO_LINE, "Goto line\tCtrl-G", "");
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_INDENT, "Increase indent\tTab", "");
  menuEdit->Append(wxID_UNINDENT, "Reduce indent\tShift-Tab", "");
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_SELECTALL, "Select all\tCtrl-A", "");
  menuEdit->Append(ID_EDIT_SELECT_LINE, "Select line\tCtrl-L", "");
  menuEdit->AppendSeparator();
  menuEdit->Append(ID_EDIT_TOUPPER, "Make UPPERCASE\tCtrl-Shift-U", "");
  menuEdit->Append(ID_EDIT_TOLOWER, "Make lowercase\tCtrl-U", "");
  menuEdit->AppendSeparator();
  menuEdit->Append(ID_EDIT_MOVELINESUP, "Move selected lines up\tAlt-Up", "");
  menuEdit->Append(ID_EDIT_MOVELINESDOWN, "Move selected lines down\tAlt-Down", "");

  //////////////////////////////////////////////////////////////////////////

  wxMenu *menuProject = new wxMenu;
  menuProject->Append(ID_PROJECT_NEW, "New project...", "Create a new cargo project");
  menuProject->Append(ID_PROJECT_OPEN, "Open project...", "Open a existing cargo or ride project");
  menuProject->Append(ID_PROJECT_SETTINGS, "Project settings...", "Change the ride project settings");
  menuProject->AppendSeparator();
  menuProject->Append(ID_PROJECT_BUILD, "Build\tCtrl-B", "Compile the current project");
  menuProject->Append(ID_PROJECT_CLEAN, "Clean", "Remove the target directory");
  menuProject->Append(ID_PROJECT_REBUILD, "Rebuild\tCtrl-Shift-B", "Clean + Build");
  menuProject->Append(ID_PROJECT_DOC, "Doc", "Build this project's and its dependencies' documentation");
  menuProject->Append(ID_PROJECT_RUN, "Run\tF5", "Build and execute src/main.rs");
  menuProject->Append(ID_PROJECT_TEST, "Test", "Run the tests");
  menuProject->Append(ID_PROJECT_BENCH, "Bench", "Run the benchmarks");
  menuProject->Append(ID_PROJECT_UPDATE, "Update", "Update dependencies listed in Cargo.lock");

  //////////////////////////////////////////////////////////////////////////
  wxMenu *menuHelp = new wxMenu;
  menuHelp->Append(wxID_ABOUT);

  //////////////////////////////////////////////////////////////////////////
  wxMenuBar *menuBar = new wxMenuBar;
  menuBar->Append(menuFile, "&File");
  menuBar->Append(menuEdit, "&Edit");
  menuBar->Append(menuProject, "&Project");
  menuBar->Append(menuHelp, "&Help");
  SetMenuBar(menuBar);
  CreateStatusBar();
  SetStatusText("");
  createNotebook();

  aui.Update();
}

void MainWindow::createNotebook() {
  wxSize client_size = GetClientSize();
  wxAuiNotebook* ctrl = new wxAuiNotebook(this, wxID_ANY,
    wxPoint(client_size.x, client_size.y),
    wxSize(430, 200),
    wxAUI_NB_DEFAULT_STYLE | wxAUI_NB_TAB_EXTERNAL_MOVE | wxNO_BORDER);
  ctrl->Freeze();
  ctrl->Thaw();
  notebook = ctrl;

  aui.AddPane(notebook, wxAuiPaneInfo().Name(wxT("notebook_content")).PaneBorder(false).CloseButton(false).Movable(false) );
}

const ride::Settings& MainWindow::getSettings() const {
  return settings;
}

MainWindow::~MainWindow() {
  aui.UnInit();
}

void MainWindow::OnExit(wxCommandEvent& event)
{
  Close(true);
}

void MainWindow::OnAbout(wxCommandEvent& event)
{
  wxMessageBox("Ride is a Rust IDE. It's named after concatenating R from rust and IDE.\nFor more information: https://github.com/madeso/ride", "About Ride", wxOK | wxICON_INFORMATION);
}

void MainWindow::OnOpen(wxCommandEvent& event)
{
  wxFileDialog
    openFileDialog(this, _("Open file"), "", "",
    FILE_PATTERN, wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE );
  if (openFileDialog.ShowModal() == wxID_CANCEL)
    return;

  wxArrayString paths;
  openFileDialog.GetPaths(paths);
  for (wxArrayString::iterator path = paths.begin(); path != paths.end(); ++path) {
    wxFileName w(*path);
    w.Normalize();
    new FileEdit(notebook, this, "", w.GetFullPath());
  }
}

FileEdit* MainWindow::getSelectedEditorNull() {
  const int selected = notebook->GetSelection();
  if (selected == -1) {
    return NULL;
  }
  wxWindow* window = notebook->GetPage(selected);
  if (window->IsKindOf(CLASSINFO(FileEdit))) {
    FileEdit* edit = reinterpret_cast<FileEdit*>(window);
    return edit;
  }
  else {
    return NULL;
  }
}

void MainWindow::OnNotebookPageClose(wxAuiNotebookEvent& evt) {
  wxWindow* window = notebook->GetPage(evt.GetSelection());
  if (window->IsKindOf(CLASSINFO(FileEdit))) {
    FileEdit* edit = reinterpret_cast<FileEdit*>(window);
    if (edit->canClose(true) == false) {
      evt.Veto();
    }
  }
}

void MainWindow::OnClose(wxCloseEvent& evt) {
  for (unsigned int i = 0; i < notebook->GetPageCount(); ++i) {
    wxWindow* window = notebook->GetPage(i);
    if (window->IsKindOf(CLASSINFO(FileEdit))) {
      FileEdit* edit = reinterpret_cast<FileEdit*>(window);
      const bool canAbort = evt.CanVeto();
      if (edit->canClose(canAbort) == false) {
        evt.Veto();
        return;
      }
    }
  }

  // shutdown protobuf now, to avoid spewing out memory leaks...
  google::protobuf::ShutdownProtobufLibrary();
  evt.Skip();
}

void MainWindow::setSettings(const ride::Settings& settings) {
  assert(this);
  this->settings = settings;
  updateAllEdits();
}

void MainWindow::OnNotebookPageClosed(wxAuiNotebookEvent& evt) {
}

void MainWindow::updateAllEdits() {
  for (unsigned int i = 0; i < notebook->GetPageCount(); ++i) {
    wxWindow* window = notebook->GetPage(i);
    if (window->IsKindOf(CLASSINFO(FileEdit))) {
      FileEdit* edit = reinterpret_cast<FileEdit*>(window);
      edit->UpdateTextControl();
    }
  }
}

void MainWindow::ShowSettings(wxCommandEvent& event) {
  SettingsDlg settingsdlg(this, this);
  settingsdlg.ShowModal();
}

//////////////////////////////////////////////////////////////////////////
#define MEM_FUN(X) \
  void MainWindow::On ## X(wxCommandEvent& event) {\
    FileEdit* selected = getSelectedEditorNull();\
    if (selected == NULL) return;\
    selected->X();\
  }

MEM_FUN(Save)
MEM_FUN(SaveAs)
MEM_FUN(Undo)
MEM_FUN(Redo)
MEM_FUN(Cut)
MEM_FUN(Copy)
MEM_FUN(Paste)
MEM_FUN(Duplicate)
MEM_FUN(Delete)
MEM_FUN(Find)
MEM_FUN(Replace)
MEM_FUN(MatchBrace)
MEM_FUN(SelectBrace)
MEM_FUN(GotoLine)
MEM_FUN(Indent)
MEM_FUN(UnIndent)
MEM_FUN(SelectAll)
MEM_FUN(SelectLine)
MEM_FUN(ToUpper)
MEM_FUN(ToLower)
MEM_FUN(MoveLinesUp)
MEM_FUN(MoveLinesDown)
#undef MEM_FUN
//////////////////////////////////////////////////////////////////////////

void MainWindow::OnProjectNew(wxCommandEvent& event) {
}

void MainWindow::OnProjectOpen(wxCommandEvent& event) {
}

#define MEM_FUN(X) \
  void MainWindow::OnProject ## X(wxCommandEvent& event) {\
  }

MEM_FUN(Settings)
MEM_FUN(Build   )
MEM_FUN(Clean   )
MEM_FUN(Rebuild )
MEM_FUN(Doc     )
MEM_FUN(Run     )
MEM_FUN(Test    )
MEM_FUN(Bench   )
MEM_FUN(Update  )
#undef MEM_FUN<|endoftext|>