<commit_before>/*
   Copyright (C) 2017 Alexandr Akulich <akulichalexander@gmail.com>

   This file is a part of TelegramQt library.

   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) any later version.

   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.

 */

#include "TelegramServerConfig.hpp"
#include "TelegramServerUser.hpp"
#include "DcConfiguration.hpp"
#include "LocalCluster.hpp"
#include "Session.hpp"

#include "Utils.hpp"
#include <QCoreApplication>
#include <QDebug>
#include <QStandardPaths>

using namespace Telegram::Server;

#ifdef USE_DBUS_NOTIFIER
#include <QDBusConnection>
#include <QDBusMessage>
#include "DefaultAuthorizationProvider.hpp"

class DBusCodeAuthProvider : public Authorization::DefaultProvider
{
protected:
    Authorization::Code generateCode(Session *session, const QString &identifier) override;
};

Authorization::Code DBusCodeAuthProvider::generateCode(Session *session, const QString &identifier)
{
    Authorization::Code code = DefaultProvider::generateCode(session, identifier);
    QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.Notifications"),
                                                          QStringLiteral("/org/freedesktop/Notifications"),
                                                          QStringLiteral("org.freedesktop.Notifications"),
                                                          QStringLiteral("Notify"));
    message.setArguments({
                             QCoreApplication::applicationName(),
                             QVariant::fromValue(0u),
                             QString(),
                             QStringLiteral("New auth code request"),
                             QStringLiteral("Auth code for account %1 is %2. Peer IP: %3").arg(identifier, code.code, session->ip),
                             QStringList(),
                             QVariantMap(),
                             3000
                         });

    // QString app_name, uint replaces_id, QString app_icon, QString summary,
    // QString body, QStringList actions, QVariantMap hints, int timeout
    QDBusConnection::sessionBus().send(message);
    return code;
}
#endif // USE_DBUS_NOTIFIER

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    a.setOrganizationName(QStringLiteral("TelegramQt"));
    a.setApplicationName(QStringLiteral("TelegramQt Server"));
    Telegram::initialize();

    Config config;
    if (!config.load()) {
        // create "default" config file to ease editing
        config.save();
    }

    const Telegram::RsaKey key = Telegram::RsaKey::fromFile(config.privateKeyFile());
    if (!key.isValid()) {
        qCritical() << "Unable to read RSA key. Please read README.md for more information.";
        return -1;
    }

    LocalCluster cluster;
    cluster.setServerPrivateRsaKey(key);
    cluster.setServerConfiguration(config.serverConfiguration());

#ifdef USE_DBUS_NOTIFIER
    DBusCodeAuthProvider authProvider;
    cluster.setAuthorizationProvider(&authProvider);
    qInfo() << "DBus auth code provider enabled";
#endif

    cluster.start();

    return a.exec();
}
<commit_msg>Server: add command line option to specify config location<commit_after>/*
   Copyright (C) 2017 Alexandr Akulich <akulichalexander@gmail.com>

   This file is a part of TelegramQt library.

   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) any later version.

   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.

 */

#include "TelegramServerConfig.hpp"
#include "TelegramServerUser.hpp"
#include "DcConfiguration.hpp"
#include "LocalCluster.hpp"
#include "Session.hpp"

#include "Utils.hpp"
#include <QCoreApplication>
#include <QDebug>
#include <QStandardPaths>
#include <QCommandLineParser>

using namespace Telegram::Server;

#ifdef USE_DBUS_NOTIFIER
#include <QDBusConnection>
#include <QDBusMessage>
#include "DefaultAuthorizationProvider.hpp"

class DBusCodeAuthProvider : public Authorization::DefaultProvider
{
protected:
    Authorization::Code generateCode(Session *session, const QString &identifier) override;
};

Authorization::Code DBusCodeAuthProvider::generateCode(Session *session, const QString &identifier)
{
    Authorization::Code code = DefaultProvider::generateCode(session, identifier);
    QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.Notifications"),
                                                          QStringLiteral("/org/freedesktop/Notifications"),
                                                          QStringLiteral("org.freedesktop.Notifications"),
                                                          QStringLiteral("Notify"));
    message.setArguments({
                             QCoreApplication::applicationName(),
                             QVariant::fromValue(0u),
                             QString(),
                             QStringLiteral("New auth code request"),
                             QStringLiteral("Auth code for account %1 is %2. Peer IP: %3").arg(identifier, code.code, session->ip),
                             QStringList(),
                             QVariantMap(),
                             3000
                         });

    // QString app_name, uint replaces_id, QString app_icon, QString summary,
    // QString body, QStringList actions, QVariantMap hints, int timeout
    QDBusConnection::sessionBus().send(message);
    return code;
}
#endif // USE_DBUS_NOTIFIER

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    a.setOrganizationName(QStringLiteral("TelegramQt"));
    a.setApplicationName(QStringLiteral("TelegramQt Server"));

    Telegram::initialize();

    QCommandLineParser parser;
    parser.addHelpOption();

    QCommandLineOption configFileOption(QStringList{ QStringLiteral("c"), QStringLiteral("config") });
    configFileOption.setDescription(QStringLiteral("Path to config file"));
    configFileOption.setValueName(QStringLiteral("configFilePath"));
    parser.addOption(configFileOption);

    parser.process(a);

    // where to load config file from?
    QString configFilePath;
    if (parser.isSet(configFileOption)) {
        configFilePath = parser.value(configFileOption);
    }

    // Load config
    Config config(configFilePath);
    if (!config.load()) {
        // create "default" config file to ease editing
        config.save();
    }

    const Telegram::RsaKey key = Telegram::RsaKey::fromFile(config.privateKeyFile());
    if (!key.isValid()) {
        qCritical() << "Unable to read RSA key. Please read README.md for more information.";
        return -1;
    }

    LocalCluster cluster;
    cluster.setServerPrivateRsaKey(key);
    cluster.setServerConfiguration(config.serverConfiguration());

#ifdef USE_DBUS_NOTIFIER
    DBusCodeAuthProvider authProvider;
    cluster.setAuthorizationProvider(&authProvider);
    qInfo() << "DBus auth code provider enabled";
#endif

    cluster.start();

    return a.exec();
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <config_folders.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "liblibreoffice.h"

#include <tools/errinf.hxx>
#include <osl/file.hxx>
#include <osl/process.h>
#include <rtl/strbuf.hxx>
#include <rtl/bootstrap.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <comphelper/processfactory.hxx>

#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/frame/Desktop.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/lang/Locale.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/ucb/XContentProvider.hpp>
#include <com/sun/star/ucb/XUniversalContentBroker.hpp>

#include <vcl/svapp.hxx>
#include <tools/resmgr.hxx>
#include <vcl/graphicfilter.hxx>
#include <unotools/syslocaleoptions.hxx>

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

class LibLODocument_Impl;
class LibLibreOffice_Impl;

static LibLibreOffice_Impl *gImpl = NULL;

typedef struct {
    const char *extn;
    const char *filterName;
} ExtensionMap;

static const ExtensionMap
aWriterExtensionMap[] = {
    { "doc",   "MS Word 97" },
    { "docx",  "MS Word 2007 XML" },
    { "fodt",  "OpenDocument Text Flat XML" },
    { "html",  "HTML (StarWriter)" },
    { "odt",   "writer8" },
    { "ott",   "writer8_template" },
    { "pdf",   "writer_pdf_Export" },
    { "txt",   "Text" },
    { "xhtml", "XHTML Writer File" },
    { NULL, NULL }
};

static const ExtensionMap
aCalcExtensionMap[] = {
    { "csv",   "Text - txt - csv (StarCalc)" },
    { "fods",  "OpenDocument Spreadsheet Flat XML" },
    { "html",  "HTML (StarCalc)" },
    { "ods",   "calc8" },
    { "ots",   "calc8_template" },
    { "pdf",   "calc_pdf_Export" },
    { "xhtml", "XHTML Calc File" },
    { "xls",   "MS Excel 97" },
    { "xlsx",  "Calc MS Excel 2007 XML" },
    { NULL, NULL }
};

static const ExtensionMap
aImpressExtensionMap[] = {
    { "fodp",  "OpenDocument Presentation Flat XML" },
    { "html",  "impress_html_Export" },
    { "odg",   "impress8_draw" },
    { "odp",   "impress8" },
    { "otp",   "impress8_template" },
    { "pdf",   "impress_pdf_Export" },
    { "potm",  "Impress MS PowerPoint 2007 XML Template" },
    { "pot",   "MS PowerPoint 97 Vorlage" },
    { "pptx",  "Impress MS PowerPoint 2007 XML" },
    { "pps",   "MS PowerPoint 97 Autoplay" },
    { "ppt",   "MS PowerPoint 97" },
    { "svg",   "impress_svg_Export" },
    { "swf",   "impress_flash_Export" },
    { "xhtml", "XHTML Impress File" },
    { NULL, NULL }
};

