<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: docmacromode.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef SFX2_DOCMACROMODE_HXX
#define SFX2_DOCMACROMODE_HXX

#include "sfx2/dllapi.h"

/** === begin UNO includes === **/
#include <com/sun/star/task/XInteractionHandler.hpp>
#include <com/sun/star/embed/XStorage.hpp>
#include <com/sun/star/script/XLibraryContainer.hpp>
#include <com/sun/star/document/XEmbeddedScripts.hpp>
/** === end UNO includes === **/

#include <boost/shared_ptr.hpp>

//........................................................................
namespace sfx2
{
//........................................................................

    //====================================================================
    //= IMacroDocumentAccess
    //====================================================================
    /** provides access to several settings of a document, which are needed by ->DocumentMacroMode
        to properly determine the current macro execution mode of this document
    */
    class SAL_NO_VTABLE IMacroDocumentAccess
    {
    public:
        /** retrieves the current MacroExecutionMode.

            Usually, this is initialized from the media descriptor used to load the document,
            respectively the one passed into the document's XModel::attachResource call.

            If no such mode was passed there, document implementations should return
            MacroExecMode::NEVER_EXECUTE.

            @see ::com::sun::star::document::MediaDescriptor::MacroExecutionMode
            @see ::com::sun::star::frame::XComponentLoader::loadComponentFromURL
            @see ::com::sun::star::frame::XModel::attachResource

            @see setCurrentMacroExecMode

            @todo
                Effectively, this is the MacroExecutionMode of the MediaDescriptor of
                the document. Thus, this setting could be obtained from the XModel
                directly. We should introduce a getDocumentModel method here, which
                can be used for this and other purposes.
        */
        virtual sal_Int16
                    getCurrentMacroExecMode() const = 0;

        /** sets the MacroExecutionMode of the document, as calculated by the DocumentMacroMode
            class.

            Effectively, the existence of this method means that the responsibility
            to store the current macro execution mode is not with the DocumentMacroMode
            instance, but with the document instance itself.

            Usually, a document implementation will simply put the macro execution mode
            into its media descriptor, as returned by XModel::getArgs.

            @see ::com::sun::star::document::MediaDescriptor::MacroExecutionMode
            @see ::com::sun::star::frame::XComponentLoader::loadComponentFromURL
            @see ::com::sun::star::frame::XModel::attachResource

            see getCurrentMacroExecMode
        */
        virtual sal_Bool
                    setCurrentMacroExecMode( sal_uInt16 ) = 0;

        /** returns the origin of the document

            This usually is the document's location, or, if the document has been
            newly created from a template, then the location of the template. Location
            here means the complete path of the document, including the file name.

            @todo
                This probably can also be obtained from the XModel, by calling getURL
                or getLocation. If both are empty, then we need an UNO way to obtain
                the URL of the underlying template document - if any. If we have this,
                we could replace this method with a newly introduced method
                getDocumentModel and some internal code.
        */
        virtual ::rtl::OUString
                    getDocumentLocation() const = 0;

        /** returns the storage to which the document has last been committed to, for read-only
            access

            An implementation is allowed to return <NULL/> here if and only if the document
            does not support signing the script storages.

            @todo
                UNOize this, too. Once we have a getDocumentModel, we should be able to
                obtain the "last commit" storage via UNO API, provided it's an
                XStorageBasedDocument.
        */
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >
                    getLastCommitDocumentStorage() = 0;

        /** checks whether the document's storage contains sub storages with macros or scripts

            A default implementation of this method will simply cann DocumentMacroMode::storageHasMacros
            with the document's root storage. However, there might be document types where this
            isn't sufficient (e.g. database documents which contain sub documents which can also
            contain macro/script storages).
        */
        virtual sal_Bool
                    documentStorageHasMacros() const = 0;

        /** provides access to the XEmbeddedScripts interface of the document

            Implementations are allowed to return <NULL/> here if and only if they
            do not (yet) support embedding scripts.

            @todo
                can also be replaced with a call to the (to be introduced) getDocumentModel
                method, and a queryInterface.
        */
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::document::XEmbeddedScripts >
                    getEmbeddedDocumentScripts() const = 0;

        /** returns the state of the signatures for the scripts embedded in the document

            Note: On the medium run, the signature handling of a document should be outsourced
            into a dedicated class, instead of being hard-wired into the SfxObjectShell. This
            class could then be used outside the SfxObjectShell (e.g. in Base documents), too.
            When this happens, this method here becomes should be replaced by a method at this
            new class.

            @seealso <sfx2/signaturestate.hxx>
        */
        virtual sal_Int16
                    getScriptingSignatureState() const = 0;

        /** shows a warning that the document's signature is broken

            Here, a similar note applies as to getScriptingSignatureState: This method doesn't
            really belong here. It's just there because SfxObjectShell_Impl::bSignatureErrorIsShown
            is not accessible where the method is called.
            So, once the signature handling has been oursourced from SfxObjectShell/_Impl, so it
            is re-usable in non-SFX contexts as well, this method here is also unneeded, probably.

            @param _rxInteraction
                the interaction handler to use for showing the warning. It is exactly the same
                as passed to DocumentMacroMode::adjustMacroMode, so it is <NULL/> if and
                only if the instance passed to that method was <NULL/>.
        */
        virtual void
                    showBrokenSignatureWarning(
                        const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& _rxInteraction
                    ) const = 0;
    };

    //====================================================================
    //= DocumentMacroMode
    //====================================================================
    struct DocumentMacroMode_Data;

    /** encapsulates handling the macro mode of a document

        @see com::sun::star::document::MacroExecMode
    */
    class SFX2_DLLPUBLIC DocumentMacroMode
    {
    public:
        /** creates an instance

        @param _rDocumentAccess
            access to the document which this instance works for. Must live as long as the
            DocumentMacroMode instance lives, at least
        */
        DocumentMacroMode( IMacroDocumentAccess& _rDocumentAccess );
        ~DocumentMacroMode();

        /** allows macro execution in the document

            Effectively, the macro mode is set to MacroExecMode::ALWAYS_EXECUTE_NO_WARN.

            @return
                <TRUE/>, always
        */
        sal_Bool    allowMacroExecution();

        /** disallows macro execution in the document

            Effectively, the macro mode is set to MacroExecMode::NEVER_EXECUTE.

            @return
                <TRUE/>, always
        */
        sal_Bool    disallowMacroExecution();

        /** checks whether the document allows executing contained macros.

            The method transforms the current macro execution mode into either
            ALWAYS_EXECUTE_NO_WARN or NEVER_EXECUTE, depending on the current value,
            possible configuration settings, and possible user interaction.

            @param _rxInteraction
                A handler for interactions which might become necessary.
                This includes

Asking the user for confirmation for macro execution.

Telling the user that macro execution is disabled.

                If the user needs to be asked for macro execution confirmation, and if
                this parameter is <NULL/>, the most defensive assumptions will be made,
                effectively disabling macro execution.

            @return
                <TRUE/> if and only if macro execution in this document is allowed.
        */
        sal_Bool    adjustMacroMode(
                    const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& _rxInteraction
                );

        /** determines whether macro execution is disallowed

            There's a number of reasons why macro execution could be disallowed:

Somebody called ->disallowMacroExecution

Macro execution is disabled globally, via the security options

Macro execution mode was not defined initially, and the user denied
                    executing macros for this particular document.

            Note that if this method returns <FALSE/>, then subsequent calls of
            ->adjustMacroMode can still return <FALSE/>.
            That is, if the current macro execution mode for the document is not yet known
            (and inparticular not MacroExecMode::NEVER_EXECUTE), then ->isMacroExecutionDisallowed
            will return <FALSE/>.
            However, a subsequent call to ->adjustMacroMode can result in the user
            denying macro execution, in which ->adjustMacroMode will return <FALSE/>,
            and the next call to isMacroExecutionDisallowed will return <TRUE/>.
        */
        sal_Bool    isMacroExecutionDisallowed() const;

        /** determines whether the document actually has a macros library

            Effectively, this method checks the Basic library container (as returned by
            IMacroDocumentAccess::getEmbeddedDocumentScripts().getBasicLibraries) for
            content.
        */
        sal_Bool    hasMacroLibrary() const;

        /** determines whether the given document storage has sub storages containing scripts
            or macros.

            Effectively, the method checks for the presence of a sub-storage name "Scripts" (where
            BeanShell-/JavaScript-/Python-Scripts are stored, and a sub storage named "Basic" (where
            Basic scripts are stored).
        */
        static sal_Bool
                storageHasMacros( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& _rxStorage );

        /** checks the macro execution mode while loading the document.

            This must be called when the loading is effectively finished, but before any macro action
            happened.

            The method will disallow macro execution for this document if it is disabled
            globally (SvtSecurityOptions::IsMacroDisabled). Otherwise, it will check whether
            the document contains a macro storage or macro libraries. If so, it will
            properly calculate the MacroExecutionMode by calling adjustMacroMode.

            If the document doesn't contain macros, yet, then the macro execution for this
            document will be allowed (again: unless disabled globally), since in this case
            macros which later are newly created by the user should be allowed, of course.

            @see isMacroExecutionDisallowed
            @see IMacroDocumentAccess::documentStorageHasMacros
            @see hasMacroLibrary
            @see IMacroDocumentAccess::checkForBrokenScriptingSignatures
        */
        void    checkMacrosOnLoading(
                    const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& _rxInteraction
                );

    private:
        ::boost::shared_ptr< DocumentMacroMode_Data >   m_pData;
    };

//........................................................................
} // namespace sfx2
//........................................................................

#endif // SFX2_DOCMACROMODE_HXX
<commit_msg>INTEGRATION: CWS dba30c (1.4.28); FILE MERGED 2008/05/09 08:23:23 oj 1.4.28.2: RESYNC: (1.4-1.5); FILE MERGED 2008/05/08 12:55:38 fs 1.4.28.1: ##i87741# checkMacrosOnLoading now returning the adjusted macro execution mode (true/false)<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: docmacromode.hxx,v $
 * $Revision: 1.6 $
 *
 * 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.
 *
 ************************************************************************/

#ifndef SFX2_DOCMACROMODE_HXX
#define SFX2_DOCMACROMODE_HXX

#include "sfx2/dllapi.h"

/** === begin UNO includes === **/
#include <com/sun/star/task/XInteractionHandler.hpp>
#include <com/sun/star/embed/XStorage.hpp>
#include <com/sun/star/script/XLibraryContainer.hpp>
#include <com/sun/star/document/XEmbeddedScripts.hpp>
/** === end UNO includes === **/

#include <boost/shared_ptr.hpp>

//........................................................................
namespace sfx2
{
//........................................................................