extern "C" {

SAL_DLLPUBLIC_EXPORT LibreOffice *liblibreoffice_hook(void);

static void doc_destroy( LibreOfficeDocument *pThis );
static int  doc_saveAs( LibreOfficeDocument *pThis, const char *pUrl, const char *pFormat );

struct LibLODocument_Impl : public _LibreOfficeDocument
{
    uno::Reference < css::lang::XComponent > mxComponent;

    LibLODocument_Impl( const uno::Reference < css::lang::XComponent > &xComponent )
            : mxComponent( xComponent )
    {
        nSize = sizeof( LibreOffice );

        destroy = doc_destroy;
        saveAs = doc_saveAs;
    }
};

static void doc_destroy( LibreOfficeDocument *pThis )
{
    LibLODocument_Impl *pDocument = static_cast< LibLODocument_Impl *>( pThis );
    delete pDocument;
}

static void                 lo_destroy       (LibreOffice *pThis);
static int                  lo_initialize    (LibreOffice *pThis,
                                              const char *pInstallPath);
static LibreOfficeDocument *lo_documentLoad  (LibreOffice *pThis,
                                              const char *pURL);
static char *               lo_getError      (LibreOffice *pThis);

struct LibLibreOffice_Impl : public _LibreOffice
{
    rtl::OUString maLastExceptionMsg;

    LibLibreOffice_Impl()
    {
        nSize = sizeof( LibreOfficeDocument );

        destroy = lo_destroy;
        initialize = lo_initialize;
        documentLoad = lo_documentLoad;
        getError = lo_getError;
    }
};

// Wonder global state ...
static uno::Reference<css::uno::XComponentContext> xContext;
static uno::Reference<css::lang::XMultiServiceFactory> xSFactory;
static uno::Reference<css::lang::XMultiComponentFactory> xFactory;

static OUString getUString( const char *str )
{
    if( !str )
        return OUString( "" );
    return OStringToOUString( OString( str, strlen (str) ),
                              RTL_TEXTENCODING_UTF8 );
}

// Try to convert a relative URL to an absolute one
static OUString getAbsoluteURL( const char *pURL )
{
    OUString aURL( getUString( pURL ) );
    OUString sAbsoluteDocUrl, sWorkingDir, sDocPathUrl;

    // FIXME: this would appear to kill non-file URLs.
    osl_getProcessWorkingDir(&sWorkingDir.pData);
    osl::FileBase::getFileURLFromSystemPath( aURL, sDocPathUrl );
    osl::FileBase::getAbsoluteFileURL(sWorkingDir, sDocPathUrl, sAbsoluteDocUrl);

    return sAbsoluteDocUrl;
}

static LibreOfficeDocument *
lo_documentLoad( LibreOffice *pThis, const char *pURL )
{
    LibLibreOffice_Impl *pLib = static_cast< LibLibreOffice_Impl *>( pThis );

    OUString aURL = getAbsoluteURL( pURL );

    uno::Reference < css::frame::XDesktop2 > xComponentLoader =
            css::frame::Desktop::create(xContext);

    pLib->maLastExceptionMsg = "";
    try {
        uno::Reference < css::lang::XComponent > xComponent =
            xComponentLoader->loadComponentFromURL(
                aURL, OUString("_blank"), 0,
                uno::Sequence < css::beans::PropertyValue >());
        if( xComponentLoader.is() )
            return new LibLODocument_Impl( xComponent );
        else
            pLib->maLastExceptionMsg = "unknown load failure";
    } catch (const uno::Exception &ex) {
        pLib->maLastExceptionMsg = ex.Message;
    }
    return NULL;
}

static int
doc_saveAs( LibreOfficeDocument *pThis,
            const char *url, const char *format )
{
    LibLODocument_Impl *pDocument = static_cast< LibLODocument_Impl *>( pThis );

    OUString sFormat = getUString( format );

    OUString aURL = getAbsoluteURL( url );

    try {
        uno::Reference< frame::XModel > xDocument( pDocument->mxComponent,
                                                   uno::UNO_QUERY_THROW );
        uno::Sequence< beans::PropertyValue > aSeq = xDocument->getArgs();

        OUString aDocumentService;
        for( sal_Int32 i = 0; i < aSeq.getLength(); ++i )
        {
            if( aSeq[i].Name == "DocumentService" )
                aSeq[i].Value >>= aDocumentService;
            OUString aValue;
            aSeq[i].Value >>= aValue;
        }

        if( aDocumentService == "")
        {
            gImpl->maLastExceptionMsg = "Unknown document type";
            return false;
        }
        const ExtensionMap *pMap;

        if( aDocumentService == "com.sun.star.sheet.SpreadsheetDocument" )
            pMap = (const ExtensionMap *)aCalcExtensionMap;
        else if( aDocumentService == "com.sun.star.presentation.PresentationDocument" )
            pMap = (const ExtensionMap *)aImpressExtensionMap;
        else // for the sake of argument only writer documents ...
            pMap = (const ExtensionMap *)aWriterExtensionMap;

        if( ! format )
        {
            // sniff from the extension
            sal_Int32 idx = aURL.lastIndexOf( "." );
            if( idx > 0 )
            {
                sFormat = aURL.copy( idx + 1 );
            }
            else
            {
                gImpl->maLastExceptionMsg = "input filename without a suffix";
                return false;
            }
        }

        OUString aFilterName;
        for( sal_Int32 i = 0; pMap[i].extn; i++ )
        {
            if( sFormat.equalsIgnoreAsciiCaseAscii( pMap[i].extn ) )
            {
                aFilterName = getUString( pMap[i].filterName );
                break;
            }
        }
        if( ! aFilterName.getLength() )
        {
            gImpl->maLastExceptionMsg = "no output filter found for provided suffix";
            return false;
        }

        aSeq.realloc(2);
        aSeq[0].Name = "Overwrite";
        aSeq[0].Value <<= sal_True;
        aSeq[1].Name = "FilterName";
        aSeq[1].Value <<= aFilterName;

        uno::Reference< frame::XStorable > xStorable( pDocument->mxComponent,
                                                      uno::UNO_QUERY_THROW );
        xStorable->storeToURL( aURL, aSeq );

        return true;
    } catch (const uno::Exception &ex) {
        gImpl->maLastExceptionMsg = "exception " + ex.Message;
        return false;
    }
}

static char *
lo_getError (LibreOffice *pThis)
{
    LibLibreOffice_Impl *pLib = static_cast< LibLibreOffice_Impl *>( pThis );
    OString aStr = rtl::OUStringToOString( pLib->maLastExceptionMsg, RTL_TEXTENCODING_UTF8 );
    char *pMem = (char *) malloc (aStr.getLength() + 1);
    strcpy( pMem, aStr.getStr() );
    return pMem;
}

static void
force_c_locale( void )
{
    // force locale (and resource files loaded) to en-US
    OUString aLangISO( "en-US" );
    LanguageTag aLocale( aLangISO );
    ResMgr::SetDefaultLocale( aLocale );
    SvtSysLocaleOptions aLocalOptions;
    aLocalOptions.SetLocaleConfigString( aLangISO );
    aLocalOptions.SetUILocaleConfigString( aLangISO );
}

static void
aBasicErrorFunc( const OUString &rErr, const OUString &rAction )
{
    OStringBuffer aErr( "Unexpected dialog: " );
    aErr.append( OUStringToOString( rAction, RTL_TEXTENCODING_ASCII_US ) );
    aErr.append( " Error: " );
    aErr.append( OUStringToOString( rErr, RTL_TEXTENCODING_ASCII_US ) );
    fprintf( stderr, "Unexpected basic error dialog '%s'\n", aErr.getStr() );
}

static void
initialize_uno( const OUString &aAppURL )
{
    rtl::Bootstrap::setIniFilename( aAppURL + "/fundamentalrc" );

    rtl::Bootstrap::set( "CONFIGURATION_LAYERS",
                         "xcsxcu:${BRAND_BASE_DIR}/" LIBO_SHARE_FOLDER "/registry "
                         "res:${BRAND_BASE_DIR}/" LIBO_SHARE_FOLDER "/registry "
//                       "bundledext:${${BRAND_BASE_DIR}/" LIBO_ETC_FOLDER "/unorc:BUNDLED_EXTENSIONS_USER}/registry/com.sun.star.comp.deployment.configuration.PackageRegistryBackend/configmgr.ini " );
//                       "sharedext:${${BRAND_BASE_DIR}/" LIBO_ETC_FOLDER "/unorc:SHARED_EXTENSIONS_USER}/registry/com.sun.star.comp.deployment.configuration.PackageRegistryBackend/configmgr.ini "
//                       "userext:${${BRAND_BASE_DIR}/" LIBO_ETC_FOLDER "/unorc:UNO_USER_PACKAGES_CACHE}/registry/com.sun.star.comp.deployment.configuration.PackageRegistryBackend/configmgr.ini "
//                         "user:${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/bootstraprc:UserInstallation}/user/registrymodifications.xcu"
                         );

    xContext = cppu::defaultBootstrap_InitialComponentContext();
    fprintf( stderr, "Uno initialized %d\n", xContext.is() );
    xFactory = xContext->getServiceManager();
    xSFactory = uno::Reference<lang::XMultiServiceFactory>(xFactory, uno::UNO_QUERY_THROW);
    comphelper::setProcessServiceFactory(xSFactory);

    // set UserInstallation to user profile dir in test/user-template
//    rtl::Bootstrap aDefaultVars;
//    aDefaultVars.set(OUString("UserInstallation"), aAppURL + "../registry" );
    // configmgr setup ?
}

static int
lo_initialize( LibreOffice *pThis, const char *app_path )
{
    (void) pThis;

    static bool bInitialized = false;
    if( bInitialized )
        return 1;

    if( !app_path )
        return 0;

    OUString aAppPath( app_path, strlen( app_path ), RTL_TEXTENCODING_UTF8 );
    OUString aAppURL;
    if( osl::FileBase::getFileURLFromSystemPath( aAppPath, aAppURL ) !=
        osl::FileBase::E_None )
        return 0;

    try {
        initialize_uno( aAppURL );
        force_c_locale();

        // Force headless
        rtl::Bootstrap::set( "SAL_USE_VCLPLUGIN", "svp" );
        InitVCL();
        Application::EnableHeadlessMode(true);

        ErrorHandler::RegisterDisplay( aBasicErrorFunc );

        fprintf( stderr, "initialized\n" );
        bInitialized = true;
    } catch (css::uno::Exception & e) {
        fprintf( stderr, "bootstrapping exception '%s'\n",
                 OUStringToOString( e.Message, RTL_TEXTENCODING_UTF8 ).getStr() );
    }
    return bInitialized;
}

LibreOffice *liblibreoffice_hook(void)
{
    if( !gImpl )
    {
        fprintf( stderr, "create libreoffice object\n" );
        gImpl = new LibLibreOffice_Impl();
    }
    return static_cast< LibreOffice *>( gImpl );
}

static void lo_destroy (LibreOffice *pThis)
{
    LibLibreOffice_Impl *pLib = static_cast< LibLibreOffice_Impl *>( pThis );
    delete pLib;
    gImpl = NULL;
}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>-Werror,-Wmismatched-tags<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <config_folders.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "liblibreoffice.h"

#include <tools/errinf.hxx>
#include <osl/file.hxx>
#include <osl/process.h>
#include <rtl/strbuf.hxx>
#include <rtl/bootstrap.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <comphelper/processfactory.hxx>

#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/frame/Desktop.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/lang/Locale.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/ucb/XContentProvider.hpp>
#include <com/sun/star/ucb/XUniversalContentBroker.hpp>

#include <vcl/svapp.hxx>
#include <tools/resmgr.hxx>
#include <vcl/graphicfilter.hxx>
#include <unotools/syslocaleoptions.hxx>

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

struct LibLODocument_Impl;
struct LibLibreOffice_Impl;

static LibLibreOffice_Impl *gImpl = NULL;

typedef struct {
    const char *extn;
    const char *filterName;
} ExtensionMap;

static const ExtensionMap
aWriterExtensionMap[] = {
    { "doc",   "MS Word 97" },
    { "docx",  "MS Word 2007 XML" },
    { "fodt",  "OpenDocument Text Flat XML" },
    { "html",  "HTML (StarWriter)" },
    { "odt",   "writer8" },
    { "ott",   "writer8_template" },
    { "pdf",   "writer_pdf_Export" },
    { "txt",   "Text" },
    { "xhtml", "XHTML Writer File" },
    { NULL, NULL }
};

static const ExtensionMap
aCalcExtensionMap[] = {
    { "csv",   "Text - txt - csv (StarCalc)" },
    { "fods",  "OpenDocument Spreadsheet Flat XML" },
    { "html",  "HTML (StarCalc)" },
    { "ods",   "calc8" },
    { "ots",   "calc8_template" },
    { "pdf",   "calc_pdf_Export" },
    { "xhtml", "XHTML Calc File" },
    { "xls",   "MS Excel 97" },
    { "xlsx",  "Calc MS Excel 2007 XML" },
    { NULL, NULL }
};

static const ExtensionMap
aImpressExtensionMap[] = {
    { "fodp",  "OpenDocument Presentation Flat XML" },
    { "html",  "impress_html_Export" },
    { "odg",   "impress8_draw" },
    { "odp",   "impress8" },
    { "otp",   "impress8_template" },
    { "pdf",   "impress_pdf_Export" },
    { "potm",  "Impress MS PowerPoint 2007 XML Template" },
    { "pot",   "MS PowerPoint 97 Vorlage" },
    { "pptx",  "Impress MS PowerPoint 2007 XML" },
    { "pps",   "MS PowerPoint 97 Autoplay" },
    { "ppt",   "MS PowerPoint 97" },
    { "svg",   "impress_svg_Export" },
    { "swf",   "impress_flash_Export" },
    { "xhtml", "XHTML Impress File" },
    { NULL, NULL }
};

extern "C" {

SAL_DLLPUBLIC_EXPORT LibreOffice *liblibreoffice_hook(void);

static void doc_destroy( LibreOfficeDocument *pThis );
static int  doc_saveAs( LibreOfficeDocument *pThis, const char *pUrl, const char *pFormat );

struct LibLODocument_Impl : public _LibreOfficeDocument
{
    uno::Reference < css::lang::XComponent > mxComponent;

    LibLODocument_Impl( const uno::Reference < css::lang::XComponent > &xComponent )
            : mxComponent( xComponent )
    {
        nSize = sizeof( LibreOffice );

        destroy = doc_destroy;
        saveAs = doc_saveAs;
    }
};

static void doc_destroy( LibreOfficeDocument *pThis )
{
    LibLODocument_Impl *pDocument = static_cast< LibLODocument_Impl *>( pThis );
    delete pDocument;
}

static void                 lo_destroy       (LibreOffice *pThis);
static int                  lo_initialize    (LibreOffice *pThis,
                                              const char *pInstallPath);
static LibreOfficeDocument *lo_documentLoad  (LibreOffice *pThis,
                                              const char *pURL);
static char *               lo_getError      (LibreOffice *pThis);

struct LibLibreOffice_Impl : public _LibreOffice
{
    rtl::OUString maLastExceptionMsg;

    LibLibreOffice_Impl()
    {
        nSize = sizeof( LibreOfficeDocument );

        destroy = lo_destroy;
        initialize = lo_initialize;
        documentLoad = lo_documentLoad;
        getError = lo_getError;
    }
};

// Wonder global state ...
static uno::Reference<css::uno::XComponentContext> xContext;
static uno::Reference<css::lang::XMultiServiceFactory> xSFactory;
static uno::Reference<css::lang::XMultiComponentFactory> xFactory;

static OUString getUString( const char *str )
{
    if( !str )
        return OUString( "" );
    return OStringToOUString( OString( str, strlen (str) ),
                              RTL_TEXTENCODING_UTF8 );
}

// Try to convert a relative URL to an absolute one
static OUString getAbsoluteURL( const char *pURL )
{
    OUString aURL( getUString( pURL ) );
    OUString sAbsoluteDocUrl, sWorkingDir, sDocPathUrl;

    // FIXME: this would appear to kill non-file URLs.
    osl_getProcessWorkingDir(&sWorkingDir.pData);
    osl::FileBase::getFileURLFromSystemPath( aURL, sDocPathUrl );
    osl::FileBase::getAbsoluteFileURL(sWorkingDir, sDocPathUrl, sAbsoluteDocUrl);

    return sAbsoluteDocUrl;
}

static LibreOfficeDocument *
lo_documentLoad( LibreOffice *pThis, const char *pURL )
{
    LibLibreOffice_Impl *pLib = static_cast< LibLibreOffice_Impl *>( pThis );

    OUString aURL = getAbsoluteURL( pURL );

    uno::Reference < css::frame::XDesktop2 > xComponentLoader =
            css::frame::Desktop::create(xContext);

    pLib->maLastExceptionMsg = "";
    try {
        uno::Reference < css::lang::XComponent > xComponent =
            xComponentLoader->loadComponentFromURL(
                aURL, OUString("_blank"), 0,
                uno::Sequence < css::beans::PropertyValue >());
        if( xComponentLoader.is() )
            return new LibLODocument_Impl( xComponent );
        else
            pLib->maLastExceptionMsg = "unknown load failure";
    } catch (const uno::Exception &ex) {
        pLib->maLastExceptionMsg = ex.Message;
    }
    return NULL;
}

static int
doc_saveAs( LibreOfficeDocument *pThis,
            const char *url, const char *format )
{
    LibLODocument_Impl *pDocument = static_cast< LibLODocument_Impl *>( pThis );

    OUString sFormat = getUString( format );

    OUString aURL = getAbsoluteURL( url );

    try {
        uno::Reference< frame::XModel > xDocument( pDocument->mxComponent,
                                                   uno::UNO_QUERY_THROW );
        uno::Sequence< beans::PropertyValue > aSeq = xDocument->getArgs();

        OUString aDocumentService;
        for( sal_Int32 i = 0; i < aSeq.getLength(); ++i )
        {
            if( aSeq[i].Name == "DocumentService" )
                aSeq[i].Value >>= aDocumentService;
            OUString aValue;
            aSeq[i].Value >>= aValue;
        }

        if( aDocumentService == "")
        {
            gImpl->maLastExceptionMsg = "Unknown document type";
            return false;
        }
        const ExtensionMap *pMap;

        if( aDocumentService == "com.sun.star.sheet.SpreadsheetDocument" )
            pMap = (const ExtensionMap *)aCalcExtensionMap;
        else if( aDocumentService == "com.sun.star.presentation.PresentationDocument" )
            pMap = (const ExtensionMap *)aImpressExtensionMap;
        else // for the sake of argument only writer documents ...
            pMap = (const ExtensionMap *)aWriterExtensionMap;

        if( ! format )
        {
            // sniff from the extension
            sal_Int32 idx = aURL.lastIndexOf( "." );
            if( idx > 0 )
            {
                sFormat = aURL.copy( idx + 1 );
            }
            else
            {
                gImpl->maLastExceptionMsg = "input filename without a suffix";
                return false;
            }
        }

        OUString aFilterName;
        for( sal_Int32 i = 0; pMap[i].extn; i++ )
        {
            if( sFormat.equalsIgnoreAsciiCaseAscii( pMap[i].extn ) )
            {
                aFilterName = getUString( pMap[i].filterName );
                break;
            }
        }
        if( ! aFilterName.getLength() )
        {
            gImpl->maLastExceptionMsg = "no output filter found for provided suffix";
            return false;
        }

        aSeq.realloc(2);
        aSeq[0].Name = "Overwrite";
        aSeq[0].Value <<= sal_True;
        aSeq[1].Name = "FilterName";
        aSeq[1].Value <<= aFilterName;

        uno::Reference< frame::XStorable > xStorable( pDocument->mxComponent,
                                                      uno::UNO_QUERY_THROW );
        xStorable->storeToURL( aURL, aSeq );

        return true;
    } catch (const uno::Exception &ex) {
        gImpl->maLastExceptionMsg = "exception " + ex.Message;
        return false;
    }
}

static char *
lo_getError (LibreOffice *pThis)
{
    LibLibreOffice_Impl *pLib = static_cast< LibLibreOffice_Impl *>( pThis );
    OString aStr = rtl::OUStringToOString( pLib->maLastExceptionMsg, RTL_TEXTENCODING_UTF8 );
    char *pMem = (char *) malloc (aStr.getLength() + 1);
    strcpy( pMem, aStr.getStr() );
    return pMem;
}

static void
force_c_locale( void )
{
    // force locale (and resource files loaded) to en-US
    OUString aLangISO( "en-US" );
    LanguageTag aLocale( aLangISO );
    ResMgr::SetDefaultLocale( aLocale );
    SvtSysLocaleOptions aLocalOptions;
    aLocalOptions.SetLocaleConfigString( aLangISO );
    aLocalOptions.SetUILocaleConfigString( aLangISO );
}

static void
aBasicErrorFunc( const OUString &rErr, const OUString &rAction )
{
    OStringBuffer aErr( "Unexpected dialog: " );
    aErr.append( OUStringToOString( rAction, RTL_TEXTENCODING_ASCII_US ) );
    aErr.append( " Error: " );
    aErr.append( OUStringToOString( rErr, RTL_TEXTENCODING_ASCII_US ) );
    fprintf( stderr, "Unexpected basic error dialog '%s'\n", aErr.getStr() );
}

static void
initialize_uno( const OUString &aAppURL )
{
    rtl::Bootstrap::setIniFilename( aAppURL + "/fundamentalrc" );

    rtl::Bootstrap::set( "CONFIGURATION_LAYERS",
                         "xcsxcu:${BRAND_BASE_DIR}/" LIBO_SHARE_FOLDER "/registry "
                         "res:${BRAND_BASE_DIR}/" LIBO_SHARE_FOLDER "/registry "
//                       "bundledext:${${BRAND_BASE_DIR}/" LIBO_ETC_FOLDER "/unorc:BUNDLED_EXTENSIONS_USER}/registry/com.sun.star.comp.deployment.configuration.PackageRegistryBackend/configmgr.ini " );
//                       "sharedext:${${BRAND_BASE_DIR}/" LIBO_ETC_FOLDER "/unorc:SHARED_EXTENSIONS_USER}/registry/com.sun.star.comp.deployment.configuration.PackageRegistryBackend/configmgr.ini "
//                       "userext:${${BRAND_BASE_DIR}/" LIBO_ETC_FOLDER "/unorc:UNO_USER_PACKAGES_CACHE}/registry/com.sun.star.comp.deployment.configuration.PackageRegistryBackend/configmgr.ini "
//                         "user:${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/bootstraprc:UserInstallation}/user/registrymodifications.xcu"
                         );

    xContext = cppu::defaultBootstrap_InitialComponentContext();
    fprintf( stderr, "Uno initialized %d\n", xContext.is() );
    xFactory = xContext->getServiceManager();
    xSFactory = uno::Reference<lang::XMultiServiceFactory>(xFactory, uno::UNO_QUERY_THROW);
    comphelper::setProcessServiceFactory(xSFactory);

    // set UserInstallation to user profile dir in test/user-template
//    rtl::Bootstrap aDefaultVars;
//    aDefaultVars.set(OUString("UserInstallation"), aAppURL + "../registry" );
    // configmgr setup ?
}

static int
lo_initialize( LibreOffice *pThis, const char *app_path )
{
    (void) pThis;

    static bool bInitialized = false;
    if( bInitialized )
        return 1;

    if( !app_path )
        return 0;

    OUString aAppPath( app_path, strlen( app_path ), RTL_TEXTENCODING_UTF8 );
    OUString aAppURL;
    if( osl::FileBase::getFileURLFromSystemPath( aAppPath, aAppURL ) !=
        osl::FileBase::E_None )
        return 0;

    try {
        initialize_uno( aAppURL );
        force_c_locale();

        // Force headless
        rtl::Bootstrap::set( "SAL_USE_VCLPLUGIN", "svp" );
        InitVCL();
        Application::EnableHeadlessMode(true);

        ErrorHandler::RegisterDisplay( aBasicErrorFunc );

        fprintf( stderr, "initialized\n" );
        bInitialized = true;
    } catch (css::uno::Exception & e) {
        fprintf( stderr, "bootstrapping exception '%s'\n",
                 OUStringToOString( e.Message, RTL_TEXTENCODING_UTF8 ).getStr() );
    }
    return bInitialized;
}

LibreOffice *liblibreoffice_hook(void)
{
    if( !gImpl )
    {
        fprintf( stderr, "create libreoffice object\n" );
        gImpl = new LibLibreOffice_Impl();
    }
    return static_cast< LibreOffice *>( gImpl );
}

static void lo_destroy (LibreOffice *pThis)
{
    LibLibreOffice_Impl *pLib = static_cast< LibLibreOffice_Impl *>( pThis );
    delete pLib;
    gImpl = NULL;
}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include "musicmarqueewidget.h"
#include <QtGui>

MusicMarqueeWidget::MusicMarqueeWidget(QWidget *parent)
    : QWidget(parent)
{
    m_offset = 0;
    m_myTimerId = 0;
}

void MusicMarqueeWidget::setText(const QString &newText)
{
    m_myText = newText.leftJustified(50, ' ');
    update();
    updateGeometry();
}

QSize MusicMarqueeWidget::sizeHint() const
{
    return fontMetrics().size(0, text());
}

void MusicMarqueeWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);

    int textWidth = fontMetrics().width(text());
    if(textWidth < 1)
    {
        return;
    }
    int x = -m_offset;
    while(x < width())
    {
        painter.drawText(x, 0, textWidth, height(),
                         Qt::AlignLeft | Qt::AlignVCenter, text());
        x += textWidth;
    }
    painter.end();
}

void MusicMarqueeWidget::showEvent(QShowEvent *)
{
    m_myTimerId = startTimer(30);
}

void MusicMarqueeWidget::timerEvent(QTimerEvent *event)
{
    if(event->timerId() == m_myTimerId)
    {
        ++m_offset;
        if (m_offset >= fontMetrics().width(text()))
        {
            m_offset = 0;
        }
        scroll(-1, 0);
    }
    else
    {
        QWidget::timerEvent(event);
    }
}

void MusicMarqueeWidget::hideEvent(QHideEvent *)
{
    killTimer(m_myTimerId);
    m_myTimerId = 0;
}
<commit_msg>optimized marquee widgte size[320187]<commit_after>#include "musicmarqueewidget.h"
#include <QtGui>

MusicMarqueeWidget::MusicMarqueeWidget(QWidget *parent)
    : QWidget(parent)
{
    m_offset = 0;
    m_myTimerId = 0;
}

void MusicMarqueeWidget::setText(const QString &newText)
{
    m_myText = newText.leftJustified(fontMetrics().width(newText) >= width()
                                     ? 45 : 25, ' ');
    update();
    updateGeometry();
}

QSize MusicMarqueeWidget::sizeHint() const
{
    return fontMetrics().size(0, text());
}

void MusicMarqueeWidget::paintEvent(QPaintEvent *event)
{
    QWidget::paintEvent(event);
    QPainter painter(this);
    int textWidth = fontMetrics().width(text());
    if(textWidth < 1)
    {
        return;
    }
    int x = -m_offset;
    while(x < width())
    {
        painter.drawText(x, 0, textWidth, height(),
                         Qt::AlignLeft | Qt::AlignVCenter, text());
        x += textWidth;
    }
    painter.end();
}