    //====================================================================
    //= IMacroDocumentAccess
    //====================================================================
    /** provides access to several settings of a document, which are needed by ->DocumentMacroMode
        to properly determine the current macro execution mode of this document
    */
    class SAL_NO_VTABLE IMacroDocumentAccess
    {
    public:
        /** retrieves the current MacroExecutionMode.

            Usually, this is initialized from the media descriptor used to load the document,
            respectively the one passed into the document's XModel::attachResource call.

            If no such mode was passed there, document implementations should return
            MacroExecMode::NEVER_EXECUTE.

            @see ::com::sun::star::document::MediaDescriptor::MacroExecutionMode
            @see ::com::sun::star::frame::XComponentLoader::loadComponentFromURL
            @see ::com::sun::star::frame::XModel::attachResource

            @see setCurrentMacroExecMode

            @todo
                Effectively, this is the MacroExecutionMode of the MediaDescriptor of
                the document. Thus, this setting could be obtained from the XModel
                directly. We should introduce a getDocumentModel method here, which
                can be used for this and other purposes.
        */
        virtual sal_Int16
                    getCurrentMacroExecMode() const = 0;

        /** sets the MacroExecutionMode of the document, as calculated by the DocumentMacroMode
            class.

            Effectively, the existence of this method means that the responsibility
            to store the current macro execution mode is not with the DocumentMacroMode
            instance, but with the document instance itself.

            Usually, a document implementation will simply put the macro execution mode
            into its media descriptor, as returned by XModel::getArgs.

            @see ::com::sun::star::document::MediaDescriptor::MacroExecutionMode
            @see ::com::sun::star::frame::XComponentLoader::loadComponentFromURL
            @see ::com::sun::star::frame::XModel::attachResource

            see getCurrentMacroExecMode
        */
        virtual sal_Bool
                    setCurrentMacroExecMode( sal_uInt16 ) = 0;

        /** returns the origin of the document

            This usually is the document's location, or, if the document has been
            newly created from a template, then the location of the template. Location
            here means the complete path of the document, including the file name.

            @todo
                This probably can also be obtained from the XModel, by calling getURL
                or getLocation. If both are empty, then we need an UNO way to obtain
                the URL of the underlying template document - if any. If we have this,
                we could replace this method with a newly introduced method
                getDocumentModel and some internal code.
        */
        virtual ::rtl::OUString
                    getDocumentLocation() const = 0;

        /** returns the storage to which the document has last been committed to, for read-only
            access

            An implementation is allowed to return <NULL/> here if and only if the document
            does not support signing the script storages.

            @todo
                UNOize this, too. Once we have a getDocumentModel, we should be able to
                obtain the "last commit" storage via UNO API, provided it's an
                XStorageBasedDocument.
        */
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >
                    getLastCommitDocumentStorage() = 0;

        /** checks whether the document's storage contains sub storages with macros or scripts

            A default implementation of this method will simply cann DocumentMacroMode::storageHasMacros
            with the document's root storage. However, there might be document types where this
            isn't sufficient (e.g. database documents which contain sub documents which can also
            contain macro/script storages).
        */
        virtual sal_Bool
                    documentStorageHasMacros() const = 0;

        /** provides access to the XEmbeddedScripts interface of the document

            Implementations are allowed to return <NULL/> here if and only if they
            do not (yet) support embedding scripts.

            @todo
                can also be replaced with a call to the (to be introduced) getDocumentModel
                method, and a queryInterface.
        */
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::document::XEmbeddedScripts >
                    getEmbeddedDocumentScripts() const = 0;

        /** returns the state of the signatures for the scripts embedded in the document

            Note: On the medium run, the signature handling of a document should be outsourced
            into a dedicated class, instead of being hard-wired into the SfxObjectShell. This
            class could then be used outside the SfxObjectShell (e.g. in Base documents), too.
            When this happens, this method here becomes should be replaced by a method at this
            new class.

            @seealso <sfx2/signaturestate.hxx>
        */
        virtual sal_Int16
                    getScriptingSignatureState() const = 0;

        /** shows a warning that the document's signature is broken

            Here, a similar note applies as to getScriptingSignatureState: This method doesn't
            really belong here. It's just there because SfxObjectShell_Impl::bSignatureErrorIsShown
            is not accessible where the method is called.
            So, once the signature handling has been oursourced from SfxObjectShell/_Impl, so it
            is re-usable in non-SFX contexts as well, this method here is also unneeded, probably.

            @param _rxInteraction
                the interaction handler to use for showing the warning. It is exactly the same
                as passed to DocumentMacroMode::adjustMacroMode, so it is <NULL/> if and
                only if the instance passed to that method was <NULL/>.
        */
        virtual void
                    showBrokenSignatureWarning(
                        const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& _rxInteraction
                    ) const = 0;
    };

    //====================================================================
    //= DocumentMacroMode
    //====================================================================
    struct DocumentMacroMode_Data;

    /** encapsulates handling the macro mode of a document

        @see com::sun::star::document::MacroExecMode
    */
    class SFX2_DLLPUBLIC DocumentMacroMode
    {
    public:
        /** creates an instance

        @param _rDocumentAccess
            access to the document which this instance works for. Must live as long as the
            DocumentMacroMode instance lives, at least
        */
        DocumentMacroMode( IMacroDocumentAccess& _rDocumentAccess );
        ~DocumentMacroMode();

        /** allows macro execution in the document

            Effectively, the macro mode is set to MacroExecMode::ALWAYS_EXECUTE_NO_WARN.

            @return
                <TRUE/>, always
        */
        sal_Bool    allowMacroExecution();

        /** disallows macro execution in the document

            Effectively, the macro mode is set to MacroExecMode::NEVER_EXECUTE.

            @return
                <TRUE/>, always
        */
        sal_Bool    disallowMacroExecution();

        /** checks whether the document allows executing contained macros.

            The method transforms the current macro execution mode into either
            ALWAYS_EXECUTE_NO_WARN or NEVER_EXECUTE, depending on the current value,
            possible configuration settings, and possible user interaction.

            @param _rxInteraction
                A handler for interactions which might become necessary.
                This includes

Asking the user for confirmation for macro execution.

Telling the user that macro execution is disabled.

                If the user needs to be asked for macro execution confirmation, and if
                this parameter is <NULL/>, the most defensive assumptions will be made,
                effectively disabling macro execution.

            @return
                <TRUE/> if and only if macro execution in this document is allowed.
        */
        sal_Bool    adjustMacroMode(
                    const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& _rxInteraction
                );

        /** determines whether macro execution is disallowed

            There's a number of reasons why macro execution could be disallowed:

Somebody called ->disallowMacroExecution

Macro execution is disabled globally, via the security options

Macro execution mode was not defined initially, and the user denied
                    executing macros for this particular document.

            Note that if this method returns <FALSE/>, then subsequent calls of
            ->adjustMacroMode can still return <FALSE/>.
            That is, if the current macro execution mode for the document is not yet known
            (and inparticular not MacroExecMode::NEVER_EXECUTE), then ->isMacroExecutionDisallowed
            will return <FALSE/>.
            However, a subsequent call to ->adjustMacroMode can result in the user
            denying macro execution, in which ->adjustMacroMode will return <FALSE/>,
            and the next call to isMacroExecutionDisallowed will return <TRUE/>.
        */
        sal_Bool    isMacroExecutionDisallowed() const;

        /** determines whether the document actually has a macros library

            Effectively, this method checks the Basic library container (as returned by
            IMacroDocumentAccess::getEmbeddedDocumentScripts().getBasicLibraries) for
            content.
        */
        sal_Bool    hasMacroLibrary() const;

        /** determines whether the given document storage has sub storages containing scripts
            or macros.

            Effectively, the method checks for the presence of a sub-storage name "Scripts" (where
            BeanShell-/JavaScript-/Python-Scripts are stored, and a sub storage named "Basic" (where
            Basic scripts are stored).
        */
        static sal_Bool
                storageHasMacros( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& _rxStorage );

        /** checks the macro execution mode while loading the document.

            This must be called when the loading is effectively finished, but before any macro action
            happened.

            The method will disallow macro execution for this document if it is disabled
            globally (SvtSecurityOptions::IsMacroDisabled). Otherwise, it will check whether
            the document contains a macro storage or macro libraries. If so, it will
            properly calculate the MacroExecutionMode by calling adjustMacroMode.

            If the document doesn't contain macros, yet, then the macro execution for this
            document will be allowed (again: unless disabled globally), since in this case
            macros which later are newly created by the user should be allowed, of course.

            @return
                <TRUE/> if and only if macro execution is allowed in the document

            @see isMacroExecutionDisallowed
            @see IMacroDocumentAccess::documentStorageHasMacros
            @see hasMacroLibrary
            @see IMacroDocumentAccess::checkForBrokenScriptingSignatures
        */
        sal_Bool
                checkMacrosOnLoading(
                    const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& _rxInteraction
                );

    private:
        ::boost::shared_ptr< DocumentMacroMode_Data >   m_pData;
    };

//........................................................................
} // namespace sfx2
//........................................................................

#endif // SFX2_DOCMACROMODE_HXX
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// frontend_logger.cpp
//
// Identification: src/backend/logging/frontend_logger.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <thread>

#include "backend/common/logger.h"
#include "backend/logging/log_manager.h"
#include "backend/logging/checkpoint_manager.h"
#include "backend/logging/frontend_logger.h"
#include "backend/logging/checkpoint.h"
#include "backend/logging/loggers/wal_frontend_logger.h"
#include "backend/logging/loggers/wbl_frontend_logger.h"

// configuration for testing
extern int64_t peloton_wait_timeout;

namespace peloton {
namespace logging {

FrontendLogger::FrontendLogger() {
  logger_type = LOGGER_TYPE_FRONTEND;

  // Set wait timeout
  wait_timeout = peloton_wait_timeout;
}

FrontendLogger::~FrontendLogger() {
  for (auto backend_logger : backend_loggers) {
    delete backend_logger;
  }
}

/** * @brief Return the frontend logger based on logging type
 * @param logging type can be write ahead logging or write behind logging
 */
FrontendLogger *FrontendLogger::GetFrontendLogger(LoggingType logging_type,
                                                  bool test_mode) {
  FrontendLogger *frontend_logger = nullptr;

  LOG_INFO("Logging_type is %d", (int)logging_type);
  if (IsBasedOnWriteAheadLogging(logging_type) == true) {
    frontend_logger = new WriteAheadFrontendLogger(test_mode);
  } else if (IsBasedOnWriteBehindLogging(logging_type) == true) {
    frontend_logger = new WriteBehindFrontendLogger();
  } else {
    LOG_ERROR("Unsupported logging type");
  }

  return frontend_logger;
}

// only the distinguished logger does this
void FrontendLogger::UpdateGlobalMaxFlushId() {
  if (is_distinguished_logger) {
    cid_t global_max_flushed_commit_id = INVALID_CID;

    auto &log_manager = LogManager::GetInstance();
    std::vector<std::unique_ptr<FrontendLogger>> &frontend_loggers =
        log_manager.GetFrontendLoggersList();
    int num_loggers = frontend_loggers.size();

    for (int i = 0; i < num_loggers; i++) {
      cid_t logger_max_commit_id;
      logger_max_commit_id = frontend_loggers[i].get()->GetMaxFlushedCommitId();
      global_max_flushed_commit_id =
          std::max(global_max_flushed_commit_id, logger_max_commit_id);
    }

    log_manager.SetGlobalMaxFlushedCommitId(global_max_flushed_commit_id);
  }
}

/**
 * @brief MainLoop
 */
void FrontendLogger::MainLoop(void) {
  auto &log_manager = LogManager::GetInstance();

  /////////////////////////////////////////////////////////////////////
  // STANDBY MODE
  /////////////////////////////////////////////////////////////////////

  LOG_TRACE("FrontendLogger Standby Mode");

  // Standby before we need to do RECOVERY
  log_manager.WaitForModeTransition(LOGGING_STATUS_TYPE_STANDBY, false);

  // Do recovery if we can, otherwise terminate
  switch (log_manager.GetLoggingStatus()) {
    case LOGGING_STATUS_TYPE_RECOVERY: {
      LOG_TRACE("Frontendlogger] Recovery Mode");

      /////////////////////////////////////////////////////////////////////
      // RECOVERY MODE
      /////////////////////////////////////////////////////////////////////

      // First, do recovery if needed
      LOG_INFO("Log manager: Invoking DoRecovery");
      DoRecovery();
      LOG_INFO("Log manager: DoRecovery done");

      // Now, enter LOGGING mode
      // log_manager.SetLoggingStatus(LOGGING_STATUS_TYPE_LOGGING);
      // Notify log manager that this frontend logger has completed recovery
      log_manager.NotifyRecoveryDone();

      // Now wait until the other frontend loggers also complete their recovery
      log_manager.WaitForModeTransition(LOGGING_STATUS_TYPE_LOGGING, true);

      break;
    }

    case LOGGING_STATUS_TYPE_LOGGING: {
      LOG_TRACE("Frontendlogger] Logging Mode");
    } break;

    default:
      break;
  }

  /////////////////////////////////////////////////////////////////////
  // LOGGING MODE
  /////////////////////////////////////////////////////////////////////

  // Periodically, wake up and do logging
  while (log_manager.GetLoggingStatus() == LOGGING_STATUS_TYPE_LOGGING) {
    // Collect LogRecords from all backend loggers
    // LOG_INFO("Log manager: Invoking CollectLogRecordsFromBackendLoggers");
    CollectLogRecordsFromBackendLoggers();

    // Flush the data to the file
    // LOG_INFO("Log manager: Invoking FlushLogRecords");
    FlushLogRecords();

    // update the global max flushed ID (only distinguished logger does this)
    UpdateGlobalMaxFlushId();
  }

  /////////////////////////////////////////////////////////////////////
  // TERMINATE MODE
  /////////////////////////////////////////////////////////////////////

  // flush any remaining log records
  CollectLogRecordsFromBackendLoggers();
  FlushLogRecords();

  /////////////////////////////////////////////////////////////////////
  // SLEEP MODE
  /////////////////////////////////////////////////////////////////////

  LOG_TRACE("Frontendlogger Sleep Mode");

  // Setting frontend logger status to sleep
  log_manager.SetLoggingStatus(LOGGING_STATUS_TYPE_SLEEP);
}

/**
 * @brief Collect the log records from BackendLoggers
 */
void FrontendLogger::CollectLogRecordsFromBackendLoggers() {
  auto sleep_period = std::chrono::milliseconds(wait_timeout);
  std::this_thread::sleep_for(sleep_period);
  int debug_flag = 0;

  auto &log_manager = LogManager::GetInstance();

  {
    cid_t max_committed_cid = 0;
    cid_t lower_bound = MAX_CID;

    // Look at the local queues of the backend loggers
    backend_loggers_lock.Lock();
    // LOG_TRACE("Collect log buffers from %lu backend loggers",
    //           backend_loggers.size());
    int i = 0;
    for (auto backend_logger : backend_loggers) {
      auto cid_pair = backend_logger->PrepareLogBuffers();
      auto &log_buffers = backend_logger->GetLogBuffers();
      auto log_buffer_size = log_buffers.size();

      // update max_possible_commit_id with the latest buffer
      cid_t backend_lower_bound = cid_pair.first;
      cid_t backend_committed = cid_pair.second;
      if (backend_committed > backend_lower_bound) {
        LOG_INFO("bel: %d got max_committed_cid:%lu", i, backend_committed);
        max_committed_cid = std::max(max_committed_cid, backend_committed);
      } else if (backend_lower_bound != INVALID_CID) {
        LOG_INFO("bel: %d got lower_bound_cid:%lu", i, backend_lower_bound);
        lower_bound = std::min(lower_bound, backend_lower_bound);
      }
      // Skip current backend_logger, nothing to do
      if (log_buffer_size == 0) {
        i++;
        continue;
      }

      // Move the log record from backend_logger to here
      for (oid_t log_record_itr = 0; log_record_itr < log_buffer_size;
           log_record_itr++) {
        // copy to front end logger
        global_queue.push_back(std::move(log_buffers[log_record_itr]));
      }

      // cleanup the local queue
      log_buffers.clear();
      i++;
    }
    cid_t max_possible_commit_id;
    if (max_committed_cid == 0 && lower_bound == MAX_CID) {
      // nothing collected
      cid_t global_max = log_manager.GetGlobalMaxFlushedCommitId();

      if (global_max > max_collected_commit_id)
        max_collected_commit_id = global_max;

      max_possible_commit_id = max_collected_commit_id;
      max_seen_commit_id = max_collected_commit_id;
      debug_flag = 1;
    } else if (max_committed_cid == 0) {
      max_possible_commit_id = lower_bound;
      debug_flag = 2;
    } else if (lower_bound == MAX_CID) {
      debug_flag = 3;
      max_possible_commit_id = max_committed_cid;
    } else {
      max_possible_commit_id = lower_bound;
      debug_flag = 4;
    }
    // max_collected_commit_id should never decrease
    // LOG_INFO("Before assert");
    if (max_possible_commit_id < max_collected_commit_id) {
      LOG_INFO(
          "Will abort! max_possible_commit_id: %d, max_collected_commit_id: %d",
          (int)max_possible_commit_id, (int)max_collected_commit_id);
      LOG_INFO("Had entered Case %d", (int)debug_flag);
    }
    assert(max_possible_commit_id >= max_collected_commit_id);
    if (max_committed_cid > max_seen_commit_id) {
      max_seen_commit_id = max_committed_cid;
    }
    max_collected_commit_id = max_possible_commit_id;
    // LOG_INFO("max_collected_commit_id: %d, max_possible_commit_id: %d",
    // (int)max_collected_commit_id, (int)max_possible_commit_id);
    backend_loggers_lock.Unlock();
  }
}

cid_t FrontendLogger::GetMaxFlushedCommitId() { return max_flushed_commit_id; }

void FrontendLogger::SetMaxFlushedCommitId(cid_t cid) {
  max_flushed_commit_id = cid;
}

void FrontendLogger::SetBackendLoggerLoggedCid(BackendLogger &bel) {
  backend_loggers_lock.Lock();
  bel.SetLoggingCidLowerBound(max_seen_commit_id);
  backend_loggers_lock.Unlock();
}

/**
 * @brief Add backend logger to the list of backend loggers
 * @param backend logger
 */
void FrontendLogger::AddBackendLogger(BackendLogger *backend_logger) {
  // Grant empty buffers
  for (int i = 0; i < BUFFER_POOL_SIZE; i++) {
    std::unique_ptr<LogBuffer> buffer(new LogBuffer(backend_logger));
    backend_logger->GrantEmptyBuffer(std::move(buffer));
  }
  // Add backend logger to the list of backend loggers
  backend_loggers_lock.Lock();
  backend_logger->SetLoggingCidLowerBound(max_collected_commit_id);
  backend_loggers.push_back(backend_logger);
  backend_loggers_lock.Unlock();
}

}  // namespace logging
}
<commit_msg>Fix build failure without debug option<commit_after>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// frontend_logger.cpp
//
// Identification: src/backend/logging/frontend_logger.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <thread>

#include "backend/common/logger.h"
#include "backend/logging/log_manager.h"
#include "backend/logging/checkpoint_manager.h"
#include "backend/logging/frontend_logger.h"
#include "backend/logging/checkpoint.h"
#include "backend/logging/loggers/wal_frontend_logger.h"
#include "backend/logging/loggers/wbl_frontend_logger.h"

// configuration for testing
extern int64_t peloton_wait_timeout;