void MusicMarqueeWidget::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);
    m_myTimerId = startTimer(30);
}

void MusicMarqueeWidget::timerEvent(QTimerEvent *event)
{
    if(event->timerId() == m_myTimerId)
    {
        ++m_offset;
        if (m_offset >= fontMetrics().width(text()))
        {
            m_offset = 0;
        }
        scroll(-1, 0);
    }
    else
    {
        QWidget::timerEvent(event);
    }
}

void MusicMarqueeWidget::hideEvent(QHideEvent *event)
{
    QWidget::hideEvent(event);
    killTimer(m_myTimerId);
    m_myTimerId = 0;
}
<|endoftext|>


<commit_before>#pragma once

// https://infektor.net/posts/2017-03-31-range-based-enumerate.html

#include <iterator>
#include <utility>

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

namespace acmacs
{
    namespace _enumerate_internal
    {
        template <typename Iterator, typename index_type> struct enumerate_iterator
        {
            using iterator = Iterator;
              //using index_type = typename std::iterator_traits<iterator>::difference_type;
            using reference = typename std::iterator_traits<iterator>::reference;

            inline enumerate_iterator(index_type aIndex, iterator aIterator) : index(aIndex), iter(aIterator) {}
            inline enumerate_iterator& operator++() { ++index; ++iter; return *this; }
            inline bool operator!=(const enumerate_iterator &other) const { return iter != other.iter; }
            inline std::pair<index_type, reference> operator*() { return {index, *iter}; }

         private:
            index_type index;
            iterator iter;
        };

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

        template <typename Iterator, typename index_type> struct enumerate_range
        {
              // using index_type = typename std::iterator_traits<Iterator>::difference_type;
            using iterator = enumerate_iterator<Iterator, index_type>;

            inline enumerate_range(Iterator aFirst, Iterator aLast, index_type aInitial) : first(aFirst), last(aLast), initial(aInitial) {}
            inline iterator begin() const { return iterator(initial, first); }
            inline iterator end() const { return iterator(0, last); }

         private:
            Iterator first;
            Iterator last;
            index_type initial;
        };

    } // namespace _enumerate_internal

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

    template <typename Iterator, typename index_type> inline auto enumerate(Iterator first, Iterator last, index_type initial = 0)
    {
        return _enumerate_internal::enumerate_range<Iterator, index_type>(first, last, initial);
    }

    template <typename Container> inline auto enumerate(Container& content, size_t initial = 0)
    {
        using iter_type = decltype(std::begin(content));
        return _enumerate_internal::enumerate_range<iter_type, size_t>(std::begin(content), std::end(content), initial);
    }

    template <typename Container> inline auto enumerate(const Container& content, size_t initial = 0)
    {
        using iter_type = decltype(std::begin(content));
        return _enumerate_internal::enumerate_range<iter_type, size_t>(std::begin(content), std::end(content), initial);
    }

} // namespace acmacs

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>minor fix<commit_after>#pragma once

// https://infektor.net/posts/2017-03-31-range-based-enumerate.html

#include <iterator>
#include <utility>

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

namespace acmacs
{
    namespace _enumerate_internal
    {
        template <typename Iterator, typename index_type> struct enumerate_iterator
        {
            using iterator = Iterator;
              //using index_type = typename std::iterator_traits<iterator>::difference_type;
            using reference = typename std::iterator_traits<iterator>::reference;

            enumerate_iterator(index_type aIndex, iterator aIterator) : index(aIndex), iter(aIterator) {}
            enumerate_iterator& operator++() { ++index; ++iter; return *this; }
            bool operator!=(const enumerate_iterator &other) const { return iter != other.iter; }
            std::pair<index_type, reference> operator*() { return {index, *iter}; }

         private:
            index_type index;
            iterator iter;
        };

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

        template <typename Iterator, typename index_type> struct enumerate_range
        {
              // using index_type = typename std::iterator_traits<Iterator>::difference_type;
            using iterator = enumerate_iterator<Iterator, index_type>;

            enumerate_range(Iterator aFirst, Iterator aLast, index_type aInitial) : first(aFirst), last(aLast), initial(aInitial) {}
            iterator begin() const { return iterator(initial, first); }
            iterator end() const { return iterator(0, last); }

         private:
            Iterator first;
            Iterator last;
            index_type initial;
        };

    } // namespace _enumerate_internal

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

    template <typename Iterator, typename index_type> inline auto enumerate(Iterator first, Iterator last, index_type initial = 0)
    {
        return _enumerate_internal::enumerate_range<Iterator, index_type>(first, last, initial);
    }

    template <typename Container> inline auto enumerate(Container& content, size_t initial = 0)
    {
        using iter_type = decltype(std::begin(content));
        return _enumerate_internal::enumerate_range<iter_type, size_t>(std::begin(content), std::end(content), initial);
    }

    template <typename Container> inline auto enumerate(const Container& content, size_t initial = 0)
    {
        using iter_type = decltype(std::begin(content));
        return _enumerate_internal::enumerate_range<iter_type, size_t>(std::begin(content), std::end(content), initial);
    }

} // namespace acmacs

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before>// @(#)root/base:$Id$
// Author: Christian Bormann  13/10/97

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TSystemDirectory                                                     //
//                                                                      //
// Describes an Operating System directory for the browser.             //
//                                                                      //
// Author: Christian Bormann  30/09/97                                  //
//         http://www.ikf.physik.uni-frankfurt.de/~bormann/             //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TSystemDirectory.h"
#include "TSystem.h"
#include "TBrowser.h"
#include "TOrdCollection.h"
#include "TList.h"

ClassImp(TSystemDirectory);

////////////////////////////////////////////////////////////////////////////////
/// Create a system directory object.

TSystemDirectory::TSystemDirectory()
{
   fDirsInBrowser  = 0;
   fFilesInBrowser = 0;
}

////////////////////////////////////////////////////////////////////////////////
/// Create a system directory object.

TSystemDirectory::TSystemDirectory(const char *dirname, const char *path) :
   TSystemFile(dirname, path)
{
   fDirsInBrowser  = 0;
   fFilesInBrowser = 0;
}

////////////////////////////////////////////////////////////////////////////////
///copy constructor

TSystemDirectory::TSystemDirectory(const TSystemDirectory& sd) :
  TSystemFile(sd),
  fDirsInBrowser(sd.fDirsInBrowser),
  fFilesInBrowser(sd.fFilesInBrowser)
{
}

////////////////////////////////////////////////////////////////////////////////
///assignment operator

TSystemDirectory& TSystemDirectory::operator=(const TSystemDirectory& sd)
{
   if(this!=&sd) {
      TSystemFile::operator=(sd);
      fDirsInBrowser=sd.fDirsInBrowser;
      fFilesInBrowser=sd.fFilesInBrowser;
   }
   return *this;
}

////////////////////////////////////////////////////////////////////////////////
/// Delete system directory object.

TSystemDirectory::~TSystemDirectory()
{
   delete fDirsInBrowser;
   delete fFilesInBrowser;
}

////////////////////////////////////////////////////////////////////////////////
/// Returns a TList of TSystemFile objects representing the contents
/// of the directory. It's the responsibility of the user to delete
/// the list (the list owns the contained objects).
/// Returns 0 in case of errors.

TList *TSystemDirectory::GetListOfFiles() const
{
   void *dir = gSystem->OpenDirectory(GetTitle());
   if (!dir) return 0;

   const char *file = 0;
   TList *contents  = new TList;
   contents->SetOwner();
   while ((file = gSystem->GetDirEntry(dir))) {
      if (IsItDirectory(file)) {
         TString sdirpath;
         if (file[0] == '.' && file[1] == '\0')
            sdirpath = GetTitle();
         else if (file[0] == '.' && file[1] == '.' && file[2] == '.')
            sdirpath = gSystem->DirName(GetTitle());
         else {
            sdirpath = GetTitle();
            if (!sdirpath.EndsWith("/"))
               sdirpath += "/";
            sdirpath += file;
         }
         contents->Add(new TSystemDirectory(file, sdirpath.Data()));
      } else
         contents->Add(new TSystemFile(file, GetTitle()));
   }
   gSystem->FreeDirectory(dir);
   return contents;
}

////////////////////////////////////////////////////////////////////////////////
/// Create a system directory object.

void TSystemDirectory::SetDirectory(const char *name)
{
   SetName(name);
   SetTitle(name);
}

////////////////////////////////////////////////////////////////////////////////
/// Check if name is a directory.

Bool_t TSystemDirectory::IsItDirectory(const char *name) const
{
   Long64_t size;
   Long_t id, flags, modtime;
   const char *dirfile = GetTitle();
   TString savDir = gSystem->WorkingDirectory();

   gSystem->ChangeDirectory(dirfile);
   flags = id = size = modtime = 0;
   gSystem->GetPathInfo(name, &id, &size, &flags, &modtime);
   Int_t isdir = (Int_t)flags & 2;

   gSystem->ChangeDirectory(savDir);
   return isdir ? kTRUE : kFALSE;
}

////////////////////////////////////////////////////////////////////////////////
/// Browse OS system directories.

void TSystemDirectory::Browse(TBrowser *b)
{
   // Collections to keep track of all browser objects that have been
   // generated. It's main goal is to prevent the contineous
   // allocations of new objects with the same names during browsing.
   if (!fDirsInBrowser)  fDirsInBrowser  = new TOrdCollection;
   if (!fFilesInBrowser) fFilesInBrowser = new TOrdCollection(10);

   const char *name = GetTitle();
   TSystemFile *sfile;
   TSystemDirectory *sdir;
   const char *file;

   gSystem->ChangeDirectory(name);

   if (GetName()[0] == '.' && GetName()[1] == '.')
      SetName(gSystem->BaseName(name));

   void *dir = gSystem->OpenDirectory(name);

   if (!dir)
      return;

   while ((file = gSystem->GetDirEntry(dir))) {
      if (b->TestBit(TBrowser::kNoHidden) && file[0] == '.' && file[1] != '.' )
         continue;
      if (IsItDirectory(file)) {
         TString sdirpath;
         if (!strcmp(file, "."))
            sdirpath = name;
         else if (!strcmp(file, ".."))
            sdirpath = gSystem->DirName(name);
         else {
            sdirpath =  name;
            if (!sdirpath.EndsWith("/"))
               sdirpath += "/";
            sdirpath += file;
         }
         if (!(sdir = FindDirObj(sdirpath.Data()))) {
            sdir = new TSystemDirectory(file, sdirpath.Data());
            fDirsInBrowser->Add(sdir);
         }
         b->Add(sdir, file);
      } else {
         if (!(sfile = FindFileObj(file, gSystem->WorkingDirectory()))) {
            sfile = new TSystemFile(file, gSystem->WorkingDirectory());
            fFilesInBrowser->Add(sfile);
         }
         b->Add(sfile, file);
      }
   }
   gSystem->FreeDirectory(dir);
}

////////////////////////////////////////////////////////////////////////////////
/// Method that returns system directory object if it
/// exists in list, 0 otherwise.

TSystemDirectory *TSystemDirectory::FindDirObj(const char *name)
{
   int size = fDirsInBrowser->GetSize();
   for (int i = 0; i < size; i++) {
      TSystemDirectory *obj = (TSystemDirectory *) fDirsInBrowser->At(i);
      if (!strcmp(name, obj->GetTitle()))
         return obj;
   }
   return 0;
}

////////////////////////////////////////////////////////////////////////////////
/// Method that returns system file object if it exists in
/// list, 0 otherwise.

TSystemFile *TSystemDirectory::FindFileObj(const char *name, const char *dir)
{
   int size = fFilesInBrowser->GetSize();
   for (int i = 0; i < size; i++) {
      TSystemFile *obj = (TSystemFile *) fFilesInBrowser->At(i);
      if (!strcmp(name, obj->GetName()) && !strcmp(dir, obj->GetTitle()))
         return obj;
   }
   return 0;
}
<commit_msg>Doxygen<commit_after>// @(#)root/base:$Id$
// Author: Christian Bormann  13/10/97

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

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

/** \class TSystemDirectory
Describes an Operating System directory for the browser.
*/

#include "TSystemDirectory.h"
#include "TSystem.h"
#include "TBrowser.h"
#include "TOrdCollection.h"
#include "TList.h"

ClassImp(TSystemDirectory);

////////////////////////////////////////////////////////////////////////////////
/// Create a system directory object.

TSystemDirectory::TSystemDirectory()
{
   fDirsInBrowser  = 0;
   fFilesInBrowser = 0;
}

////////////////////////////////////////////////////////////////////////////////
/// Create a system directory object.

TSystemDirectory::TSystemDirectory(const char *dirname, const char *path) :
   TSystemFile(dirname, path)
{
   fDirsInBrowser  = 0;
   fFilesInBrowser = 0;
}

////////////////////////////////////////////////////////////////////////////////
/// Copy constructor

TSystemDirectory::TSystemDirectory(const TSystemDirectory& sd) :
  TSystemFile(sd),
  fDirsInBrowser(sd.fDirsInBrowser),
  fFilesInBrowser(sd.fFilesInBrowser)
{
}

////////////////////////////////////////////////////////////////////////////////
/// Assignment operator

TSystemDirectory& TSystemDirectory::operator=(const TSystemDirectory& sd)
{
   if(this!=&sd) {
      TSystemFile::operator=(sd);
      fDirsInBrowser=sd.fDirsInBrowser;
      fFilesInBrowser=sd.fFilesInBrowser;
   }
   return *this;
}

////////////////////////////////////////////////////////////////////////////////
/// Delete system directory object.

TSystemDirectory::~TSystemDirectory()
{
   delete fDirsInBrowser;
   delete fFilesInBrowser;
}

////////////////////////////////////////////////////////////////////////////////
/// Returns a TList of TSystemFile objects representing the contents
/// of the directory. It's the responsibility of the user to delete
/// the list (the list owns the contained objects).
/// Returns 0 in case of errors.

TList *TSystemDirectory::GetListOfFiles() const
{
   void *dir = gSystem->OpenDirectory(GetTitle());
   if (!dir) return 0;

   const char *file = 0;
   TList *contents  = new TList;
   contents->SetOwner();
   while ((file = gSystem->GetDirEntry(dir))) {
      if (IsItDirectory(file)) {
         TString sdirpath;
         if (file[0] == '.' && file[1] == '\0')
            sdirpath = GetTitle();
         else if (file[0] == '.' && file[1] == '.' && file[2] == '.')
            sdirpath = gSystem->DirName(GetTitle());
         else {
            sdirpath = GetTitle();
            if (!sdirpath.EndsWith("/"))
               sdirpath += "/";
            sdirpath += file;
         }
         contents->Add(new TSystemDirectory(file, sdirpath.Data()));
      } else
         contents->Add(new TSystemFile(file, GetTitle()));
   }
   gSystem->FreeDirectory(dir);
   return contents;
}

////////////////////////////////////////////////////////////////////////////////
/// Create a system directory object.

void TSystemDirectory::SetDirectory(const char *name)
{
   SetName(name);
   SetTitle(name);
}

////////////////////////////////////////////////////////////////////////////////
/// Check if name is a directory.

Bool_t TSystemDirectory::IsItDirectory(const char *name) const
{
   Long64_t size;
   Long_t id, flags, modtime;
   const char *dirfile = GetTitle();
   TString savDir = gSystem->WorkingDirectory();

   gSystem->ChangeDirectory(dirfile);
   flags = id = size = modtime = 0;
   gSystem->GetPathInfo(name, &id, &size, &flags, &modtime);
   Int_t isdir = (Int_t)flags & 2;

   gSystem->ChangeDirectory(savDir);
   return isdir ? kTRUE : kFALSE;
}

////////////////////////////////////////////////////////////////////////////////
/// Browse OS system directories.

void TSystemDirectory::Browse(TBrowser *b)
{
   // Collections to keep track of all browser objects that have been
   // generated. It's main goal is to prevent the continuous
   // allocations of new objects with the same names during browsing.
   if (!fDirsInBrowser)  fDirsInBrowser  = new TOrdCollection;
   if (!fFilesInBrowser) fFilesInBrowser = new TOrdCollection(10);

   const char *name = GetTitle();
   TSystemFile *sfile;
   TSystemDirectory *sdir;
   const char *file;

   gSystem->ChangeDirectory(name);

   if (GetName()[0] == '.' && GetName()[1] == '.')
      SetName(gSystem->BaseName(name));

   void *dir = gSystem->OpenDirectory(name);

   if (!dir)
      return;

   while ((file = gSystem->GetDirEntry(dir))) {
      if (b->TestBit(TBrowser::kNoHidden) && file[0] == '.' && file[1] != '.' )
         continue;
      if (IsItDirectory(file)) {
         TString sdirpath;
         if (!strcmp(file, "."))
            sdirpath = name;
         else if (!strcmp(file, ".."))
            sdirpath = gSystem->DirName(name);
         else {
            sdirpath =  name;
            if (!sdirpath.EndsWith("/"))
               sdirpath += "/";
            sdirpath += file;
         }
         if (!(sdir = FindDirObj(sdirpath.Data()))) {
            sdir = new TSystemDirectory(file, sdirpath.Data());
            fDirsInBrowser->Add(sdir);
         }
         b->Add(sdir, file);
      } else {
         if (!(sfile = FindFileObj(file, gSystem->WorkingDirectory()))) {
            sfile = new TSystemFile(file, gSystem->WorkingDirectory());
            fFilesInBrowser->Add(sfile);
         }
         b->Add(sfile, file);
      }
   }
   gSystem->FreeDirectory(dir);
}

////////////////////////////////////////////////////////////////////////////////
/// Method that returns system directory object if it
/// exists in list, 0 otherwise.

TSystemDirectory *TSystemDirectory::FindDirObj(const char *name)
{
   int size = fDirsInBrowser->GetSize();
   for (int i = 0; i < size; i++) {
      TSystemDirectory *obj = (TSystemDirectory *) fDirsInBrowser->At(i);
      if (!strcmp(name, obj->GetTitle()))
         return obj;
   }
   return 0;
}

////////////////////////////////////////////////////////////////////////////////
/// Method that returns system file object if it exists in
/// list, 0 otherwise.

TSystemFile *TSystemDirectory::FindFileObj(const char *name, const char *dir)
{
   int size = fFilesInBrowser->GetSize();
   for (int i = 0; i < size; i++) {
      TSystemFile *obj = (TSystemFile *) fFilesInBrowser->At(i);
      if (!strcmp(name, obj->GetName()) && !strcmp(dir, obj->GetTitle()))
         return obj;
   }
   return 0;
}
<|endoftext|>


<commit_before>#include "pbfParser.h"
#include "platform.h"
#include "tileID.h"

#include <sstream>
#include <fstream>

#include "protobuffSrc.h"

MapboxProtoBuffSrc::MapboxProtoBuffSrc() {
    m_urlTemplate = "http://vector.mapzen.com/osm/all/[z]/[x]/[y].mapbox";
}

std::shared_ptr<TileData> MapboxProtoBuffSrc::parse(const MapTile& _tile, std::stringstream& _in) {

    std::shared_ptr<TileData> tileData = std::make_shared<TileData>();

    std::string buffer(std::istreambuf_iterator<char>(_in.rdbuf()), (std::istreambuf_iterator<char>()));

    protobuf::message item(buffer.data(), buffer.size());

    while(item.next()) {
        if(item.tag == 3) {
            protobuf::message layerMsg = item.getMessage();
            protobuf::message layerItr = layerMsg;
            while (layerItr.next()) {
                if (layerItr.tag == 1) {
                    auto layerName = layerItr.string();
                    tileData->layers.emplace_back(layerName);
                    PbfParser::extractLayer(layerMsg, tileData->layers.back(), _tile);
                } else {
                    layerItr.skip();
                }
            }
        } else {
            item.skip();
        }
    }
    return tileData;
}
<commit_msg>renamed header inclusion<commit_after>#include "pbfParser.h"
#include "platform.h"
#include "tileID.h"