namespace peloton {
namespace logging {

FrontendLogger::FrontendLogger() {
  logger_type = LOGGER_TYPE_FRONTEND;

  // Set wait timeout
  wait_timeout = peloton_wait_timeout;
}

FrontendLogger::~FrontendLogger() {
  for (auto backend_logger : backend_loggers) {
    delete backend_logger;
  }
}

/** * @brief Return the frontend logger based on logging type
 * @param logging type can be write ahead logging or write behind logging
 */
FrontendLogger *FrontendLogger::GetFrontendLogger(LoggingType logging_type,
                                                  bool test_mode) {
  FrontendLogger *frontend_logger = nullptr;

  LOG_INFO("Logging_type is %d", (int)logging_type);
  if (IsBasedOnWriteAheadLogging(logging_type) == true) {
    frontend_logger = new WriteAheadFrontendLogger(test_mode);
  } else if (IsBasedOnWriteBehindLogging(logging_type) == true) {
    frontend_logger = new WriteBehindFrontendLogger();
  } else {
    LOG_ERROR("Unsupported logging type");
  }

  return frontend_logger;
}

// only the distinguished logger does this
void FrontendLogger::UpdateGlobalMaxFlushId() {
  if (is_distinguished_logger) {
    cid_t global_max_flushed_commit_id = INVALID_CID;

    auto &log_manager = LogManager::GetInstance();
    std::vector<std::unique_ptr<FrontendLogger>> &frontend_loggers =
        log_manager.GetFrontendLoggersList();
    int num_loggers = frontend_loggers.size();

    for (int i = 0; i < num_loggers; i++) {
      cid_t logger_max_commit_id;
      logger_max_commit_id = frontend_loggers[i].get()->GetMaxFlushedCommitId();
      global_max_flushed_commit_id =
          std::max(global_max_flushed_commit_id, logger_max_commit_id);
    }

    log_manager.SetGlobalMaxFlushedCommitId(global_max_flushed_commit_id);
  }
}

/**
 * @brief MainLoop
 */
void FrontendLogger::MainLoop(void) {
  auto &log_manager = LogManager::GetInstance();

  /////////////////////////////////////////////////////////////////////
  // STANDBY MODE
  /////////////////////////////////////////////////////////////////////

  LOG_TRACE("FrontendLogger Standby Mode");

  // Standby before we need to do RECOVERY
  log_manager.WaitForModeTransition(LOGGING_STATUS_TYPE_STANDBY, false);

  // Do recovery if we can, otherwise terminate
  switch (log_manager.GetLoggingStatus()) {
    case LOGGING_STATUS_TYPE_RECOVERY: {
      LOG_TRACE("Frontendlogger] Recovery Mode");

      /////////////////////////////////////////////////////////////////////
      // RECOVERY MODE
      /////////////////////////////////////////////////////////////////////

      // First, do recovery if needed
      LOG_INFO("Log manager: Invoking DoRecovery");
      DoRecovery();
      LOG_INFO("Log manager: DoRecovery done");

      // Now, enter LOGGING mode
      // log_manager.SetLoggingStatus(LOGGING_STATUS_TYPE_LOGGING);
      // Notify log manager that this frontend logger has completed recovery
      log_manager.NotifyRecoveryDone();

      // Now wait until the other frontend loggers also complete their recovery
      log_manager.WaitForModeTransition(LOGGING_STATUS_TYPE_LOGGING, true);

      break;
    }

    case LOGGING_STATUS_TYPE_LOGGING: {
      LOG_TRACE("Frontendlogger] Logging Mode");
    } break;

    default:
      break;
  }

  /////////////////////////////////////////////////////////////////////
  // LOGGING MODE
  /////////////////////////////////////////////////////////////////////

  // Periodically, wake up and do logging
  while (log_manager.GetLoggingStatus() == LOGGING_STATUS_TYPE_LOGGING) {
    // Collect LogRecords from all backend loggers
    // LOG_INFO("Log manager: Invoking CollectLogRecordsFromBackendLoggers");
    CollectLogRecordsFromBackendLoggers();

    // Flush the data to the file
    // LOG_INFO("Log manager: Invoking FlushLogRecords");
    FlushLogRecords();

    // update the global max flushed ID (only distinguished logger does this)
    UpdateGlobalMaxFlushId();
  }

  /////////////////////////////////////////////////////////////////////
  // TERMINATE MODE
  /////////////////////////////////////////////////////////////////////

  // flush any remaining log records
  CollectLogRecordsFromBackendLoggers();
  FlushLogRecords();

  /////////////////////////////////////////////////////////////////////
  // SLEEP MODE
  /////////////////////////////////////////////////////////////////////

  LOG_TRACE("Frontendlogger Sleep Mode");

  // Setting frontend logger status to sleep
  log_manager.SetLoggingStatus(LOGGING_STATUS_TYPE_SLEEP);
}

/**
 * @brief Collect the log records from BackendLoggers
 */
void FrontendLogger::CollectLogRecordsFromBackendLoggers() {
  auto sleep_period = std::chrono::milliseconds(wait_timeout);
  std::this_thread::sleep_for(sleep_period);
  int debug_flag = 0;

  auto &log_manager = LogManager::GetInstance();

  {
    cid_t max_committed_cid = 0;
    cid_t lower_bound = MAX_CID;

    // Look at the local queues of the backend loggers
    backend_loggers_lock.Lock();
    // LOG_TRACE("Collect log buffers from %lu backend loggers",
    //           backend_loggers.size());
    int i = 0;
    for (auto backend_logger : backend_loggers) {
      auto cid_pair = backend_logger->PrepareLogBuffers();
      auto &log_buffers = backend_logger->GetLogBuffers();
      auto log_buffer_size = log_buffers.size();

      // update max_possible_commit_id with the latest buffer
      cid_t backend_lower_bound = cid_pair.first;
      cid_t backend_committed = cid_pair.second;
      if (backend_committed > backend_lower_bound) {
        LOG_INFO("bel: %d got max_committed_cid:%lu", i, backend_committed);
        max_committed_cid = std::max(max_committed_cid, backend_committed);
      } else if (backend_lower_bound != INVALID_CID) {
        LOG_INFO("bel: %d got lower_bound_cid:%lu", i, backend_lower_bound);
        lower_bound = std::min(lower_bound, backend_lower_bound);
      }
      // Skip current backend_logger, nothing to do
      if (log_buffer_size == 0) {
        i++;
        continue;
      }

      // Move the log record from backend_logger to here
      for (oid_t log_record_itr = 0; log_record_itr < log_buffer_size;
           log_record_itr++) {
        // copy to front end logger
        global_queue.push_back(std::move(log_buffers[log_record_itr]));
      }

      // cleanup the local queue
      log_buffers.clear();
      i++;
    }
    cid_t max_possible_commit_id;
    if (max_committed_cid == 0 && lower_bound == MAX_CID) {
      // nothing collected
      cid_t global_max = log_manager.GetGlobalMaxFlushedCommitId();

      if (global_max > max_collected_commit_id)
        max_collected_commit_id = global_max;

      max_possible_commit_id = max_collected_commit_id;
      max_seen_commit_id = max_collected_commit_id;
      debug_flag = 1;
    } else if (max_committed_cid == 0) {
      max_possible_commit_id = lower_bound;
      debug_flag = 2;
    } else if (lower_bound == MAX_CID) {
      debug_flag = 3;
      max_possible_commit_id = max_committed_cid;
    } else {
      max_possible_commit_id = lower_bound;
      debug_flag = 4;
    }
    // max_collected_commit_id should never decrease
    // LOG_INFO("Before assert");
    if (max_possible_commit_id < max_collected_commit_id) {
      LOG_INFO(
          "Will abort! max_possible_commit_id: %d, max_collected_commit_id: %d",
          (int)max_possible_commit_id, (int)max_collected_commit_id);
      LOG_INFO("Had entered Case %d", (int)debug_flag);
      (void) debug_flag;
    }
    assert(max_possible_commit_id >= max_collected_commit_id);
    if (max_committed_cid > max_seen_commit_id) {
      max_seen_commit_id = max_committed_cid;
    }
    max_collected_commit_id = max_possible_commit_id;
    // LOG_INFO("max_collected_commit_id: %d, max_possible_commit_id: %d",
    // (int)max_collected_commit_id, (int)max_possible_commit_id);
    backend_loggers_lock.Unlock();
  }
}

cid_t FrontendLogger::GetMaxFlushedCommitId() { return max_flushed_commit_id; }

void FrontendLogger::SetMaxFlushedCommitId(cid_t cid) {
  max_flushed_commit_id = cid;
}

void FrontendLogger::SetBackendLoggerLoggedCid(BackendLogger &bel) {
  backend_loggers_lock.Lock();
  bel.SetLoggingCidLowerBound(max_seen_commit_id);
  backend_loggers_lock.Unlock();
}

/**
 * @brief Add backend logger to the list of backend loggers
 * @param backend logger
 */
void FrontendLogger::AddBackendLogger(BackendLogger *backend_logger) {
  // Grant empty buffers
  for (int i = 0; i < BUFFER_POOL_SIZE; i++) {
    std::unique_ptr<LogBuffer> buffer(new LogBuffer(backend_logger));
    backend_logger->GrantEmptyBuffer(std::move(buffer));
  }
  // Add backend logger to the list of backend loggers
  backend_loggers_lock.Lock();
  backend_logger->SetLoggingCidLowerBound(max_collected_commit_id);
  backend_loggers.push_back(backend_logger);
  backend_loggers_lock.Unlock();
}

}  // namespace logging
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2010  Thomas McGuire <mcguire@kde.org>
 * Copyright (C) 2011, 2015  Alexander Potashev <aspotashev@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) version 3, or any
 * later version accepted by the membership of KDE e.V. (or its
 * successor approved by the membership of KDE e.V.), which shall
 * act as a proxy defined in Section 6 of version 3 of the license.
 *
 * 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, see <http://www.gnu.org/licenses/>.
 */

#include "authenticationdialog.h"

#include "util.h"

#include <KWebView>
#include <KMessageBox>

#include <KLocalizedString>

#include <QtCore/QTimer>
#include <QtCore/QUrlQuery>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QProgressBar>
#include <QtWidgets/QDialogButtonBox>

namespace Vkontakte
{

class Q_DECL_HIDDEN AuthenticationDialog::Private
{
public:
    QString appId;
    Vkontakte::AppPermissions::Value permissions;
    QString displayMode;

    KWebView *webView;
    QProgressBar *progressBar;

    QString error;
    QString errorDescription;
};

AuthenticationDialog::AuthenticationDialog(QWidget *parent)
    : QDialog(parent)
    , d(new Private)
{
    d->displayMode = QStringLiteral("page");

    setWindowTitle(i18nc("@title:window", "Authenticate with VKontakte"));
    setAttribute(Qt::WA_DeleteOnClose, true);

    QWidget *progressWidget = new QWidget(this);
    QHBoxLayout *progressLayout = new QHBoxLayout(progressWidget);
    progressLayout->setMargin(0);
    d->webView = new KWebView(this);

    d->progressBar = new QProgressBar(this);
    d->progressBar->setRange(0, 100);
    QLabel *progressLabel = new QLabel(i18n("Loading Page:"), this);
    progressLayout->addWidget(progressLabel);
    progressLayout->addWidget(d->progressBar);

    // Buttons
    QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Cancel, this);
    connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);

    // Layout
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(progressWidget);
    layout->addWidget(d->webView);
    layout->addWidget(buttonBox);
    setLayout(layout);

    connect(buttonBox, &QDialogButtonBox::rejected, this, &AuthenticationDialog::canceled);
    connect(d->webView, SIGNAL(urlChanged(QUrl)), this, SLOT(urlChanged(QUrl)));
    connect(d->webView, SIGNAL(loadStarted()), progressWidget, SLOT(show()));
    connect(d->webView, SIGNAL(loadFinished(bool)), progressWidget, SLOT(hide()));
    connect(d->webView, SIGNAL(loadProgress(int)), d->progressBar, SLOT(setValue(int)));
    connect(d->webView, SIGNAL(loadFinished(bool)), this, SLOT(loadFinished(bool)));
}

AuthenticationDialog::~AuthenticationDialog()
{
    delete d;
}

void AuthenticationDialog::setAppId(const QString &appId)
{
    d->appId = appId;
}

void Vkontakte::AuthenticationDialog::setPermissions(Vkontakte::AppPermissions::Value permissions)
{
    d->permissions = permissions;
}

// display= {page, popup, touch, wap}
void AuthenticationDialog::setDisplayMode(const QString &displayMode)
{
    d->displayMode = displayMode;
}

void AuthenticationDialog::start()
{
    Q_ASSERT(!d->appId.isEmpty());

    const QString url = QStringLiteral(
        "http://oauth.vk.com/authorize?"
        "client_id=%1&"
        "scope=%2&"
        "redirect_uri=http://oauth.vk.com/blank.html&"
        "display=%3&"
        "response_type=token")
        .arg(d->appId)
        .arg(appPermissionsToStringList(d->permissions).join(QStringLiteral(",")))
        .arg(d->displayMode);
    qDebug() << "Showing" << url;
    d->webView->setUrl(QUrl::fromUserInput(url));
    show();
}