#include <sstream>
#include <fstream>

#include "protobufSrc.h"

MapboxProtoBuffSrc::MapboxProtoBuffSrc() {
    m_urlTemplate = "http://vector.mapzen.com/osm/all/[z]/[x]/[y].mapbox";
}

std::shared_ptr<TileData> MapboxProtoBuffSrc::parse(const MapTile& _tile, std::stringstream& _in) {

    std::shared_ptr<TileData> tileData = std::make_shared<TileData>();

    std::string buffer(std::istreambuf_iterator<char>(_in.rdbuf()), (std::istreambuf_iterator<char>()));

    protobuf::message item(buffer.data(), buffer.size());

    while(item.next()) {
        if(item.tag == 3) {
            protobuf::message layerMsg = item.getMessage();
            protobuf::message layerItr = layerMsg;
            while (layerItr.next()) {
                if (layerItr.tag == 1) {
                    auto layerName = layerItr.string();
                    tileData->layers.emplace_back(layerName);
                    PbfParser::extractLayer(layerMsg, tileData->layers.back(), _tile);
                } else {
                    layerItr.skip();
                }
            }
        } else {
            item.skip();
        }
    }
    return tileData;
}
<|endoftext|>


<commit_before>#pragma once

#include <HgScene2.h>
#include <HgEngine.h>

namespace Engine {

std::unordered_map<std::string, factoryCallback> HgScene::m_entityFactories;

HgScene::HgScene()
{
	auto vBuffer = std::make_shared<HgVectorBuffer<Instancing::GPUTransformationMatrix>>();

	std::unique_ptr<IGLBufferUse> action = std::make_unique<MatrixVertexAttribute>("ModelMatrix");
	vBuffer->setUseClass(action);

	m_vBuffer = vBuffer;
}

HgEntity* HgScene::create_entity(const char* type_str)
{
	auto factory = m_entityFactories.find(type_str);

	if (factory == m_entityFactories.end()) {
		fprintf(stderr, "Unable to find entity type \"%s\"\n", type_str);
		return nullptr;
	}
	factoryCallback clbk = factory->second;
	HgEntity* entity = clbk(this);

	return entity;
}

void HgScene::RegisterEntityFactory(const char* str, Engine::factoryCallback clbk)
{
	m_entityFactories[str] = clbk;
}

void HgScene::update(HgTime dtime)
{
	for (auto& i : m_collections) {
		i->update(dtime);
	}

	RemoveInvalidEntities();
}

void HgScene::RemoveInvalidEntities()
{
	m_tmpEntities.clear();
	if (m_tmpEntities.capacity() < m_entities.size())
	{
		m_tmpEntities.reserve(m_entities.size());
	}

	for (auto id : m_entities)
	{
		if (EntityIdTable::Manager.exists(id))
		{
			m_tmpEntities.push_back(id);
		}
	}
	std::swap(m_entities, m_tmpEntities);
}

struct {
	bool operator()(const EntityRDPair& a, const EntityRDPair& b) const
	{
		//sort to ascending entity id
		if (a.ptr == b.ptr)
		{
			return a.entity < b.entity;
		}
		return a.ptr < b.ptr;
	}
} orderByRenderData;

struct RdDrawOrder
{
	RdDrawOrder()
		:drawOrder(0)
	{}

	EntityRDPair rdPair;
	int8_t drawOrder;

	inline bool isSameGroup(const RdDrawOrder& rhs)
	{
		return (drawOrder == rhs.drawOrder)
			&& (rdPair.ptr == rhs.rdPair.ptr);
	}
};

struct {
	bool operator()(const RdDrawOrder& a, const RdDrawOrder& b) const
	{
		if (a.drawOrder == b.drawOrder)
		{
			//sort to ascending entity id
			if (a.rdPair.ptr == b.rdPair.ptr)
			{
				return a.rdPair.entity < b.rdPair.entity;
			}
			return a.rdPair.ptr < b.rdPair.ptr;
		}
		return a.drawOrder < b.drawOrder;
	}
} orderEntitesForDraw;

void HgScene::EnqueueForRender(RenderQueue* queue, HgTime dt) {
	for (auto& i : m_collections) {
		i->EnqueueForRender(queue, dt);
	}

	if (m_entities.empty()) return;

	auto renderDatas = RenderDataTable::Manager.getRenderDataForEntities(m_entities.data(), m_entities.size());

	std::vector<RdDrawOrder> list;
	list.reserve(renderDatas.size());

	for (auto& rdp : renderDatas)
	{
		RdDrawOrder t;
		t.rdPair = rdp;
		t.drawOrder = EntityTable::Singleton.getPtr(rdp.entity)->getDrawOrder();
		list.push_back(t);
	}

	if (m_modelMatrices.capacity() < list.size())
	{
		m_modelMatrices.resize(list.size());
	}

	std::vector< Instancing::InstancingMetaData > instances;

	m_vBuffer->setDataSource(m_modelMatrices);
	m_vBuffer->setNeedsLoadToGPU(true); //entire vector contents needs to be sent to the GPU

	//sort by draworder, renderdata, entityID
	std::sort(list.begin(), list.end(), orderEntitesForDraw);

	//group by draworder, renderdata
	RdDrawOrder lastRDO;
	Instancing::InstancingMetaData imd;
	uint32_t matrixOffset = 0;
	for (const auto& t : list)
	{
		if (!lastRDO.isSameGroup(t))
		{
			if (imd.instanceCount > 0)
			{
				instances.push_back(imd);
			}
			imd = Instancing::InstancingMetaData();
			imd.byteOffset = sizeof(Instancing::GPUTransformationMatrix) * matrixOffset;
			imd.renderData = t.rdPair.ptr;
			imd.instanceData = m_vBuffer;
		}
		lastRDO = t;
		auto entity = EntityTable::Singleton.getPtr(t.rdPair.entity);

		const auto m = entity->computeWorldSpaceMatrix();
		m.store(m_modelMatrices[matrixOffset].matrix);

		imd.instanceCount++;
		matrixOffset++;
	}

	if (imd.instanceCount > 0)
	{
		instances.push_back(imd);
	}

	for (const auto& i : instances)
	{
		queue->Enqueue(i);
	}
}

} //Engine<commit_msg>rewrite sort for better performance<commit_after>#pragma once

#include <HgScene2.h>
#include <HgEngine.h>

namespace Engine {

std::unordered_map<std::string, factoryCallback> HgScene::m_entityFactories;

HgScene::HgScene()
{
	auto vBuffer = std::make_shared<HgVectorBuffer<Instancing::GPUTransformationMatrix>>();

	std::unique_ptr<IGLBufferUse> action = std::make_unique<MatrixVertexAttribute>("ModelMatrix");
	vBuffer->setUseClass(action);

	m_vBuffer = vBuffer;
}

HgEntity* HgScene::create_entity(const char* type_str)
{
	auto factory = m_entityFactories.find(type_str);

	if (factory == m_entityFactories.end()) {
		fprintf(stderr, "Unable to find entity type \"%s\"\n", type_str);
		return nullptr;
	}
	factoryCallback clbk = factory->second;
	HgEntity* entity = clbk(this);

	return entity;
}

void HgScene::RegisterEntityFactory(const char* str, Engine::factoryCallback clbk)
{
	m_entityFactories[str] = clbk;
}

void HgScene::update(HgTime dtime)
{
	for (auto& i : m_collections) {
		i->update(dtime);
	}

	RemoveInvalidEntities();
}

void HgScene::RemoveInvalidEntities()
{
	m_tmpEntities.clear();
	if (m_tmpEntities.capacity() < m_entities.size())
	{
		m_tmpEntities.reserve(m_entities.size());
	}

	for (auto id : m_entities)
	{
		if (EntityIdTable::Manager.exists(id))
		{
			m_tmpEntities.push_back(id);
		}
	}
	std::swap(m_entities, m_tmpEntities);
}

struct {
	bool operator()(const EntityRDPair& a, const EntityRDPair& b) const
	{
		//sort to ascending entity id
		if (a.ptr == b.ptr)
		{
			return a.entity < b.entity;
		}
		return a.ptr < b.ptr;
	}
} orderByRenderData;

struct RdDrawOrder
{
	RdDrawOrder()
		:drawOrder(0)
	{}

	EntityRDPair rdPair;
	int8_t drawOrder;

	inline bool isSameGroup(const RdDrawOrder& rhs)
	{
		return (drawOrder == rhs.drawOrder)
			&& (rdPair.ptr == rhs.rdPair.ptr);
	}
};

struct {
	bool operator()(const RdDrawOrder& a, const RdDrawOrder& b) const
	{
		return (a.drawOrder < b.drawOrder) ||
		((a.drawOrder == b.drawOrder) && (a.rdPair.ptr < b.rdPair.ptr)) ||
		((a.drawOrder == b.drawOrder) && (a.rdPair.ptr == b.rdPair.ptr) && (a.rdPair.ptr < b.rdPair.ptr));

	//if (a.drawOrder == b.drawOrder)
	//	{
	//		//sort to ascending entity id
	//		if (a.rdPair.ptr == b.rdPair.ptr)
	//		{
	//			return a.rdPair.entity < b.rdPair.entity;
	//		}
	//		return a.rdPair.ptr < b.rdPair.ptr;
	//	}
	//	return a.drawOrder < b.drawOrder;
	}
} orderEntitesForDraw;

void HgScene::EnqueueForRender(RenderQueue* queue, HgTime dt) {
	for (auto& i : m_collections) {
		i->EnqueueForRender(queue, dt);
	}

	if (m_entities.empty()) return;

	auto renderDatas = RenderDataTable::Manager.getRenderDataForEntities(m_entities.data(), m_entities.size());

	std::vector<RdDrawOrder> list;
	list.reserve(renderDatas.size());

	for (auto& rdp : renderDatas)
	{
		RdDrawOrder t;
		t.rdPair = rdp;
		t.drawOrder = EntityTable::Singleton.getPtr(rdp.entity)->getDrawOrder();
		list.push_back(t);
	}

	if (m_modelMatrices.capacity() < list.size())
	{
		m_modelMatrices.resize(list.size());
	}

	std::vector< Instancing::InstancingMetaData > instances;

	m_vBuffer->setDataSource(m_modelMatrices);
	m_vBuffer->setNeedsLoadToGPU(true); //entire vector contents needs to be sent to the GPU

	//sort by draworder, renderdata, entityID
	std::sort(list.begin(), list.end(), orderEntitesForDraw);

	//group by draworder, renderdata
	RdDrawOrder lastRDO;
	Instancing::InstancingMetaData imd;
	uint32_t matrixOffset = 0;
	for (const auto& t : list)
	{
		if (!lastRDO.isSameGroup(t))
		{
			if (imd.instanceCount > 0)
			{
				instances.push_back(imd);
			}
			imd = Instancing::InstancingMetaData();
			imd.byteOffset = sizeof(Instancing::GPUTransformationMatrix) * matrixOffset;
			imd.renderData = t.rdPair.ptr;
			imd.instanceData = m_vBuffer;
			lastRDO = t;
		}
		auto entity = EntityTable::Singleton.getPtr(t.rdPair.entity);

		const auto m = entity->computeWorldSpaceMatrix();
		m.store(m_modelMatrices[matrixOffset].matrix);

		imd.instanceCount++;
		matrixOffset++;
	}

	if (imd.instanceCount > 0)
	{
		instances.push_back(imd);
	}

	for (const auto& i : instances)
	{
		queue->Enqueue(i);
	}
}

} //Engine<|endoftext|>


<commit_before>/*
 *  Harversine.c
 *  Haversine
 *
 *  Created by Jaime Rios on 2/16/08.
 *
 */

#include "Harversine.h"

#include <math.h> // For PI

/*
 Haversine Formula
 R = earth’s radius (mean radius = 6,371km)
 Δlat = lat2− lat1
 Δlong = long2− long1
 a = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2)
 c = 2.atan2(√a, √(1−a))
 d = R.c

 JavaScript Example from http://www.movable-type.co.uk/scripts/latlong.html
 var R = 6371; // km
 var dLat = (lat2-lat1).toRad();
 var dLon = (lon2-lon1).toRad();
 lat1 = lat1.toRad(), lat2 = lat2.toRad();

 var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
		 Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
		 Math.sin(dLon/2) * Math.sin(dLon/2);
 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
 var d = R * c;
 */
auto CalculateDistance( Angle latitude1, Angle longtitude1, Angle latitude2, Angle longtitude2 ) -> Angle
{
    auto radius = Kilometers{ 6371 }; // Earth's radius

	// Get the difference between our two points then convert the difference into radians
    auto latDelta = Convert(latitude2 - latitude1);
    auto lonDelta = Convert(longtitude2 - longtitude1);

    latitude1     = Convert(latitude1);
    latitude2     = Convert(latitude2);

	auto a = pow ( sin(latDelta/2), 2 ) +
			 cos(latitude1) * cos(latitude2) *
			 pow ( sin(lonDelta/2), 2 );

	auto c = 2 * atan2( sqrt(a), sqrt( 1 - a ));
	auto d = radius * c;

	return d;
}

// Convert our passed value to Radians
auto Convert( const Angle angle ) -> Radians
{
	return angle * (M_PI/180);
}<commit_msg>Spaces versus tabs again :|<commit_after>/*
 *  Harversine.c
 *  Haversine
 *
 *  Created by Jaime Rios on 2/16/08.
 *
 */

#include "Harversine.h"

#include <math.h> // For PI

/*
 Haversine Formula
 R = earth’s radius (mean radius = 6,371km)
 Δlat = lat2− lat1
 Δlong = long2− long1
 a = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2)
 c = 2.atan2(√a, √(1−a))
 d = R.c

 JavaScript Example from http://www.movable-type.co.uk/scripts/latlong.html
 var R = 6371; // km
 var dLat = (lat2-lat1).toRad();
 var dLon = (lon2-lon1).toRad();
 lat1 = lat1.toRad(), lat2 = lat2.toRad();

 var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
		 Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
		 Math.sin(dLon/2) * Math.sin(dLon/2);
 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
 var d = R * c;
 */
auto CalculateDistance( Angle latitude1, Angle longtitude1, Angle latitude2, Angle longtitude2 ) -> Angle
{
    auto radius = Kilometers{ 6371 }; // Earth's radius

	// Get the difference between our two points then convert the difference into radians
    auto latDelta = Convert(latitude2 - latitude1);
    auto lonDelta = Convert(longtitude2 - longtitude1);

    latitude1     = Convert(latitude1);
    latitude2     = Convert(latitude2);

    auto a = pow ( sin(latDelta/2), 2 ) +
             cos(latitude1) * cos(latitude2) *
             pow ( sin(lonDelta/2), 2 );

    auto c = 2 * atan2( sqrt(a), sqrt( 1 - a ));
    auto d = radius * c;

	return d;
}

// Convert our passed value to Radians
auto Convert( const Angle angle ) -> Radians
{
	return angle * (M_PI/180);
}<|endoftext|>


<commit_before>#include <cstdio>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#include <map>
#include <cstring>
#include <string>
#include <set>
#include <stack>
#define pb push_back

#define mp make_pair
#define f first
#define s second
#define ll long long

using namespace std;

class Solver {

    vector <int> current_set;
    int N, count_set;

    vector<vector<int>> edges;
    vector<int> L;
    map <int, int> R;
    vector<int> viz;
    set<vector<int>> unique_sets;

 public:
     Solver(int _N) {
         //
         N = _N;
         count_set = 0;
         edges.assign(N, vector<int>());
         L.assign(N,0);
         viz.assign(N, 0);
     }

     bool intersect(int mask1, int mask2) {
         return (mask1 & mask2);
     }

     void to_set(int mask) {
         cout << "{";
         vector<int> Ans;
         for (int i = 0; i < N; ++i) {
             if (mask & (1 << i)) {
                 Ans.push_back(i + 1);
             }
         }
         for (int i = 0; i < Ans.size() - 1; ++i) {
             cout << Ans[i] << ",";
         }
         if (Ans.size() > 0) {
             cout << Ans[Ans.size() - 1];
         }
         cout << "}";
     }

     bool pairup(int node) {
         if (viz[node]) {
             return 0;
         }
         viz[node] = 1;
         for (auto vec: edges[node]) {
             if (R.find(vec) == R.end()) {
                 L[node] = vec;
                 R[vec] = node;
                 return 1;
             }
         }
         for (auto vec: edges[node]) {
             if (pairup(R[vec])) {
                 L[node] = vec;
                 R[vec] = node;
                 return 1;
             }
         }
         return 0;
     }

     void debug_set(const vector<int>& v) {
         cout << "**********\n";
         for (int i = 0; i < v.size(); ++i) {
             to_set(v[i]);
             cout << "\n";
         }
     }
     bool do_matching(const vector<int>&to_check) {
         //debug_set(to_check);
         //
         int ret = prime_condition(to_check);
         if (ret == 0) {
             return 0;
         }
         for (int i = 0; i < N; ++i) {
            edges[i].clear();
            viz[i] = 0;
            L[i] = -1;
            R.clear();
         }
         for (int i = 0; i < N; ++i) {
             for (int j = 0; j < N; ++j) {
                 if (to_check[j] & (1 << i)) {
                     edges[i].push_back(j);
                 }
             }
         }
         for (int i = 0; i < N; ++i) {
             if (edges[i].size() == 0) {
                 return 0;
             }
         }
         int change = 1;
         while(change) {
             change = 0;
             for (int i = 0; i < N; ++i) {
                 viz[i] = 0;
             }
             for (int i = 0; i < N; ++i) {
                 if (L[i] == -1) {
                     change |= pairup(i);
                 }
             }
         }

         for (int i = 0; i < N; ++i) {
             if (L[i] == -1) {
                 cout << "FAIL ON\n";
                 cout << "is prime condition? " << ret << "\n";
                 write_set(L, to_check);

                 cout << "graph: \n";
                 for (int k = 0; k < N; ++k) {
                     cerr << k + 1 << " -> " ;
                     for (auto vec: edges[k]) {
                         to_set(to_check[vec]);
                     }
                     cerr << "\n";
                 }
                 return 0;
             }
         }
         /*
         cout << "set: " << count_set << "\n";
         write_set(L, to_check);
         */
         //cerr << "MATCHING DONE?\n";
         /*
         vector<int> tmp(to_check);
         sort(tmp.begin(), tmp.end());
         unique_sets.insert(tmp);
         */
         return 1;
     }

     void generate_all_sets(int k) {
         if (k == N) {
             count_set += do_matching(current_set);
         } else {
             int start = 0;
             if (k != 0) {
                 start = current_set[k - 1];
             }
             for (int mask = start + 1; mask < (1 << N); ++mask) {
                 bool flag = false;
                 for (int i = 0; i < k; ++i) {
                     if (!intersect(mask, current_set[i])) {
                         flag = true;
                         break;
                     }
                 }
                 if (flag) {
                     continue;
                 }
                 current_set.push_back(mask);
                 generate_all_sets(k + 1);
                 current_set.pop_back();
             }
         }
     }

     bool prime_condition(const vector<int>&to_check) {
         for (int i = 0; i < N; ++i) {
             for (int j = 0; j < N; ++j) {
                 if (i == j) {
                     continue;
                 }
                 bool can_go = false;
                 for (int k = 0; k < N; ++k) {
                     if (intersect(to_check[k], 1<<i) && !intersect(to_check[k], 1<<j)) {
                         can_go = true;
                         break;
                     }
                 }
                 if (!can_go) {
                     //cerr << "pair: " << i + 1 << " " << j + 1 << "\n";
                     return 0;
                 }
             }
         }
         return 1;
     }

     void write_set(vector<int>& L, const vector<int>&v) {
         for (int i = 0; i < N; ++i) {
             if (L[i] == -1) {
                 cout << "?";
             } else {
                 cout << i + 1;
             }
             cout << " -> ";
             if (L[i] != -1) {
                 to_set(v[L[i]]);
             }
             cout << "\n";
        }
     }
     void checker() {
         generate_all_sets(0);
         cout << "Found " << count_set << " matchings\n";
         cout << "Found " << unique_sets.size() << " unique sets\n";
     }
};
int main() {
  ifstream cin("test.in");

  int N; cin >> N;
  N = 4;
  Solver G(N);

  G.checker();
  //int res = G.do_matching({127,191,223,239,247,251,253,254,22019,10764,3376,12736,341,405,16808});
  //cout << res << "\n";
  //cout << G.prime_condition({7,6,5});
  return 0;
}
<commit_msg>last chance<commit_after>#include <cstdio>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#include <map>
#include <cstring>
#include <string>
#include <set>
#include <omp.h>
#include <stack>
#define pb push_back

#define mp make_pair
#define f first
#define s second
#define ll long long

using namespace std;

class Graph {
 public:
    Graph(int _N) {
        N = _N;
        viz.assign(N, 0);
        L.assign(N, -1);
        R.assign(N, -1);
        edges.assign(N, vector<int>());
        edge_mask.assign(N, 0);
    }
    void addEdge(int x, int y) {
        edges[x].push_back(y);
        edge_mask[y] |= (1 << x);
    }

    bool pairup(int node) {
        if (viz[node]) {
             return 0;
        }
        viz[node] = 1;
        for (auto vec: edges[node]) {
            if (R[vec] == -1) {
                L[node] = vec;
                R[vec] = node;
                return 1;
            }
        }
        for (auto vec: edges[node]) {
            if (pairup(R[vec])) {
                L[node] = vec;
                R[vec] = node;
                return 1;
            }
        }
        return 0;
    }
    bool maxMatch() {
        int change = 1;
        while(change) {
            change = 0;
            for (int i = 0; i < N; ++i) {
                viz[i] = 0;
            }
            for (int i = 0; i < N; ++i) {
                if (L[i] == -1) {
                    change |= pairup(i);
                }
            }
        }
        for (int i = 0; i < N; ++i) {
            if (L[i] == -1) {
                return 0;
            }
        }
        return 1;
    }
    void write() {
        for (int i = 0; i < N; ++i) {
            vector<int> row;
            for (int j = 0; j < N; ++j) {
                if ( edge_mask[i] & (1 << j) ) {
                    row.push_back(j);
                }
            }
            if (R[i] != -1) {
                cerr << R[i] << " -> ";
            } else {
                cerr << "?" <<  " -> ";
            }
            cerr << "{";
            for (int j = 0; j < row.size() - 1; ++j) {
                cerr << row[j] << ",";
            }
            cerr << *row.rbegin() << "}\n";
        }
    }
    int N;
    vector<int> viz, L, R, edge_mask;
    vector<vector<int>> edges;
};