void AuthenticationDialog::showErrorDialog()
{
    hide();
    const QString details = i18n("VKontakte Error Description: %1
"
                                 "VKontakte Error: %2
", d->errorDescription, d->error);
    KMessageBox::detailedSorry(this, i18n("Authentication with VKontakte was not successful."),
                               details, i18nc("@title:window", "Authentication Problem"));
    emit canceled();
    close();
}

void AuthenticationDialog::urlChanged(const QUrl &url)
{
    qDebug() << "Navigating to" << url;
    if (url.host() == QStringLiteral("oauth.vk.com") && url.path() == QStringLiteral("/blank.html"))
    {
        const QUrlQuery query(url);

        d->error = query.queryItemValue(QStringLiteral("error"));
        d->errorDescription = query.queryItemValue(QStringLiteral("error_description")).replace(QLatin1Char('+'), QLatin1Char(' '));
        if (!d->error.isEmpty() || !d->errorDescription.isEmpty())
        {
            QTimer::singleShot(0, this, SLOT(showErrorDialog()));
            return;
        }

        // The URL comes in the form "bla#access_token=bla&expires_in=foo", we need to convert from
        // # to ?
        const QUrl fixedURL = QUrl::fromUserInput(url.toString().replace(QLatin1Char('#'), QLatin1Char('?')));
        const QUrlQuery fixedQuery(fixedURL);
        const QString accessToken = fixedQuery.queryItemValue(QStringLiteral("access_token"));
        const QString tokenExpiresIn = fixedQuery.queryItemValue(QStringLiteral("expires_in")); // TODO: use this for something?
        if (!accessToken.isEmpty())
        {
            emit authenticated(accessToken);
            QTimer::singleShot(0, this, SLOT(close()));
        }
    }
}

void AuthenticationDialog::loadFinished(bool ok)
{
    if (!ok)
    {
        hide();

        KMessageBox::error(parentWidget(),
                           i18n("There was a network error when trying to authenticate with VKontakte web service."),
                           i18nc("@title:window", "Network Error"));

        emit canceled();
        close();
    }
}

} /* namespace Vkontakte */
<commit_msg>replace obsolete setMargin() function<commit_after>/*
 * Copyright (C) 2010  Thomas McGuire <mcguire@kde.org>
 * Copyright (C) 2011, 2015  Alexander Potashev <aspotashev@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) version 3, or any
 * later version accepted by the membership of KDE e.V. (or its
 * successor approved by the membership of KDE e.V.), which shall
 * act as a proxy defined in Section 6 of version 3 of the license.
 *
 * 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, see <http://www.gnu.org/licenses/>.
 */

#include "authenticationdialog.h"

#include "util.h"

#include <KWebView>
#include <KMessageBox>

#include <KLocalizedString>

#include <QtCore/QTimer>
#include <QtCore/QUrlQuery>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QProgressBar>
#include <QtWidgets/QDialogButtonBox>

namespace Vkontakte
{

class Q_DECL_HIDDEN AuthenticationDialog::Private
{
public:
    QString appId;
    Vkontakte::AppPermissions::Value permissions;
    QString displayMode;

    KWebView *webView;
    QProgressBar *progressBar;

    QString error;
    QString errorDescription;
};

AuthenticationDialog::AuthenticationDialog(QWidget *parent)
    : QDialog(parent)
    , d(new Private)
{
    d->displayMode = QStringLiteral("page");

    setWindowTitle(i18nc("@title:window", "Authenticate with VKontakte"));
    setAttribute(Qt::WA_DeleteOnClose, true);

    QWidget *progressWidget = new QWidget(this);
    QHBoxLayout *progressLayout = new QHBoxLayout(progressWidget);
    progressLayout->setContentsMargins(QMargins());
    d->webView = new KWebView(this);

    d->progressBar = new QProgressBar(this);
    d->progressBar->setRange(0, 100);
    QLabel *progressLabel = new QLabel(i18n("Loading Page:"), this);
    progressLayout->addWidget(progressLabel);
    progressLayout->addWidget(d->progressBar);

    // Buttons
    QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Cancel, this);
    connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);

    // Layout
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(progressWidget);
    layout->addWidget(d->webView);
    layout->addWidget(buttonBox);
    setLayout(layout);

    connect(buttonBox, &QDialogButtonBox::rejected, this, &AuthenticationDialog::canceled);
    connect(d->webView, SIGNAL(urlChanged(QUrl)), this, SLOT(urlChanged(QUrl)));
    connect(d->webView, SIGNAL(loadStarted()), progressWidget, SLOT(show()));
    connect(d->webView, SIGNAL(loadFinished(bool)), progressWidget, SLOT(hide()));
    connect(d->webView, SIGNAL(loadProgress(int)), d->progressBar, SLOT(setValue(int)));
    connect(d->webView, SIGNAL(loadFinished(bool)), this, SLOT(loadFinished(bool)));
}

AuthenticationDialog::~AuthenticationDialog()
{
    delete d;
}

void AuthenticationDialog::setAppId(const QString &appId)
{
    d->appId = appId;
}

void Vkontakte::AuthenticationDialog::setPermissions(Vkontakte::AppPermissions::Value permissions)
{
    d->permissions = permissions;
}

// display= {page, popup, touch, wap}
void AuthenticationDialog::setDisplayMode(const QString &displayMode)
{
    d->displayMode = displayMode;
}

void AuthenticationDialog::start()
{
    Q_ASSERT(!d->appId.isEmpty());

    const QString url = QStringLiteral(
        "http://oauth.vk.com/authorize?"
        "client_id=%1&"
        "scope=%2&"
        "redirect_uri=http://oauth.vk.com/blank.html&"
        "display=%3&"
        "response_type=token")
        .arg(d->appId)
        .arg(appPermissionsToStringList(d->permissions).join(QStringLiteral(",")))
        .arg(d->displayMode);
    qDebug() << "Showing" << url;
    d->webView->setUrl(QUrl::fromUserInput(url));
    show();
}

void AuthenticationDialog::showErrorDialog()
{
    hide();
    const QString details = i18n("VKontakte Error Description: %1
"
                                 "VKontakte Error: %2
", d->errorDescription, d->error);
    KMessageBox::detailedSorry(this, i18n("Authentication with VKontakte was not successful."),
                               details, i18nc("@title:window", "Authentication Problem"));
    emit canceled();
    close();
}

void AuthenticationDialog::urlChanged(const QUrl &url)
{
    qDebug() << "Navigating to" << url;
    if (url.host() == QStringLiteral("oauth.vk.com") && url.path() == QStringLiteral("/blank.html"))
    {
        const QUrlQuery query(url);

        d->error = query.queryItemValue(QStringLiteral("error"));
        d->errorDescription = query.queryItemValue(QStringLiteral("error_description")).replace(QLatin1Char('+'), QLatin1Char(' '));
        if (!d->error.isEmpty() || !d->errorDescription.isEmpty())
        {
            QTimer::singleShot(0, this, SLOT(showErrorDialog()));
            return;
        }

        // The URL comes in the form "bla#access_token=bla&expires_in=foo", we need to convert from
        // # to ?
        const QUrl fixedURL = QUrl::fromUserInput(url.toString().replace(QLatin1Char('#'), QLatin1Char('?')));
        const QUrlQuery fixedQuery(fixedURL);
        const QString accessToken = fixedQuery.queryItemValue(QStringLiteral("access_token"));
        const QString tokenExpiresIn = fixedQuery.queryItemValue(QStringLiteral("expires_in")); // TODO: use this for something?
        if (!accessToken.isEmpty())
        {
            emit authenticated(accessToken);
            QTimer::singleShot(0, this, SLOT(close()));
        }
    }
}

void AuthenticationDialog::loadFinished(bool ok)
{
    if (!ok)
    {
        hide();

        KMessageBox::error(parentWidget(),
                           i18n("There was a network error when trying to authenticate with VKontakte web service."),
                           i18nc("@title:window", "Network Error"));

        emit canceled();
        close();
    }
}

} /* namespace Vkontakte */
<|endoftext|>


<commit_before>/*
  aimcontactbase.cpp  -  AIM Contact Base

  Copyright (c) 2003 by Will Stephenson
  Copyright (c) 2006 by Roman Jarosz <kedgedev@centrum.cz>
  Kopete    (c) 2002-2006 by the Kopete developers  <kopete-devel@kde.org>

  *************************************************************************
  *                                                                       *
  * This program is free software; you can redistribute it and/or modify  *
  * it under the terms of the GNU General Public License as published by  *
  * the Free Software Foundation; either version 2 of the License, or     *
  * (at your option) any later version.                                   *
  *                                                                       *
  *************************************************************************
*/
#include "aimcontactbase.h"

#include <QtXml/QDomDocument>
#include <QtXml/QDomNodeList>
#include "kopetechatsession.h"

#include "oscaraccount.h"

//liboscar
#include "oscarutils.h"

AIMContactBase::AIMContactBase( Kopete::Account* account, const QString& name, Kopete::MetaContact* parent,
                        const QString& icon, const OContact& ssiItem )
: OscarContact(account, name, parent, icon, ssiItem )
{
	m_mobile = false;
	// Set the last autoresponse time to the current time yesterday
	m_lastAutoresponseTime = QDateTime::currentDateTime().addDays(-1);
}

AIMContactBase::~AIMContactBase()
{
}

QString AIMContactBase::sanitizedMessage( const QString& message )
{
	QDomDocument doc;
	QString domError;
	int errLine = 0, errCol = 0;
	doc.setContent( message, false, &domError, &errLine, &errCol );
	if ( !domError.isEmpty() ) //error parsing, do nothing
	{
		kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "error from dom document conversion: "
			<< domError << endl;
		return message;
	}
	else
	{
		kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "conversion to dom document successful."
			<< "looking for font tags" << endl;
		QDomNodeList fontTagList = doc.elementsByTagName( "font" );
		if ( fontTagList.count() == 0 )
		{
			kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "No font tags found. Returning normal message" << endl;
			return message;
		}
		else
		{
			kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "Found font tags. Attempting replacement" << endl;
			uint numFontTags = fontTagList.count();
			for ( uint i = 0; i < numFontTags; i++ )
			{
				QDomNode fontNode = fontTagList.item(i);
				QDomElement fontEl;
				if ( !fontNode.isNull() && fontNode.isElement() )
					fontEl = fontTagList.item(i).toElement();
				else
					continue;
				if ( fontEl.hasAttribute( "back" ) )
				{
					kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "Found attribute to replace. Doing replacement" << endl;
					QString backgroundColor = fontEl.attribute( "back" );
					backgroundColor.insert( 0, "background-color: " );
					backgroundColor.append( ';' );
					fontEl.setAttribute( "style", backgroundColor );
					fontEl.removeAttribute( "back" );
				}
			}
		}
	}
	kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "sanitized message is " << doc.toString();
	return doc.toString();
}

void AIMContactBase::sendAutoResponse(Kopete::Message& msg)
{
	// The target time is 2 minutes later than the last message
	int delta = m_lastAutoresponseTime.secsTo( QDateTime::currentDateTime() );
	kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "Last autoresponse time: " << m_lastAutoresponseTime << endl;
	kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "Current time: " << QDateTime::currentDateTime() << endl;
	kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "Difference: " << delta << endl;
	// Check to see if we're past that time
	if(delta > 120)
	{
		kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "Sending auto response" << endl;

		// This code was yoinked straight from OscarContact::slotSendMsg()
		// If only that slot wasn't private, but I'm not gonna change it right now.
		Oscar::Message message;

		if ( m_details.hasCap( CAP_UTF8 ) )
		{
			message.setText( Oscar::Message::UCS2, msg.plainBody() );
		}
		else
		{
			QTextCodec* codec = contactCodec();
			message.setText( Oscar::Message::UserDefined, msg.plainBody(), codec );
		}

		message.setTimestamp( msg.timestamp() );
		message.setSender( mAccount->accountId() );
		message.setReceiver( mName );
		message.setChannel( 0x01 );

		// isAuto defaults to false
		mAccount->engine()->sendMessage( message, true);
		kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "Sent auto response" << endl;
		manager(Kopete::Contact::CanCreate)->appendMessage(msg);
		manager(Kopete::Contact::CanCreate)->messageSucceeded();
		// Update the last autoresponse time
		m_lastAutoresponseTime = QDateTime::currentDateTime();
	}
	else
	{
		kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "Not enough time since last autoresponse, NOT sending" << endl;
	}
}

void AIMContactBase::slotSendMsg(Kopete::Message& message, Kopete::ChatSession *)
{
	Oscar::Message msg;
	QString s;

	if (message.plainBody().isEmpty()) // no text, do nothing
		return;
	//okay, now we need to change the message.escapedBody from real HTML to aimhtml.
	//looking right now for docs on that "format".
	//looks like everything except for alignment codes comes in the format of spans

	//font-style:italic ->
	//font-weight:600 ->  (anything > 400 should be , 400 is not bold)
	//text-decoration:underline ->
	//font-family: ->
	//font-size:xxpt ->

	s=message.escapedBody();
	s.replace ( QRegExp( QString::fromLatin1("([^<]*)")),
	            QString::fromLatin1(""));

	s.replace ( QRegExp( QString::fromLatin1("")),
	            QString::fromLatin1(""));

	s.replace ( QRegExp( QString::fromLatin1("")),
	            QString::fromLatin1(""));

	s.replace ( QRegExp( QString::fromLatin1("")),
	            QString::fromLatin1(""));

	s.replace ( QRegExp( QString::fromLatin1("")),
	            QString::fromLatin1(""));

	s.replace ( QRegExp( QString::fromLatin1("")),
	            QString::fromLatin1(""));

	s.replace ( QRegExp( QString::fromLatin1("")),
	            QString::fromLatin1(""));

	s.replace ( QRegExp( QString::fromLatin1("")),
	            QString::fromLatin1("\\2"));

	//okay now change the  to

	//0-9 are size 1
	s.replace ( QRegExp ( QString::fromLatin1("")),
	            QString::fromLatin1(""));
	//10-11 are size 2
	s.replace ( QRegExp ( QString::fromLatin1("")),
	            QString::fromLatin1(""));
	//12-13 are size 3
	s.replace ( QRegExp ( QString::fromLatin1("")),
	            QString::fromLatin1(""));
	//14-16 are size 4
	s.replace ( QRegExp ( QString::fromLatin1("")),
	            QString::fromLatin1(""));
	//17-22 are size 5
	s.replace ( QRegExp ( QString::fromLatin1("")),
	            QString::fromLatin1(""));
	//23-29 are size 6
	s.replace ( QRegExp ( QString::fromLatin1("")),QString::fromLatin1(""));
	//30- (and any I missed) are size 7
	s.replace ( QRegExp ( QString::fromLatin1("")),QString::fromLatin1(""));

	s.replace ( QRegExp ( QString::fromLatin1("
")), QString::fromLatin1("
") );

	kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "sending " << s << endl;

	// XXX Need to check for message size?

	if ( m_details.hasCap( CAP_UTF8 ) )
		msg.setText( Oscar::Message::UCS2, s );
	else
		msg.setText( Oscar::Message::UserDefined, s, contactCodec() );

	msg.setReceiver(mName);
	msg.setTimestamp(message.timestamp());
	msg.setChannel(0x01);

	mAccount->engine()->sendMessage(msg);

	// Show the message we just sent in the chat window
	manager(Kopete::Contact::CanCreate)->appendMessage(message);
	manager(Kopete::Contact::CanCreate)->messageSucceeded();
}

#include "aimcontactbase.moc"
//kate: tab-width 4; indent-mode csands;
<commit_msg>Forward port the fix for bug 146380 to KDE 4. CCBUG: 146380<commit_after>/*
  aimcontactbase.cpp  -  AIM Contact Base

  Copyright (c) 2003 by Will Stephenson
  Copyright (c) 2006 by Roman Jarosz <kedgedev@centrum.cz>
  Kopete    (c) 2002-2006 by the Kopete developers  <kopete-devel@kde.org>

  *************************************************************************
  *                                                                       *
  * This program is free software; you can redistribute it and/or modify  *
  * it under the terms of the GNU General Public License as published by  *
  * the Free Software Foundation; either version 2 of the License, or     *
  * (at your option) any later version.                                   *
  *                                                                       *
  *************************************************************************
*/
#include "aimcontactbase.h"

#include <QtXml/QDomDocument>
#include <QtXml/QDomNodeList>
#include "kopetechatsession.h"

#include "oscaraccount.h"

//liboscar
#include "oscarutils.h"

AIMContactBase::AIMContactBase( Kopete::Account* account, const QString& name, Kopete::MetaContact* parent,
                        const QString& icon, const OContact& ssiItem )
: OscarContact(account, name, parent, icon, ssiItem )
{
	m_mobile = false;
	// Set the last autoresponse time to the current time yesterday
	m_lastAutoresponseTime = QDateTime::currentDateTime().addDays(-1);
}

AIMContactBase::~AIMContactBase()
{
}

QString AIMContactBase::sanitizedMessage( const QString& message )
{
	QDomDocument doc;
	QString domError;
	int errLine = 0, errCol = 0;
	doc.setContent( message, false, &domError, &errLine, &errCol );
	if ( !domError.isEmpty() ) //error parsing, do nothing
	{
		kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "error from dom document conversion: "
			<< domError << endl;
		return message;
	}
	else
	{
		kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "conversion to dom document successful."
			<< "looking for font tags" << endl;
		QDomNodeList fontTagList = doc.elementsByTagName( "font" );
		if ( fontTagList.count() == 0 )
		{
			kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "No font tags found. Returning normal message" << endl;
			return message;
		}
		else
		{
			kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "Found font tags. Attempting replacement" << endl;
			uint numFontTags = fontTagList.count();
			for ( uint i = 0; i < numFontTags; i++ )
			{
				QDomNode fontNode = fontTagList.item(i);
				QDomElement fontEl;
				if ( !fontNode.isNull() && fontNode.isElement() )
					fontEl = fontTagList.item(i).toElement();
				else
					continue;
				if ( fontEl.hasAttribute( "back" ) )
				{
					kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "Found attribute to replace. Doing replacement" << endl;
					QString backgroundColor = fontEl.attribute( "back" );
					backgroundColor.insert( 0, "background-color: " );
					backgroundColor.append( ';' );
					fontEl.setAttribute( "style", backgroundColor );
					fontEl.removeAttribute( "back" );
				}
			}
		}
	}
	kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "sanitized message is " << doc.toString();
	return doc.toString();
}

void AIMContactBase::sendAutoResponse(Kopete::Message& msg)
{
	// The target time is 2 minutes later than the last message
	int delta = m_lastAutoresponseTime.secsTo( QDateTime::currentDateTime() );
	kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "Last autoresponse time: " << m_lastAutoresponseTime << endl;
	kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "Current time: " << QDateTime::currentDateTime() << endl;
	kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "Difference: " << delta << endl;
	// Check to see if we're past that time
	if(delta > 120)
	{
		kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "Sending auto response" << endl;

		// This code was yoinked straight from OscarContact::slotSendMsg()
		// If only that slot wasn't private, but I'm not gonna change it right now.
		Oscar::Message message;

		if ( m_details.hasCap( CAP_UTF8 ) )
		{
			message.setText( Oscar::Message::UCS2, msg.plainBody() );
		}
		else
		{
			QTextCodec* codec = contactCodec();
			message.setText( Oscar::Message::UserDefined, msg.plainBody(), codec );
		}

		message.setTimestamp( msg.timestamp() );
		message.setSender( mAccount->accountId() );
		message.setReceiver( mName );
		message.setChannel( 0x01 );

		// isAuto defaults to false
		mAccount->engine()->sendMessage( message, true);
		kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "Sent auto response" << endl;
		manager(Kopete::Contact::CanCreate)->appendMessage(msg);
		manager(Kopete::Contact::CanCreate)->messageSucceeded();
		// Update the last autoresponse time
		m_lastAutoresponseTime = QDateTime::currentDateTime();
	}
	else
	{
		kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "Not enough time since last autoresponse, NOT sending" << endl;
	}
}

void AIMContactBase::slotSendMsg(Kopete::Message& message, Kopete::ChatSession *)
{
	Oscar::Message msg;
	QString s;

	if (message.plainBody().isEmpty()) // no text, do nothing
		return;
	//okay, now we need to change the message.escapedBody from real HTML to aimhtml.
	//looking right now for docs on that "format".
	//looks like everything except for alignment codes comes in the format of spans

	//font-style:italic ->
	//font-weight:600 ->  (anything > 400 should be , 400 is not bold)
	//text-decoration:underline ->
	//font-family: ->
	//font-size:xxpt ->

	s=message.escapedBody();
	s.replace ( QRegExp( QString::fromLatin1("([^<]*)")),
	            QString::fromLatin1(""));

	s.replace ( QRegExp( QString::fromLatin1("")),
	            QString::fromLatin1(""));

	s.replace ( QRegExp( QString::fromLatin1("")),
	            QString::fromLatin1(""));

	s.replace ( QRegExp( QString::fromLatin1("")),
	            QString::fromLatin1(""));

	s.replace ( QRegExp( QString::fromLatin1("")),
	            QString::fromLatin1(""));

	s.replace ( QRegExp( QString::fromLatin1("")),
	            QString::fromLatin1(""));

	s.replace ( QRegExp( QString::fromLatin1("")),
	            QString::fromLatin1(""));

	s.replace ( QRegExp( QString::fromLatin1("")),
	            QString::fromLatin1("\\2"));

	//okay now change the  to

	//0-9 are size 1
	s.replace ( QRegExp ( QString::fromLatin1("")),
	            QString::fromLatin1(""));
	//10-11 are size 2
	s.replace ( QRegExp ( QString::fromLatin1("")),
	            QString::fromLatin1(""));
	//12-13 are size 3
	s.replace ( QRegExp ( QString::fromLatin1("")),
	            QString::fromLatin1(""));
	//14-16 are size 4
	s.replace ( QRegExp ( QString::fromLatin1("")),
	            QString::fromLatin1(""));
	//17-22 are size 5
	s.replace ( QRegExp ( QString::fromLatin1("")),
	            QString::fromLatin1(""));
	//23-29 are size 6
	s.replace ( QRegExp ( QString::fromLatin1("")),QString::fromLatin1(""));
	//30- (and any I missed) are size 7
	s.replace ( QRegExp ( QString::fromLatin1("")),QString::fromLatin1(""));

	s.replace ( QRegExp ( QString::fromLatin1("
")), QString::fromLatin1("
") );

	s.remove ( QRegExp ( QString::fromLatin1("
$") ) );

	kDebug(OSCAR_GEN_DEBUG) << k_funcinfo << "sending " << s << endl;

	// XXX Need to check for message size?

	if ( m_details.hasCap( CAP_UTF8 ) )
		msg.setText( Oscar::Message::UCS2, s );
	else
		msg.setText( Oscar::Message::UserDefined, s, contactCodec() );

	msg.setReceiver(mName);
	msg.setTimestamp(message.timestamp());
	msg.setChannel(0x01);

	mAccount->engine()->sendMessage(msg);

	// Show the message we just sent in the chat window
	manager(Kopete::Contact::CanCreate)->appendMessage(message);
	manager(Kopete::Contact::CanCreate)->messageSucceeded();
}

#include "aimcontactbase.moc"
//kate: tab-width 4; indent-mode csands;
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include "WindowEvaluator.hpp"
#include "SystemState.hpp"
#include <stdlib.h>

using namespace Geometry2d;

// Places a robot on the field that counts as an obstacle to the window
// evaluator, but is not actuallly in the way.  Should return one segment as
// the result.
TEST(WindowEvaluator, eval_pt_to_pt) {
    SystemState state;

    float w = Field_Dimensions::Current_Dimensions.Width();
    float l = Field_Dimensions::Current_Dimensions.Length();

    srand(10);
    for (int i = 0; i < 6; i++) {
        state.self[i]->pos = Point(rand() * w - w/2, rand() * l);
        state.self[i]->visible = true;
    }

    Point ourGoalCenter(0, 0);
    int num_w = 500;
    int num_l = 1000;

    for (float x = -w/2; x < w/2; x += w/num_w) {
        for (float y = 0; y < l; y += l/num_l) {
            WindowEvaluator winEval(&state);
            WindowingResult result = winEval.eval_pt_to_pt(Point(x, y), ourGoalCenter, .2);
        }
    }

    EXPECT_EQ(0, 0);
}
<commit_msg>Reverted Win_Eval Test<commit_after>#include <gtest/gtest.h>
#include "WindowEvaluator.hpp"
#include "SystemState.hpp"
#include "Configuration.hpp"

using namespace Geometry2d;

Configuration config;

// Places a robot on the field that counts as an obstacle to the window
// evaluator, but is not actuallly in the way.  Should return one segment as
// the result.
TEST(WindowEvaluator, eval_pt_to_seg) {
    SystemState state;
    OurRobot* obstacleBot = state.self[0];
    obstacleBot->visible = true;
    obstacleBot->pos = Point(1, 1);

    Segment ourGoalSegment(
        Point(Field_Dimensions::Current_Dimensions.GoalWidth() / 2.0, 0),
        Point(-Field_Dimensions::Current_Dimensions.GoalWidth() / 2.0, 0));

    WindowEvaluator winEval(&state);
    WindowingResult result =
        winEval.eval_pt_to_seg(Point(1, 2), ourGoalSegment);

    auto& windows = result.first;
    auto& best = result.second;

    // there should be a best window, there's nothing in the way
    EXPECT_NE(boost::none, best);

    // there should only be one window
    EXPECT_EQ(1, windows.size());

    // the window should be our goal segment
    EXPECT_EQ(ourGoalSegment, windows[0].segment);
}
<|endoftext|>


<commit_before>#include "BallFilter.hpp"
#include "BallTracker.hpp"

#include <SystemState.hpp>

#include <stdio.h>

using namespace Geometry2d;

static const float Velocity_Alpha = 0.05;

BallFilter::BallFilter() {}

void BallFilter::updateEstimate(const BallObservation& obs) {
    RJ::Seconds dtime = (obs.time - _currentEstimate.time);
    Point newVel = (obs.pos - _currentEstimate.pos) / dtime.count();

    _currentEstimate.valid = true;
    _currentEstimate.pos = obs.pos;
    _currentEstimate.vel = newVel * Velocity_Alpha +
                           _currentEstimate.vel * (1.0f - Velocity_Alpha);
    _currentEstimate.time = obs.time;
}

Ball BallFilter::predict(RJ::Time time, float* velocityUncertainty) const {
    Ball prediction{};

    RJ::Seconds t = time - _currentEstimate.time;

    const auto& vel = _currentEstimate.vel;
    const auto& pos = _currentEstimate.pos;
    const auto s0 = vel.mag();
    auto part = std::exp(-0.2913f * t.count());
    auto speed = s0 * part;
    auto distance = s0 * -3.43289f * (part - 1.0f);

    prediction.time = time;
    prediction.valid = true;
    prediction.pos = pos + vel.normalized(distance);
    prediction.vel = vel.normalized(speed);

    if (velocityUncertainty) {
        *velocityUncertainty = 2.0f + _currentEstimate.vel.mag() * 0.5f;
    }
    return prediction;
}
<commit_msg>Update Ball Filter<commit_after>#include "BallFilter.hpp"
#include "BallTracker.hpp"

#include <SystemState.hpp>

#include <stdio.h>

using namespace Geometry2d;

static const float Velocity_Alpha = 0.05;

BallFilter::BallFilter() {}

void BallFilter::updateEstimate(const BallObservation& obs) {
    RJ::Seconds dtime = (obs.time - _currentEstimate.time);
    Point newVel = (obs.pos - _currentEstimate.pos) / dtime.count();

    _currentEstimate.valid = true;
    _currentEstimate.pos = obs.pos;
    _currentEstimate.vel = newVel * Velocity_Alpha +
                           _currentEstimate.vel * (1.0f - Velocity_Alpha);
    _currentEstimate.time = obs.time;
}

Ball BallFilter::predict(RJ::Time time, float* velocityUncertainty) const {
    Ball prediction{};

    RJ::Seconds t = time - _currentEstimate.time;

    const auto& vel = _currentEstimate.vel;
    const auto& pos = _currentEstimate.pos;
    const auto s0 = vel.mag();

//    const auto decayConstant = 0.1735;
    const auto decayConstant = 0.1795;

//    auto part = std::exp(-0.2913f * t.count());
    // vel = v0 - t*Constant
    // 0 = v0 - t * C
    // t*C = v0
    // t = v0/C

    // d = v0t - 1/2*t^2*Constant

    double speed=0;
    double distance=0;
    if (s0 != 0) {
        auto maxTime = s0/decayConstant;
        if (t.count() >= maxTime) {
            speed = 0;
            distance = s0 * maxTime - pow(maxTime, 2) / 2.0 * decayConstant;
        } else {
            speed = s0 - (t.count() * decayConstant);
            distance = s0 * t.count() - pow(t.count(), 2) / 2.0 * decayConstant;
        }
    } else {
        speed = 0;
        distance = 0;
    }

    prediction.time = time;
    prediction.valid = true;
    prediction.pos = pos + vel.normalized(distance);
    prediction.vel = vel.normalized(speed);

    if (velocityUncertainty) {
        *velocityUncertainty = 2.0f + _currentEstimate.vel.mag() * 0.5f;
    }

    return prediction;
}
<|endoftext|>


<commit_before>/**
 * @file
 */
#include "libbirch/Counted.hpp"

bi::Counted::Counted() :
    sharedCount(0u),
    weakCount(1u),
    memoCount(0u),
    size(0u),
    frozen(false) {
  //
}

bi::Counted::Counted(const Counted& o) :
    sharedCount(0u),
    weakCount(1u),
    memoCount(0u),
    size(o.size),
    frozen(false) {
  //
}

bi::Counted::~Counted() {
  assert(sharedCount == 0u);
}

void bi::Counted::deallocate() {
  assert(sharedCount == 0u);
  assert(weakCount == 0u);
  bi::deallocate(this, size);
}

unsigned bi::Counted::getSize() const {
  return size;
}

bi::Counted* bi::Counted::lock() {
  unsigned count = sharedCount;
  while (count > 0u
      && !sharedCount.compare_exchange_weak(count, count + 1u,
          std::memory_order_relaxed)) {
    //
  }
  return count > 0u ? this : nullptr;
}

void bi::Counted::incShared() {
  sharedCount.fetch_add(1u, std::memory_order_relaxed);
}

void bi::Counted::decShared() {
  assert(sharedCount > 0u);
  if (sharedCount.fetch_sub(1u, std::memory_order_relaxed) - 1u == 0u
      && size > 0u) {
    // ^ size == 0u during construction, never destroy in that case
    destroy();
    decWeak();  // release weak self-reference
  }
}

unsigned bi::Counted::numShared() const {
  return sharedCount;
}

void bi::Counted::incWeak() {
  weakCount.fetch_add(1u, std::memory_order_relaxed);
}

void bi::Counted::decWeak() {
  assert(weakCount > 0u);
  if (weakCount.fetch_sub(1u, std::memory_order_relaxed) - 1u == 0u) {
    assert(sharedCount == 0u);
    // ^ because of weak self-reference, the weak count should not expire
    //   before the shared count
    deallocate();
  }
}

unsigned bi::Counted::numWeak() const {
  return weakCount;
}

void bi::Counted::incMemo() {
  /* the order of operations here is important, as the weak count should
   * never be less than the memo count */
  incWeak();
  memoCount.fetch_add(1u, std::memory_order_relaxed);
}

void bi::Counted::decMemo() {
  /* the order of operations here is important, as the weak count should
   * never be less than the memo count */
  assert(memoCount > 0u);
  memoCount.fetch_sub(1u, std::memory_order_relaxed);
  decWeak();
}

bool bi::Counted::isReachable() const {
  return sharedCount.load(std::memory_order_relaxed) > 0u
      || weakCount.load(std::memory_order_relaxed)
          > memoCount.load(std::memory_order_relaxed);
}

bool bi::Counted::isFrozen() const {
  return frozen.load(std::memory_order_relaxed);
}

void bi::Counted::freeze() {
  bool expected = false;
  bool desired = true;
  if (frozen.compare_exchange_strong(expected, desired,
      std::memory_order_relaxed)) {
    doFreeze();
  }
}

void bi::Counted::doFreeze() {
  //
}
<commit_msg>Updated atomic memory order in Counted.<commit_after>/**
 * @file
 */
#include "libbirch/Counted.hpp"

bi::Counted::Counted() :
    sharedCount(0u),
    weakCount(1u),
    memoCount(0u),
    size(0u),
    frozen(false) {
  //
}

bi::Counted::Counted(const Counted& o) :
    sharedCount(0u),
    weakCount(1u),
    memoCount(0u),
    size(o.size),
    frozen(false) {
  //
}

bi::Counted::~Counted() {
  assert(sharedCount == 0u);
}

void bi::Counted::deallocate() {
  assert(sharedCount == 0u);
  assert(weakCount == 0u);
  bi::deallocate(this, size);
}

unsigned bi::Counted::getSize() const {
  return size;
}

bi::Counted* bi::Counted::lock() {
  unsigned count = sharedCount.load(std::memory_order_acquire);
  while (count > 0u
      && !sharedCount.compare_exchange_weak(count, count + 1u,
          std::memory_order_release)) {
    //
  }
  return count > 0u ? this : nullptr;
}

void bi::Counted::incShared() {
  sharedCount.fetch_add(1u, std::memory_order_relaxed);
}

void bi::Counted::decShared() {
  assert(sharedCount > 0u);
  if (sharedCount.fetch_sub(1u, std::memory_order_relaxed) - 1u == 0u
      && size > 0u) {
    // ^ size == 0u during construction, never destroy in that case
    destroy();
    decWeak();  // release weak self-reference
  }
}

unsigned bi::Counted::numShared() const {
  return sharedCount;
}

void bi::Counted::incWeak() {
  weakCount.fetch_add(1u, std::memory_order_relaxed);
}

void bi::Counted::decWeak() {
  assert(weakCount > 0u);
  if (weakCount.fetch_sub(1u, std::memory_order_relaxed) - 1u == 0u) {
    assert(sharedCount == 0u);
    // ^ because of weak self-reference, the weak count should not expire
    //   before the shared count
    deallocate();
  }
}

unsigned bi::Counted::numWeak() const {
  return weakCount;
}

void bi::Counted::incMemo() {
  /* the order of operations here is important, as the weak count should
   * never be less than the memo count */
  incWeak();
  memoCount.fetch_add(1u, std::memory_order_relaxed);
}

void bi::Counted::decMemo() {
  /* the order of operations here is important, as the weak count should
   * never be less than the memo count */
  assert(memoCount > 0u);
  memoCount.fetch_sub(1u, std::memory_order_relaxed);
  decWeak();
}

bool bi::Counted::isReachable() const {
  return sharedCount.load(std::memory_order_relaxed) > 0u
      || weakCount.load(std::memory_order_relaxed)
          > memoCount.load(std::memory_order_relaxed);
}

bool bi::Counted::isFrozen() const {
  return frozen.load(std::memory_order_relaxed);
}

void bi::Counted::freeze() {
  bool expected = false;
  bool desired = true;
  if (frozen.compare_exchange_strong(expected, desired,
      std::memory_order_relaxed)) {
    doFreeze();
  }
}

void bi::Counted::doFreeze() {
  //
}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include <algorithm>
#include <memory>
#include <OleAuto.h>//<OAIdl.h>

//VBA比較関数型  vbCompFunc  の宣言 (VBCallbackFuncと同一)
//VBAにおけるシグネチャは
// Function comp(ByRef elem As Variant, ByRef dummy As Variant) As Variant
typedef VARIANT (__stdcall *vbCompFunc)(VARIANT*, VARIANT*);

__int32 __stdcall Dimension(const VARIANT* pv);
void safeArrayBounds(SAFEARRAY* pArray, UINT dim, SAFEARRAYBOUND bounds[]);

class compareByVBAfunc   {
    VARIANT*    begin;
    vbCompFunc  comp;
public:
    compareByVBAfunc(VARIANT* pA, vbCompFunc f) : begin(pA), comp(f) { }
    bool operator ()(__int32 i, __int32 j) const
    {
        return (*comp)(begin + i, begin + j).lVal ? true: false;
    }
};

//1次元昇順
class compFunctor  {
    VARIANT*    begin;
public:
    compFunctor(VARIANT* pA) : begin(pA) { }
    bool operator ()(__int32 i, __int32 j) const
    {
        return VARCMP_LT == VarCmp(begin + i, begin + j, LANG_JAPANESE, 0);
    }
};

//2次元昇順
class compDictionaryFunctor  {
    VARIANT*    begin;
    void set(__int32 k, SAFEARRAY*&  pArray, SAFEARRAYBOUND& bound) const
    {
        if ( 1 == Dimension(begin + k) )
        {
            pArray = ( 0 == (VT_BYREF & begin[k].vt) )?  (begin[k].parray): (*begin[k].pparray);
            safeArrayBounds(pArray, 1, &bound);
        }
        else
        {
            pArray = nullptr;
        }
    }
public:
    compDictionaryFunctor(VARIANT* pA) : begin(pA) { }
    bool operator ()(__int32 i, __int32 j) const
    {
        SAFEARRAY*  pArray1, *pArray2;
        SAFEARRAYBOUND bound1, bound2;
        set(i, pArray1, bound1);
        set(j, pArray2, bound2);
        if ( pArray1 == nullptr || pArray2 == nullptr )     return false;
        VARIANT Var1, Var2;
        for ( ULONG k = 0; k < bound1.cElements && k < bound2.cElements; ++k )
        {
            auto index1 = static_cast<LONG>(k + bound1.lLbound);
            auto index2 = static_cast<LONG>(k + bound2.lLbound);
            ::SafeArrayGetElement(pArray1, &index1, &Var1);
            ::SafeArrayGetElement(pArray2, &index2, &Var2);
            if ( VARCMP_LT == VarCmp(&Var1, &Var2, LANG_JAPANESE, 0) )
                return true;
            if ( VARCMP_LT == VarCmp(&Var2, &Var1, LANG_JAPANESE, 0) )
                return false;
        }
        return false;
    }
};

VARIANT __stdcall stdsort(VARIANT* array, __int32 pComp)
{
    VARIANT      ret;
    ::VariantInit(&ret);
    if ( 1 != Dimension(array) )            return ret;
    SAFEARRAY* pArray = ( 0 == (VT_BYREF & array->vt) )?  (array->parray): (*array->pparray);
    SAFEARRAYBOUND bound = {1, 0};   //要素数、LBound
    safeArrayBounds(pArray, 1, &bound);
	std::unique_ptr<__int32[]>	index(new __int32[bound.cElements]);
    std::unique_ptr<VARIANT[]>	VArray(new VARIANT[bound.cElements]);
	for ( ULONG i = 0; i < bound.cElements; ++i )
    {
		index[i] = static_cast<__int32>(i);
        auto j = static_cast<LONG>(i + bound.lLbound);
        ::SafeArrayGetElement(pArray, &j, &VArray[i]);
    }
    if ( 0 < pComp )
    {
        compareByVBAfunc functor(VArray.get(), reinterpret_cast<vbCompFunc>(pComp));
        std::sort(index.get(), index.get() + bound.cElements, functor);
    }
    else if ( -1 == pComp ) //1次元昇順
    {
        compFunctor   functor(VArray.get());
        std::sort(index.get(), index.get() + bound.cElements, functor);
    }
    else if ( -2 == pComp  ) //2次元昇順
    {
        compDictionaryFunctor   functor(VArray.get());
        std::sort(index.get(), index.get() + bound.cElements, functor);
    }
    //-------------------------------------------------------
    SAFEARRAYBOUND boundRet = { bound.cElements, 0};   //要素数、LBound
    SAFEARRAY* retArray = ::SafeArrayCreate(VT_VARIANT, 1, &boundRet);
    VARIANT elem;
    ::VariantInit(&elem);
    elem.vt = VT_I4;
	for ( LONG i = 0; i < static_cast<LONG>(bound.cElements); ++i )
    {
        elem.lVal = index[i];
        ::SafeArrayPutElement(retArray, &i, &elem);
    }
    ret.vt = VT_ARRAY | VT_VARIANT;
    ret.parray = retArray;
    return      ret;
}
<commit_msg>ソートとlower_bound等<commit_after>#include "stdafx.h"
#include <algorithm>
#include <memory>
#include <OleAuto.h>//<OAIdl.h>

//VBA比較関数型  vbCompFunc  の宣言 (VBCallbackFuncと同一)
//VBAにおけるシグネチャは
// Function comp(ByRef elem As Variant, ByRef dummy As Variant) As Variant
typedef VARIANT (__stdcall *vbCompFunc)(VARIANT*, VARIANT*);

__int32 __stdcall Dimension(const VARIANT* pv);
void safeArrayBounds(SAFEARRAY* pArray, UINT dim, SAFEARRAYBOUND bounds[]);

class compareByVBAfunc   {
    VARIANT*    begin;
    vbCompFunc  comp;
public:
    compareByVBAfunc(VARIANT* pA, vbCompFunc f) : begin(pA), comp(f) { }
    bool operator ()(__int32 i, __int32 j) const
    {
        return (*comp)(begin + i, begin + j).lVal ? true: false;
    }
};

//1次元昇順
class compFunctor  {
    VARIANT*    begin;
public:
    compFunctor(VARIANT* pA) : begin(pA) { }
    bool operator ()(__int32 i, __int32 j) const
    {
        return VARCMP_LT == VarCmp(begin + i, begin + j, LANG_JAPANESE, 0);
    }
};

//2次元昇順
class compDictionaryFunctor  {
    VARIANT*    begin;
    void set(__int32 k, SAFEARRAY*&  pArray, SAFEARRAYBOUND& bound) const
    {
        if ( 1 == Dimension(begin + k) )
        {
            pArray = ( 0 == (VT_BYREF & begin[k].vt) )?  (begin[k].parray): (*begin[k].pparray);
            safeArrayBounds(pArray, 1, &bound);
        }
        else
        {
            pArray = nullptr;
        }
    }
public:
    compDictionaryFunctor(VARIANT* pA) : begin(pA) { }
    bool operator ()(__int32 i, __int32 j) const
    {
        SAFEARRAY*  pArray1, *pArray2;
        SAFEARRAYBOUND bound1, bound2;
        set(i, pArray1, bound1);
        set(j, pArray2, bound2);
        if ( pArray1 == nullptr || pArray2 == nullptr )     return false;
        VARIANT Var1, Var2;
        for ( ULONG k = 0; k < bound1.cElements && k < bound2.cElements; ++k )
        {
            auto index1 = static_cast<LONG>(k + bound1.lLbound);
            auto index2 = static_cast<LONG>(k + bound2.lLbound);
            ::SafeArrayGetElement(pArray1, &index1, &Var1);
            ::SafeArrayGetElement(pArray2, &index2, &Var2);
            if ( VARCMP_LT == VarCmp(&Var1, &Var2, LANG_JAPANESE, 0) )
                return true;
            if ( VARCMP_LT == VarCmp(&Var2, &Var1, LANG_JAPANESE, 0) )
                return false;
        }
        return false;
    }
};

VARIANT __stdcall stdsort(VARIANT* array, __int32 pComp)
{
    VARIANT      ret;
    ::VariantInit(&ret);
    if ( 1 != Dimension(array) )            return ret;
    SAFEARRAY* pArray = ( 0 == (VT_BYREF & array->vt) )?  (array->parray): (*array->pparray);
    SAFEARRAYBOUND bound = {1, 0};   //要素数、LBound
    safeArrayBounds(pArray, 1, &bound);
    std::unique_ptr<__int32[]>	index(new __int32[bound.cElements]);
    std::unique_ptr<VARIANT[]>	VArray(new VARIANT[bound.cElements]);
    for ( ULONG i = 0; i < bound.cElements; ++i )
    {
        index[i] = static_cast<__int32>(i);
        auto j = static_cast<LONG>(i + bound.lLbound);
        ::SafeArrayGetElement(pArray, &j, &VArray[i]);
    }
    if ( 0 < pComp )
    {
        compareByVBAfunc functor(VArray.get(), reinterpret_cast<vbCompFunc>(pComp));
        std::sort(index.get(), index.get() + bound.cElements, functor);
    }
    else if ( -1 == pComp ) //1次元昇順
    {
        compFunctor   functor(VArray.get());
        std::sort(index.get(), index.get() + bound.cElements, functor);
    }
    else if ( -2 == pComp  ) //2次元昇順
    {
        compDictionaryFunctor   functor(VArray.get());
        std::sort(index.get(), index.get() + bound.cElements, functor);
    }
    //-------------------------------------------------------
    SAFEARRAYBOUND boundRet = { bound.cElements, 0};   //要素数、LBound
    SAFEARRAY* retArray = ::SafeArrayCreate(VT_VARIANT, 1, &boundRet);
    VARIANT elem;
    ::VariantInit(&elem);
    elem.vt = VT_I4;
    for ( LONG i = 0; i < static_cast<LONG>(bound.cElements); ++i )
    {
        elem.lVal = index[i];
        ::SafeArrayPutElement(retArray, &i, &elem);
    }
    ret.vt = VT_ARRAY | VT_VARIANT;
    ret.parray = retArray;
    return      ret;
}
<|endoftext|>