class Solver {

    vector <int> current_set;
    int N, count_set;
    set<vector<int>> unique_sets;

 public:
     Solver(int _N) {
         N = _N;
         count_set = 0;
     }

     bool intersect(int mask1, int mask2) {
         return (mask1 & mask2);
     }

     bool do_matching(const vector<int>& to_check) {
         //debug_set(to_check);
         //
         int ret = prime_condition(to_check);
         if (ret == 0) {
             return 0;
         }
         Graph G(N);
         // prob cache misses?
         for (int i = 0; i < N; ++i) {
             for (int j = 0; j < N; ++j) {
                 if (to_check[j] & (1 << i)) {
                     G.addEdge(i, j);
                 }
             }
         }
         for (int i = 0; i < N; ++i) {
             if (G.edges[i].size() == 0) {
                 return 0;
             }
         }

         if (!G.maxMatch()) {
                 cout << "FAIL ON\n";
                 cout << "is prime condition? " << ret << "\n";
                 G.write();
                 return 0;
         }
         //cout << "set: " << count_set << "\n";
         //cerr << "MATCHING DONE?\n";
         /*
         vector<int> tmp(to_check);
         sort(tmp.begin(), tmp.end());
         unique_sets.insert(tmp);
         */
         return 1;
     }

     void generate_all_sets(int k, vector<int>& current_set) {
         if (k == N) {
             count += do_matching(current_set);
         } else {
             int start = 0;
             if (k != 0) {
                 start = current_set[k - 1];
             }
             #pragma omp parallel for
             for (int mask = start + 1; mask < (1 << N); ++mask) {
                 bool flag = false;
                 for (int i = 0; i < k; ++i) {
                     if (!intersect(mask, current_set[i])) {
                         flag = true;
                         break;
                     }
                 }
                 if (!flag) {
                     vector<int> next_set(current_set);
                     next_set.push_back(mask);
                     generate_all_sets(k + 1, next_set);
                 }
             }
         }
     }

     bool prime_condition(const vector<int>&to_check) {
         for (int i = 0; i < N; ++i) {
             for (int j = 0; j < N; ++j) {
                 if (i == j) {
                     continue;
                 }
                 bool can_go = false;
                 for (int k = 0; k < N; ++k) {
                     if (intersect(to_check[k], 1<<i) && !intersect(to_check[k], 1<<j)) {
                         can_go = true;
//                         cerr << "fails with " << i << " " << j << "\n";
                         break;
                     }
                 }
                 if (!can_go) {
//                     cerr << "pair: " << i + 1 << " " << j + 1 << "\n";
                     return 0;
                 }
             }
         }
         return 1;
     }
    void debug_(vector<int>& edges) {
        for (int i = 0; i < edges.size(); ++i) {
            for (int j = 0; j < N; ++j) {
                if (edges[i] & (1 << j)) {
                    cout << j + 1 << " " ;
                }
            }
            cout << "\n";
        }
        cout << "\n";
    }
     void checker() {
         vector<int> empty_vector;
         generate_all_sets(0, empty_vector);
         cout << "Found " << count_set << " matchings\n";
         cout << "Found " << unique_sets.size() << " unique sets\n";
         /*
         for (auto edges: unique_sets) {
             debug_(edges);
         }
         */
     }
};
int main() {
  ifstream cin("test.in");

  int N; cin >> N;
  Solver G(N);
  G.checker();
//  int res = G.do_matching({35,77,161,53,19,13,102,122});
 // cout << res << "\n";
  return 0;
}
<|endoftext|>


<commit_before>// @(#)root/utils:$Id$
// Author: Axel Naumann, 2014-04-07

/*************************************************************************
 * Copyright (C) 1995-2014, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

// Provides bindings to TCling (compiled with rtti) from rootcling (compiled
// without rtti).

#include "TCling.h"
#include "TROOT.h"
#include "TFile.h"
#include "TClass.h"
#include "TStreamerInfo.h"
#include <iostream>
#include "TProtoClass.h"

std::string gPCMFilename;
std::vector<std::string> gClassesToStore;
std::vector<std::string> gTypedefsToStore;
std::vector<std::string> gAncestorPCMsNames;

extern "C"
const char*** TROOT__GetExtraInterpreterArgs() {
   return &TROOT::GetExtraInterpreterArgs();
}

extern "C"
cling::Interpreter* TCling__GetInterpreter()
{
   static bool sInitialized = false;
   gROOT; // trigger initialization
   if (!sInitialized) {
      gCling->SetClassAutoloading(false);
      sInitialized = true;
   }
   return ((TCling*)gCling)->GetInterpreter();
}

extern "C"
void InitializeStreamerInfoROOTFile(const char* filename)
{
   gPCMFilename = filename;
}

extern "C"
void AddStreamerInfoToROOTFile(const char* normName)
{
   gClassesToStore.emplace_back(normName);
}

extern "C"
void AddTypedefToROOTFile(const char* tdname)
{
   gTypedefsToStore.push_back(tdname);
}

extern "C"
void AddAncestorPCMROOTFile(const char* pcmName)
{
   gAncestorPCMsNames.emplace_back(pcmName);
}

extern "C"
bool CloseStreamerInfoROOTFile()
{
   // Write all persistent TClasses.

   // Avoid plugins.
   TVirtualStreamerInfo::SetFactory(new TStreamerInfo());

   TObjArray protoClasses;
   for (const auto normName: gClassesToStore) {
      TClass* cl = TClass::GetClass(normName.c_str(), kTRUE /*load*/);
      if (!cl) {
         std::cerr << "ERROR in CloseStreamerInfoROOTFile(): cannot find class "
                   << normName << '\n';
         return false;
      }
      // If the class is not persistent we return success.
      if (cl->GetClassVersion() == 0)
         continue;
      // If this is a proxied collection then offsets are not needed.
      if (cl->GetCollectionProxy())
         continue;
      cl->Property(); // Force initialization of the bits and property fields.
      protoClasses.AddLast(new TProtoClass(cl));
   }

   TObjArray typedefs;
   for (const auto dtname: gTypedefsToStore) {
      TDataType* dt = (TDataType*)gROOT->GetListOfTypes()->FindObject(dtname.c_str());
      if (!dt) {
         std::cerr << "ERROR in CloseStreamerInfoROOTFile(): cannot find class "
                   << dtname << '\n';
         return false;
      }
      if (dt->GetType() == -1) {
         dt->Property(); // Force initialization of the bits and property fields.
         dt->GetTypeName(); // Force caching of type name.
         typedefs.AddLast(dt);
      }
   }

   // Don't use TFile::Open(); we don't need plugins.
   TFile dictFile(gPCMFilename.c_str(), "RECREATE");
   if (dictFile.IsZombie())
      return false;
   // Instead of plugins:
   protoClasses.Write("__ProtoClasses", TObject::kSingleKey);
   protoClasses.Delete();
   typedefs.Write("__Typedefs", TObject::kSingleKey);

   dictFile.WriteObjectAny(&gAncestorPCMsNames, "std::vector<std::string>", "__AncestorPCMsNames");

   return true;
}
<commit_msg>Make sure that the list of bases is complete.<commit_after>// @(#)root/utils:$Id$
// Author: Axel Naumann, 2014-04-07

/*************************************************************************
 * Copyright (C) 1995-2014, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

// Provides bindings to TCling (compiled with rtti) from rootcling (compiled
// without rtti).

#include "TCling.h"
#include "TROOT.h"
#include "TFile.h"
#include "TClass.h"
#include "TStreamerInfo.h"
#include <iostream>
#include "TProtoClass.h"

std::string gPCMFilename;
std::vector<std::string> gClassesToStore;
std::vector<std::string> gTypedefsToStore;
std::vector<std::string> gAncestorPCMsNames;

extern "C"
const char*** TROOT__GetExtraInterpreterArgs() {
   return &TROOT::GetExtraInterpreterArgs();
}

extern "C"
cling::Interpreter* TCling__GetInterpreter()
{
   static bool sInitialized = false;
   gROOT; // trigger initialization
   if (!sInitialized) {
      gCling->SetClassAutoloading(false);
      sInitialized = true;
   }
   return ((TCling*)gCling)->GetInterpreter();
}

extern "C"
void InitializeStreamerInfoROOTFile(const char* filename)
{
   gPCMFilename = filename;
}

extern "C"
void AddStreamerInfoToROOTFile(const char* normName)
{
   gClassesToStore.emplace_back(normName);
}

extern "C"
void AddTypedefToROOTFile(const char* tdname)
{
   gTypedefsToStore.push_back(tdname);
}

extern "C"
void AddAncestorPCMROOTFile(const char* pcmName)
{
   gAncestorPCMsNames.emplace_back(pcmName);
}

extern "C"
bool CloseStreamerInfoROOTFile()
{
   // Write all persistent TClasses.

   // Avoid plugins.
   TVirtualStreamerInfo::SetFactory(new TStreamerInfo());

   TObjArray protoClasses;
   for (const auto normName: gClassesToStore) {
      TClass* cl = TClass::GetClass(normName.c_str(), kTRUE /*load*/);
      if (!cl) {
         std::cerr << "ERROR in CloseStreamerInfoROOTFile(): cannot find class "
                   << normName << '\n';
         return false;
      }
      // If the class is not persistent we return success.
      if (cl->GetClassVersion() == 0)
         continue;
      // If this is a proxied collection then offsets are not needed.
      if (cl->GetCollectionProxy())
         continue;
      cl->Property(); // Force initialization of the bits and property fields.
      cl->GetListOfBases();

      protoClasses.AddLast(new TProtoClass(cl));
   }

   TObjArray typedefs;
   for (const auto dtname: gTypedefsToStore) {
      TDataType* dt = (TDataType*)gROOT->GetListOfTypes()->FindObject(dtname.c_str());
      if (!dt) {
         std::cerr << "ERROR in CloseStreamerInfoROOTFile(): cannot find class "
                   << dtname << '\n';
         return false;
      }
      if (dt->GetType() == -1) {
         dt->Property(); // Force initialization of the bits and property fields.
         dt->GetTypeName(); // Force caching of type name.
         typedefs.AddLast(dt);
      }
   }

   // Don't use TFile::Open(); we don't need plugins.
   TFile dictFile(gPCMFilename.c_str(), "RECREATE");
   if (dictFile.IsZombie())
      return false;
   // Instead of plugins:
   protoClasses.Write("__ProtoClasses", TObject::kSingleKey);
   protoClasses.Delete();
   typedefs.Write("__Typedefs", TObject::kSingleKey);

   dictFile.WriteObjectAny(&gAncestorPCMsNames, "std::vector<std::string>", "__AncestorPCMsNames");

   return true;
}
<|endoftext|>