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

#include "TemplateScanner.hxx"

#ifndef _COMPHELPER_SERVICEFACTORY_HXX
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COMPHELPER_DOCUMENTCONSTANTS_HXX
#include <comphelper/documentconstants.hxx>
#endif

#include <tools/debug.hxx>
#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>

#ifndef _COM_SUN_STAR_FRAME_XDOCUMENTTEMPLATES_HPP_
#include <com/sun/star/frame/XDocumentTemplates.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HPP_
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENTACCESS_HPP_
#include <com/sun/star/ucb/XContentAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif

#include <set>

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

namespace {

const ::rtl::OUString TITLE            = ::rtl::OUString::createFromAscii ("Title");
const ::rtl::OUString TARGET_DIR_URL   = ::rtl::OUString::createFromAscii ("TargetDirURL");
const ::rtl::OUString DESCRIPTION      = ::rtl::OUString::createFromAscii ("TypeDescription");
const ::rtl::OUString TARGET_URL       = ::rtl::OUString::createFromAscii ("TargetURL");

const ::rtl::OUString DOCTEMPLATES     = ::rtl::OUString::createFromAscii ("com.sun.star.frame.DocumentTemplates");

//  These strings are used to find impress templates in the tree of
//  template files.  Should probably be determined dynamically.
const ::rtl::OUString IMPRESS_BIN_TEMPLATE = ::rtl::OUString::createFromAscii ("application/vnd.stardivision.impress");
const ::rtl::OUString IMPRESS_XML_TEMPLATE = MIMETYPE_VND_SUN_XML_IMPRESS;
// The following id comes from the bugdoc in #i2764#.
const ::rtl::OUString IMPRESS_XML_TEMPLATE_B = ::rtl::OUString::createFromAscii ("Impress 2.0");
const ::rtl::OUString IMPRESS_XML_TEMPLATE_OASIS = MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION;

class FolderDescriptor
{
public:
    FolderDescriptor (
        int nPriority,
        const ::rtl::OUString& rsTitle,
        const ::rtl::OUString& rsTargetDir,
        const ::rtl::OUString& rsContentIdentifier,
        const Reference<com::sun::star::ucb::XCommandEnvironment>& rxFolderEnvironment)
        : mnPriority(nPriority),
          msTitle(rsTitle),
          msTargetDir(rsTargetDir),
          msContentIdentifier(rsContentIdentifier),
          mxFolderEnvironment(rxFolderEnvironment)
    { }
    int mnPriority;
    ::rtl::OUString msTitle;
    ::rtl::OUString msTargetDir;
    ::rtl::OUString msContentIdentifier;
    //    Reference<sdbc::XResultSet> mxFolderResultSet;
    Reference<com::sun::star::ucb::XCommandEnvironment> mxFolderEnvironment;

    class Comparator { public:
        bool operator() (const FolderDescriptor& r1, const FolderDescriptor& r2)
        { return r1.mnPriority < r2.mnPriority; }
    };
};

/** Use a heuristic based on the URL of a top-level template folder to
    assign a priority that is used to sort the folders.
*/
int Classify (const ::rtl::OUString& rsTitle, const ::rtl::OUString& rsURL)
{
    int nPriority (0);

    if (rsURL.getLength() == 0)
        nPriority = 100;
    else if (rsURL.indexOf(::rtl::OUString::createFromAscii("presnt"))>=0)
    {
        nPriority = 30;
    }
    else if (rsURL.indexOf(::rtl::OUString::createFromAscii("layout"))>=0)
    {
        nPriority = 20;
    }
    else if (rsURL.indexOf(::rtl::OUString::createFromAscii("educate"))>=0)
    {
        nPriority = 40;
    }
    else if (rsURL.indexOf(::rtl::OUString::createFromAscii("finance"))>=0)
    {
        nPriority = 40;
    }
    else
    {
        // All other folders are taken for user supplied and have the
        // highest priority.
        nPriority = 10;
    }

    return nPriority;
}

} // end of anonymous namespace

namespace sd
{

class TemplateScanner::FolderDescriptorList
    : public ::std::multiset<FolderDescriptor,FolderDescriptor::Comparator>
{
};

TemplateScanner::TemplateScanner (void)
    : meState(INITIALIZE_SCANNING),
      maFolderContent(),
      mpTemplateDirectory(NULL),
      maFolderList(),
      mpLastAddedEntry(NULL),
      mxTemplateRoot(),
      mxFolderEnvironment(),
      mxEntryEnvironment(),
      mxFolderResultSet(),
      mxEntryResultSet(),
      mpFolderDescriptors(new FolderDescriptorList())
{
    //  empty;
}

TemplateScanner::~TemplateScanner (void)
{
    mpFolderDescriptors.reset();

    // Delete all entries of the template list that have not been
    // transferred to another object.
    std::vector<TemplateDir*>::iterator I;
    for (I=maFolderList.begin(); I!=maFolderList.end(); I++)
        if (*I != NULL)
            delete *I;
}

TemplateScanner::State TemplateScanner::GetTemplateRoot (void)
{
    State eNextState (INITIALIZE_FOLDER_SCANNING);

    Reference<lang::XMultiServiceFactory> xFactory = ::comphelper::getProcessServiceFactory ();
    DBG_ASSERT (xFactory.is(), "TemplateScanner::GetTemplateRoot: xFactory is NULL");

    if (xFactory.is())
    {
        Reference<frame::XDocumentTemplates> xTemplates (
            xFactory->createInstance (DOCTEMPLATES), UNO_QUERY);
        DBG_ASSERT (xTemplates.is(), "TemplateScanner::GetTemplateRoot: xTemplates is NULL");

        if (xTemplates.is())
            mxTemplateRoot = xTemplates->getContent();
        else
            eNextState = ERROR;
    }
    else
        eNextState = ERROR;

    return eNextState;
}

TemplateScanner::State TemplateScanner::InitializeEntryScanning (void)
{
    State eNextState (SCAN_ENTRY);

    if (maFolderContent.isFolder())
    {
        mxEntryEnvironment = Reference<com::sun::star::ucb::XCommandEnvironment>();

        //  We are interested only in three properties: the entry's name,
        //  its URL, and its content type.
        Sequence<rtl::OUString> aProps (3);
        aProps[0] = TITLE;
        aProps[1] = TARGET_URL;
        aProps[2] = DESCRIPTION;

        //  Create a cursor to iterate over the templates in this folders.
        ::ucb::ResultSetInclude eInclude = ::ucb::INCLUDE_DOCUMENTS_ONLY;
        mxEntryResultSet = Reference<com::sun::star::sdbc::XResultSet>(
            maFolderContent.createCursor(aProps, eInclude));
    }
    else
        eNextState = ERROR;

    return eNextState;
}

TemplateScanner::State TemplateScanner::ScanEntry (void)
{
    State eNextState (ERROR);

    Reference<com::sun::star::ucb::XContentAccess> xContentAccess (mxEntryResultSet, UNO_QUERY);
    Reference<com::sun::star::sdbc::XRow> xRow (mxEntryResultSet, UNO_QUERY);

    if (xContentAccess.is() && xRow.is() && mxEntryResultSet.is())
    {
        if (mxEntryResultSet->next())
        {
            ::rtl::OUString sTitle (xRow->getString (1));
            ::rtl::OUString sTargetURL (xRow->getString (2));
            ::rtl::OUString sContentType (xRow->getString (3));

            ::rtl::OUString aId = xContentAccess->queryContentIdentifierString();
            ::ucb::Content  aContent = ::ucb::Content (aId, mxEntryEnvironment);
            if (aContent.isDocument ())
            {
                //  Check wether the entry is an impress template.  If so
                //  add a new entry to the resulting list (which is created
                //  first if necessary).
                if (    (sContentType == MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION_TEMPLATE)
                    ||  (sContentType == IMPRESS_XML_TEMPLATE_OASIS)
                    ||  (sContentType == IMPRESS_BIN_TEMPLATE)
                    ||  (sContentType == IMPRESS_XML_TEMPLATE)
                    ||  (sContentType == IMPRESS_XML_TEMPLATE_B))
                {
                    mpLastAddedEntry = new TemplateEntry(sTitle, sTargetURL);
                    mpTemplateDirectory->maEntries.push_back(mpLastAddedEntry);
                }
            }

            // Continue scanning entries.
            eNextState = SCAN_ENTRY;
        }
        else
        {
            if (mpTemplateDirectory->maEntries.empty())
            {
                delete mpTemplateDirectory;
                mpTemplateDirectory = NULL;
            }
            else
            {
                ::vos::OGuard aGuard(Application::GetSolarMutex());
                maFolderList.push_back(mpTemplateDirectory);
            }

            // Continue with scanning the next folder.
            eNextState = SCAN_FOLDER;
        }
    }

    return eNextState;
}

TemplateScanner::State TemplateScanner::InitializeFolderScanning (void)
{
    State eNextState (ERROR);

    mxFolderResultSet = Reference<sdbc::XResultSet>();

    try
    {
        //  Create content for template folders.
        mxFolderEnvironment = Reference<com::sun::star::ucb::XCommandEnvironment>();
        ::ucb::Content aTemplateDir (mxTemplateRoot, mxFolderEnvironment);

        //  Define the list of properties we are interested in.
        Sequence<rtl::OUString> aProps (2);
        aProps[0] = TITLE;
        aProps[1] = TARGET_DIR_URL;

        //  Create an cursor to iterate over the template folders.
        ::ucb::ResultSetInclude eInclude = ::ucb::INCLUDE_FOLDERS_ONLY;
        mxFolderResultSet = Reference<sdbc::XResultSet>(
            aTemplateDir.createCursor(aProps, eInclude));
        if (mxFolderResultSet.is())
            eNextState = GATHER_FOLDER_LIST;
    }
    catch (::com::sun::star::uno::Exception&)
    {
       eNextState = ERROR;
    }

    return eNextState;
}

TemplateScanner::State TemplateScanner::GatherFolderList (void)
{
    State eNextState (ERROR);

    Reference<com::sun::star::ucb::XContentAccess> xContentAccess (mxFolderResultSet, UNO_QUERY);
    if (xContentAccess.is() && mxFolderResultSet.is())
    {
        while (mxFolderResultSet->next())
        {
            Reference<sdbc::XRow> xRow (mxFolderResultSet, UNO_QUERY);
            if (xRow.is())
            {
                ::rtl::OUString sTitle (xRow->getString (1));
                ::rtl::OUString sTargetDir (xRow->getString (2));
                ::rtl::OUString aId = xContentAccess->queryContentIdentifierString();

                mpFolderDescriptors->insert(
                    FolderDescriptor(
                        Classify(sTitle,sTargetDir),
                        sTitle,
                        sTargetDir,
                        aId,
                        mxFolderEnvironment));
            }
        }

        eNextState = SCAN_FOLDER;
    }

    return eNextState;
}

TemplateScanner::State TemplateScanner::ScanFolder (void)
{
    State eNextState (ERROR);

    if (mpFolderDescriptors->size() > 0)
    {
        FolderDescriptor aDescriptor (*mpFolderDescriptors->begin());
        mpFolderDescriptors->erase(mpFolderDescriptors->begin());

        ::rtl::OUString sTitle (aDescriptor.msTitle);
        ::rtl::OUString sTargetDir (aDescriptor.msTargetDir);
        ::rtl::OUString aId (aDescriptor.msContentIdentifier);

        maFolderContent = ::ucb::Content (aId, aDescriptor.mxFolderEnvironment);
        if (maFolderContent.isFolder())
        {
            // Scan the folder and insert it into the list of template
            // folders.
            mpTemplateDirectory = new TemplateDir (sTitle, sTargetDir);
            if (mpTemplateDirectory != NULL)
            {
                // Continue with scanning all entries in the folder.
                eNextState = INITIALIZE_ENTRY_SCAN;
            }
        }
    }
    else
    {
        eNextState = DONE;
    }

    return eNextState;
}

void TemplateScanner::Scan (void)
{
    while (HasNextStep())
        RunNextStep();
}

std::vector<TemplateDir*>& TemplateScanner::GetFolderList (void)
{
    return maFolderList;
}

void TemplateScanner::RunNextStep (void)
{
    switch (meState)
    {
        case INITIALIZE_SCANNING:
            meState = GetTemplateRoot();
            break;

        case INITIALIZE_FOLDER_SCANNING:
            meState = InitializeFolderScanning();
            break;

        case SCAN_FOLDER:
            meState = ScanFolder();
            break;

        case GATHER_FOLDER_LIST:
            meState = GatherFolderList();
            break;

        case INITIALIZE_ENTRY_SCAN:
            meState = InitializeEntryScanning();
            break;

        case SCAN_ENTRY:
            meState = ScanEntry();
            break;
    }

    switch (meState)
    {
        case DONE:
        case ERROR:
            mxTemplateRoot.clear();
            mxTemplateRoot.clear();
            mxFolderEnvironment.clear();
            mxEntryEnvironment.clear();
            mxFolderResultSet.clear();
            mxEntryResultSet.clear();
            mpLastAddedEntry = NULL;
            break;
    }
}

bool TemplateScanner::HasNextStep (void)
{
    switch (meState)
    {
        case DONE:
        case ERROR:
            return false;

        default:
            return true;
    }
}

const TemplateEntry* TemplateScanner::GetLastAddedEntry (void) const
{
    return mpLastAddedEntry;
}

}
<commit_msg>INTEGRATION: CWS pchfix02 (1.9.104); FILE MERGED 2006/09/01 17:36:56 kaib 1.9.104.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TemplateScanner.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 18:34:51 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#include "TemplateScanner.hxx"

#ifndef _COMPHELPER_SERVICEFACTORY_HXX
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COMPHELPER_DOCUMENTCONSTANTS_HXX
#include <comphelper/documentconstants.hxx>
#endif

#include <tools/debug.hxx>
#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>

#ifndef _COM_SUN_STAR_FRAME_XDOCUMENTTEMPLATES_HPP_
#include <com/sun/star/frame/XDocumentTemplates.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HPP_
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENTACCESS_HPP_
#include <com/sun/star/ucb/XContentAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif

#include <set>

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

namespace {

const ::rtl::OUString TITLE            = ::rtl::OUString::createFromAscii ("Title");
const ::rtl::OUString TARGET_DIR_URL   = ::rtl::OUString::createFromAscii ("TargetDirURL");
const ::rtl::OUString DESCRIPTION      = ::rtl::OUString::createFromAscii ("TypeDescription");
const ::rtl::OUString TARGET_URL       = ::rtl::OUString::createFromAscii ("TargetURL");

const ::rtl::OUString DOCTEMPLATES     = ::rtl::OUString::createFromAscii ("com.sun.star.frame.DocumentTemplates");

//  These strings are used to find impress templates in the tree of
//  template files.  Should probably be determined dynamically.
const ::rtl::OUString IMPRESS_BIN_TEMPLATE = ::rtl::OUString::createFromAscii ("application/vnd.stardivision.impress");
const ::rtl::OUString IMPRESS_XML_TEMPLATE = MIMETYPE_VND_SUN_XML_IMPRESS;
// The following id comes from the bugdoc in #i2764#.
const ::rtl::OUString IMPRESS_XML_TEMPLATE_B = ::rtl::OUString::createFromAscii ("Impress 2.0");
const ::rtl::OUString IMPRESS_XML_TEMPLATE_OASIS = MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION;

class FolderDescriptor
{
public:
    FolderDescriptor (
        int nPriority,
        const ::rtl::OUString& rsTitle,
        const ::rtl::OUString& rsTargetDir,
        const ::rtl::OUString& rsContentIdentifier,
        const Reference<com::sun::star::ucb::XCommandEnvironment>& rxFolderEnvironment)
        : mnPriority(nPriority),
          msTitle(rsTitle),
          msTargetDir(rsTargetDir),
          msContentIdentifier(rsContentIdentifier),
          mxFolderEnvironment(rxFolderEnvironment)
    { }
    int mnPriority;
    ::rtl::OUString msTitle;
    ::rtl::OUString msTargetDir;
    ::rtl::OUString msContentIdentifier;
    //    Reference<sdbc::XResultSet> mxFolderResultSet;
    Reference<com::sun::star::ucb::XCommandEnvironment> mxFolderEnvironment;

    class Comparator { public:
        bool operator() (const FolderDescriptor& r1, const FolderDescriptor& r2)
        { return r1.mnPriority < r2.mnPriority; }
    };
};

/** Use a heuristic based on the URL of a top-level template folder to
    assign a priority that is used to sort the folders.
*/
int Classify (const ::rtl::OUString& rsTitle, const ::rtl::OUString& rsURL)
{
    int nPriority (0);

    if (rsURL.getLength() == 0)
        nPriority = 100;
    else if (rsURL.indexOf(::rtl::OUString::createFromAscii("presnt"))>=0)
    {
        nPriority = 30;
    }
    else if (rsURL.indexOf(::rtl::OUString::createFromAscii("layout"))>=0)
    {
        nPriority = 20;
    }
    else if (rsURL.indexOf(::rtl::OUString::createFromAscii("educate"))>=0)
    {
        nPriority = 40;
    }
    else if (rsURL.indexOf(::rtl::OUString::createFromAscii("finance"))>=0)
    {
        nPriority = 40;
    }
    else
    {
        // All other folders are taken for user supplied and have the
        // highest priority.
        nPriority = 10;
    }

    return nPriority;
}

} // end of anonymous namespace

namespace sd
{

class TemplateScanner::FolderDescriptorList
    : public ::std::multiset<FolderDescriptor,FolderDescriptor::Comparator>
{
};

TemplateScanner::TemplateScanner (void)
    : meState(INITIALIZE_SCANNING),
      maFolderContent(),
      mpTemplateDirectory(NULL),
      maFolderList(),
      mpLastAddedEntry(NULL),
      mxTemplateRoot(),
      mxFolderEnvironment(),
      mxEntryEnvironment(),
      mxFolderResultSet(),
      mxEntryResultSet(),
      mpFolderDescriptors(new FolderDescriptorList())
{
    //  empty;
}

TemplateScanner::~TemplateScanner (void)
{
    mpFolderDescriptors.reset();

    // Delete all entries of the template list that have not been
    // transferred to another object.
    std::vector<TemplateDir*>::iterator I;
    for (I=maFolderList.begin(); I!=maFolderList.end(); I++)
        if (*I != NULL)
            delete *I;
}

TemplateScanner::State TemplateScanner::GetTemplateRoot (void)
{
    State eNextState (INITIALIZE_FOLDER_SCANNING);

    Reference<lang::XMultiServiceFactory> xFactory = ::comphelper::getProcessServiceFactory ();
    DBG_ASSERT (xFactory.is(), "TemplateScanner::GetTemplateRoot: xFactory is NULL");

    if (xFactory.is())
    {
        Reference<frame::XDocumentTemplates> xTemplates (
            xFactory->createInstance (DOCTEMPLATES), UNO_QUERY);
        DBG_ASSERT (xTemplates.is(), "TemplateScanner::GetTemplateRoot: xTemplates is NULL");

        if (xTemplates.is())
            mxTemplateRoot = xTemplates->getContent();
        else
            eNextState = ERROR;
    }
    else
        eNextState = ERROR;

    return eNextState;
}

TemplateScanner::State TemplateScanner::InitializeEntryScanning (void)
{
    State eNextState (SCAN_ENTRY);

    if (maFolderContent.isFolder())
    {
        mxEntryEnvironment = Reference<com::sun::star::ucb::XCommandEnvironment>();

        //  We are interested only in three properties: the entry's name,
        //  its URL, and its content type.
        Sequence<rtl::OUString> aProps (3);
        aProps[0] = TITLE;
        aProps[1] = TARGET_URL;
        aProps[2] = DESCRIPTION;

        //  Create a cursor to iterate over the templates in this folders.
        ::ucb::ResultSetInclude eInclude = ::ucb::INCLUDE_DOCUMENTS_ONLY;
        mxEntryResultSet = Reference<com::sun::star::sdbc::XResultSet>(
            maFolderContent.createCursor(aProps, eInclude));
    }
    else
        eNextState = ERROR;

    return eNextState;
}

TemplateScanner::State TemplateScanner::ScanEntry (void)
{
    State eNextState (ERROR);

    Reference<com::sun::star::ucb::XContentAccess> xContentAccess (mxEntryResultSet, UNO_QUERY);
    Reference<com::sun::star::sdbc::XRow> xRow (mxEntryResultSet, UNO_QUERY);

    if (xContentAccess.is() && xRow.is() && mxEntryResultSet.is())
    {
        if (mxEntryResultSet->next())
        {
            ::rtl::OUString sTitle (xRow->getString (1));
            ::rtl::OUString sTargetURL (xRow->getString (2));
            ::rtl::OUString sContentType (xRow->getString (3));

            ::rtl::OUString aId = xContentAccess->queryContentIdentifierString();
            ::ucb::Content  aContent = ::ucb::Content (aId, mxEntryEnvironment);
            if (aContent.isDocument ())
            {
                //  Check wether the entry is an impress template.  If so
                //  add a new entry to the resulting list (which is created
                //  first if necessary).
                if (    (sContentType == MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION_TEMPLATE)
                    ||  (sContentType == IMPRESS_XML_TEMPLATE_OASIS)
                    ||  (sContentType == IMPRESS_BIN_TEMPLATE)
                    ||  (sContentType == IMPRESS_XML_TEMPLATE)
                    ||  (sContentType == IMPRESS_XML_TEMPLATE_B))
                {
                    mpLastAddedEntry = new TemplateEntry(sTitle, sTargetURL);
                    mpTemplateDirectory->maEntries.push_back(mpLastAddedEntry);
                }
            }

            // Continue scanning entries.
            eNextState = SCAN_ENTRY;
        }
        else
        {
            if (mpTemplateDirectory->maEntries.empty())
            {
                delete mpTemplateDirectory;
                mpTemplateDirectory = NULL;
            }
            else
            {
                ::vos::OGuard aGuard(Application::GetSolarMutex());
                maFolderList.push_back(mpTemplateDirectory);
            }

            // Continue with scanning the next folder.
            eNextState = SCAN_FOLDER;
        }
    }

    return eNextState;
}

TemplateScanner::State TemplateScanner::InitializeFolderScanning (void)
{
    State eNextState (ERROR);

    mxFolderResultSet = Reference<sdbc::XResultSet>();

    try
    {
        //  Create content for template folders.
        mxFolderEnvironment = Reference<com::sun::star::ucb::XCommandEnvironment>();
        ::ucb::Content aTemplateDir (mxTemplateRoot, mxFolderEnvironment);

        //  Define the list of properties we are interested in.
        Sequence<rtl::OUString> aProps (2);
        aProps[0] = TITLE;
        aProps[1] = TARGET_DIR_URL;

        //  Create an cursor to iterate over the template folders.
        ::ucb::ResultSetInclude eInclude = ::ucb::INCLUDE_FOLDERS_ONLY;
        mxFolderResultSet = Reference<sdbc::XResultSet>(
            aTemplateDir.createCursor(aProps, eInclude));
        if (mxFolderResultSet.is())
            eNextState = GATHER_FOLDER_LIST;
    }
    catch (::com::sun::star::uno::Exception&)
    {
       eNextState = ERROR;
    }

    return eNextState;
}

TemplateScanner::State TemplateScanner::GatherFolderList (void)
{
    State eNextState (ERROR);

    Reference<com::sun::star::ucb::XContentAccess> xContentAccess (mxFolderResultSet, UNO_QUERY);
    if (xContentAccess.is() && mxFolderResultSet.is())
    {
        while (mxFolderResultSet->next())
        {
            Reference<sdbc::XRow> xRow (mxFolderResultSet, UNO_QUERY);
            if (xRow.is())
            {
                ::rtl::OUString sTitle (xRow->getString (1));
                ::rtl::OUString sTargetDir (xRow->getString (2));
                ::rtl::OUString aId = xContentAccess->queryContentIdentifierString();

                mpFolderDescriptors->insert(
                    FolderDescriptor(
                        Classify(sTitle,sTargetDir),
                        sTitle,
                        sTargetDir,
                        aId,
                        mxFolderEnvironment));
            }
        }

        eNextState = SCAN_FOLDER;
    }

    return eNextState;
}

TemplateScanner::State TemplateScanner::ScanFolder (void)
{
    State eNextState (ERROR);

    if (mpFolderDescriptors->size() > 0)
    {
        FolderDescriptor aDescriptor (*mpFolderDescriptors->begin());
        mpFolderDescriptors->erase(mpFolderDescriptors->begin());

        ::rtl::OUString sTitle (aDescriptor.msTitle);
        ::rtl::OUString sTargetDir (aDescriptor.msTargetDir);
        ::rtl::OUString aId (aDescriptor.msContentIdentifier);

        maFolderContent = ::ucb::Content (aId, aDescriptor.mxFolderEnvironment);
        if (maFolderContent.isFolder())
        {
            // Scan the folder and insert it into the list of template
            // folders.
            mpTemplateDirectory = new TemplateDir (sTitle, sTargetDir);
            if (mpTemplateDirectory != NULL)
            {
                // Continue with scanning all entries in the folder.
                eNextState = INITIALIZE_ENTRY_SCAN;
            }
        }
    }
    else
    {
        eNextState = DONE;
    }

    return eNextState;
}

void TemplateScanner::Scan (void)
{
    while (HasNextStep())
        RunNextStep();
}

std::vector<TemplateDir*>& TemplateScanner::GetFolderList (void)
{
    return maFolderList;
}

void TemplateScanner::RunNextStep (void)
{
    switch (meState)
    {
        case INITIALIZE_SCANNING:
            meState = GetTemplateRoot();
            break;

        case INITIALIZE_FOLDER_SCANNING:
            meState = InitializeFolderScanning();
            break;

        case SCAN_FOLDER:
            meState = ScanFolder();
            break;

        case GATHER_FOLDER_LIST:
            meState = GatherFolderList();
            break;

        case INITIALIZE_ENTRY_SCAN:
            meState = InitializeEntryScanning();
            break;

        case SCAN_ENTRY:
            meState = ScanEntry();
            break;
    }

    switch (meState)
    {
        case DONE:
        case ERROR:
            mxTemplateRoot.clear();
            mxTemplateRoot.clear();
            mxFolderEnvironment.clear();
            mxEntryEnvironment.clear();
            mxFolderResultSet.clear();
            mxEntryResultSet.clear();
            mpLastAddedEntry = NULL;
            break;
    }
}

bool TemplateScanner::HasNextStep (void)
{
    switch (meState)
    {
        case DONE:
        case ERROR:
            return false;

        default:
            return true;
    }
}

const TemplateEntry* TemplateScanner::GetLastAddedEntry (void) const
{
    return mpLastAddedEntry;
}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: TemplateScanner.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: pjunck $ $Date: 2004-10-28 13:26:09 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "TemplateScanner.hxx"

#ifndef _OSL_TIME_H_
#include <osl/time.h>
#endif

#ifndef _VOS_MUTEX_HXX
#include <vos/mutex.hxx>
#endif

#ifndef _SFXAPP_HXX
#include <sfx2/app.hxx>
#endif

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

using namespace ::rtl;
using namespace ::ucb;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::ucb;

namespace {

const OUString TITLE            = OUString::createFromAscii ("Title");
const OUString TARGET_DIR_URL   = OUString::createFromAscii ("TargetDirURL");
const OUString DESCRIPTION      = OUString::createFromAscii ("TypeDescription");
const OUString TARGET_URL       = OUString::createFromAscii ("TargetURL");

const OUString DOCTEMPLATES     = OUString::createFromAscii ("com.sun.star.frame.DocumentTemplates");

//  These strings are used to find impress templates in the tree of
//  template files.  Should probably be determined dynamically.
const OUString IMPRESS_BIN_TEMPLATE = OUString::createFromAscii ("application/vnd.stardivision.impress");
const OUString IMPRESS_XML_TEMPLATE = OUString::createFromAscii ("application/vnd.sun.xml.impress");
// The following id comes from the bugdoc in #i2764#.
const OUString IMPRESS_XML_TEMPLATE_B = OUString::createFromAscii ("Impress 2.0");
const OUString IMPRESS_XML_TEMPLATE_OASIS = OUString::createFromAscii ("application/x-vnd.oasis.openoffice.presentation");

} // end of anonymous namespace

namespace sd
{

TemplateScanner::TemplateScanner (void)
{
    //  empty;
}

TemplateScanner::~TemplateScanner (void)
{
    // Delete all entries of the template list that have not been
    // transferred to another object.
    std::vector<TemplateDir*>::iterator I;
    for (I=maFolderList.begin(); I!=maFolderList.end(); I++)
        if (*I != NULL)
            delete *I;
}

void TemplateScanner::GetTemplateRoot (void)
{
    Reference<lang::XMultiServiceFactory> xFactory =
        ::comphelper::getProcessServiceFactory ();
    DBG_ASSERT (xFactory.is(),
        "TemplateScanner::GetTemplateRoot: xFactory is NULL");

    Reference<frame::XDocumentTemplates> xTemplates (
        xFactory->createInstance (DOCTEMPLATES), UNO_QUERY);
    DBG_ASSERT (xTemplates.is(),
        "TemplateScanner::GetTemplateRoot: xTemplates is NULL");

    if (xTemplates.is())
        mxTemplateRoot = xTemplates->getContent();

}

void TemplateScanner::ScanEntries (Content& rRoot, TemplateDir* pDir)
{
    Reference<XCommandEnvironment> aCmdEnv;

    //  We are interested only in three properties: the entry's name,
    //  its URL, and its content type.
    Sequence<OUString> aProps (3);
    aProps[0] = TITLE;
    aProps[1] = TARGET_URL;
    aProps[2] = DESCRIPTION;

    //  Create a cursor to iterate over the templates in this folders.
    ResultSetInclude eInclude = INCLUDE_DOCUMENTS_ONLY;
    Reference<XResultSet> xResultSet (rRoot.createCursor (aProps, eInclude));

    if (xResultSet.is())
    {
        Reference<XContentAccess> xContentAccess (xResultSet, UNO_QUERY);
        Reference<XRow> xRow (xResultSet, UNO_QUERY);

        //  Iterate over the template folder.
        while (xResultSet->next())
        {
            OUString aTitle (xRow->getString (1));
            OUString aTargetURL (xRow->getString (2));
            OUString aContentType (xRow->getString (3));

            OUString aId = xContentAccess->queryContentIdentifierString();
            Content  aContent = Content (aId, aCmdEnv);
            if ( ! aContent.isDocument ())
                continue;

            //  Check wether the entry is an impress template.  If so add a
            //  new entry to the resulting list (which is created first if
            //  necessary).
            if (    (aContentType == IMPRESS_XML_TEMPLATE_OASIS)
                ||  (aContentType == IMPRESS_BIN_TEMPLATE)
                ||  (aContentType == IMPRESS_XML_TEMPLATE)
                ||  (aContentType == IMPRESS_XML_TEMPLATE_B))
                pDir->m_aEntries.push_back (
                    new TemplateEntry (aTitle, aTargetURL));
        }
    }
}

void TemplateScanner::ScanFolders (void)
{
    try
    {
        //  Create content for template folders.
        Reference<XCommandEnvironment> aCmdEnv;
        Content aTemplateDir (mxTemplateRoot, aCmdEnv);

        //  Define the list of properties we are interested in.
        Sequence<OUString> aProps (2);
        aProps[0] = TITLE;
        aProps[1] = TARGET_DIR_URL;

        //  Create an cursor to iterate over the template folders.
        ResultSetInclude eInclude = INCLUDE_FOLDERS_ONLY;
        Reference<XResultSet> xResultSet (aTemplateDir.createCursor (
            aProps, eInclude));

        if (xResultSet.is())
        {
            Reference<XContentAccess> xContentAccess (xResultSet, UNO_QUERY);

            while (xResultSet->next())
            {
                Reference<XRow> xRow (xResultSet, UNO_QUERY);
                if ( ! xRow.is())
                    continue;
                OUString aTitle (xRow->getString (1));
                OUString aTargetDir (xRow->getString (2));

                OUString aId = xContentAccess->queryContentIdentifierString();
                Content  aContent = Content (aId, aCmdEnv);
                if (aContent.isFolder())
                {
                    //  Scan the folder and insert it into the list of
                    //  template folders.
                    TemplateDir* pDir = new TemplateDir (aTitle, aTargetDir);
                    if (pDir != NULL)
                    {
                        ScanEntries (aContent, pDir);
                        if (pDir->m_aEntries.empty())
                            delete pDir;
                        else
                        {
                            ::vos::OGuard aGuard(Application::GetSolarMutex());
                            maFolderList.push_back(pDir);
                        }
                    }
                }
            }
        }
    }
    catch(::com::sun::star::uno::Exception&)
    {
        //  Ignore all exceptions.
    }
}

void TemplateScanner::Scan (void)
{
    GetTemplateRoot ();
    ScanFolders ();
}

std::vector<TemplateDir*>& TemplateScanner::GetFolderList (void)
{
    return maFolderList;
}

}
<commit_msg>INTEGRATION: CWS impress10 (1.3.8); FILE MERGED 2004/09/22 12:28:45 af 1.3.8.1: #i34247# Code cleanup to avoid valgrind warning.<commit_after>/*************************************************************************
 *
 *  $RCSfile: TemplateScanner.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2004-11-26 15:09:53 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "TemplateScanner.hxx"

#ifndef _OSL_TIME_H_
#include <osl/time.h>
#endif

#ifndef _VOS_MUTEX_HXX
#include <vos/mutex.hxx>
#endif

#ifndef _SFXAPP_HXX
#include <sfx2/app.hxx>
#endif

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

using namespace ::rtl;
using namespace ::ucb;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::ucb;

namespace {

const OUString TITLE            = OUString::createFromAscii ("Title");
const OUString TARGET_DIR_URL   = OUString::createFromAscii ("TargetDirURL");
const OUString DESCRIPTION      = OUString::createFromAscii ("TypeDescription");
const OUString TARGET_URL       = OUString::createFromAscii ("TargetURL");

const OUString DOCTEMPLATES     = OUString::createFromAscii ("com.sun.star.frame.DocumentTemplates");

//  These strings are used to find impress templates in the tree of
//  template files.  Should probably be determined dynamically.
const OUString IMPRESS_BIN_TEMPLATE = OUString::createFromAscii ("application/vnd.stardivision.impress");
const OUString IMPRESS_XML_TEMPLATE = OUString::createFromAscii ("application/vnd.sun.xml.impress");
// The following id comes from the bugdoc in #i2764#.
const OUString IMPRESS_XML_TEMPLATE_B = OUString::createFromAscii ("Impress 2.0");
const OUString IMPRESS_XML_TEMPLATE_OASIS = OUString::createFromAscii ("application/x-vnd.oasis.openoffice.presentation");

} // end of anonymous namespace

namespace sd
{

TemplateScanner::TemplateScanner (void)
{
    //  empty;
}

TemplateScanner::~TemplateScanner (void)
{
    // Delete all entries of the template list that have not been
    // transferred to another object.
    std::vector<TemplateDir*>::iterator I;
    for (I=maFolderList.begin(); I!=maFolderList.end(); I++)
        if (*I != NULL)
            delete *I;
}

void TemplateScanner::GetTemplateRoot (void)
{
    Reference<lang::XMultiServiceFactory> xFactory =
        ::comphelper::getProcessServiceFactory ();
    DBG_ASSERT (xFactory.is(),
        "TemplateScanner::GetTemplateRoot: xFactory is NULL");

    Reference<frame::XDocumentTemplates> xTemplates (
        xFactory->createInstance (DOCTEMPLATES), UNO_QUERY);
    DBG_ASSERT (xTemplates.is(),
        "TemplateScanner::GetTemplateRoot: xTemplates is NULL");

    if (xTemplates.is())
        mxTemplateRoot = xTemplates->getContent();

}

void TemplateScanner::ScanEntries (Content& rRoot, TemplateDir* pDir)
{
    Reference<XCommandEnvironment> aCmdEnv;

    //  We are interested only in three properties: the entry's name,
    //  its URL, and its content type.
    Sequence<OUString> aProps (3);
    aProps[0] = TITLE;
    aProps[1] = TARGET_URL;
    aProps[2] = DESCRIPTION;

    //  Create a cursor to iterate over the templates in this folders.
    ResultSetInclude eInclude = INCLUDE_DOCUMENTS_ONLY;
    Reference<XResultSet> xResultSet (rRoot.createCursor (aProps, eInclude));

    if (xResultSet.is())
    {
        Reference<XContentAccess> xContentAccess (xResultSet, UNO_QUERY);
        Reference<XRow> xRow (xResultSet, UNO_QUERY);

        //  Iterate over the template folder.
        while (xResultSet->next())
        {
            OUString aTitle (xRow->getString (1));
            OUString aTargetURL (xRow->getString (2));
            OUString aContentType (xRow->getString (3));

            OUString aId = xContentAccess->queryContentIdentifierString();
            Content  aContent = Content (aId, aCmdEnv);
            if ( ! aContent.isDocument ())
                continue;

            //  Check wether the entry is an impress template.  If so add a
            //  new entry to the resulting list (which is created first if
            //  necessary).
            if (    (aContentType == IMPRESS_XML_TEMPLATE_OASIS)
                ||  (aContentType == IMPRESS_BIN_TEMPLATE)
                ||  (aContentType == IMPRESS_XML_TEMPLATE)
                ||  (aContentType == IMPRESS_XML_TEMPLATE_B))
                pDir->m_aEntries.push_back (
                    new TemplateEntry (aTitle, aTargetURL));
        }
    }
}

void TemplateScanner::ScanFolders (void)
{
    try
    {
        //  Create content for template folders.
        Reference<XCommandEnvironment> aCmdEnv;
        Content aTemplateDir (mxTemplateRoot, aCmdEnv);

        //  Define the list of properties we are interested in.
        Sequence<OUString> aProps (2);
        aProps[0] = TITLE;
        aProps[1] = TARGET_DIR_URL;

        //  Create an cursor to iterate over the template folders.
        ResultSetInclude eInclude = INCLUDE_FOLDERS_ONLY;
        Reference<XResultSet> xResultSet (aTemplateDir.createCursor (
            aProps, eInclude));

        if (xResultSet.is())
        {
            Reference<XContentAccess> xContentAccess (xResultSet, UNO_QUERY);

            while (xResultSet->next())
            {
                Reference<XRow> xRow (xResultSet, UNO_QUERY);
                if ( ! xRow.is())
                    continue;

                OUString aTitle (xRow->getString (1));
                OUString aTargetDir (xRow->getString (2));

                OUString aId = xContentAccess->queryContentIdentifierString();
                Content  aContent = Content (aId, aCmdEnv);
                if (aContent.isFolder())
                {
                    //  Scan the folder and insert it into the list of
                    //  template folders.
                    TemplateDir* pDir = new TemplateDir (aTitle, aTargetDir);
                    if (pDir != NULL)
                    {
                        ScanEntries (aContent, pDir);
                        if (pDir->m_aEntries.empty())
                            delete pDir;
                        else
                        {
                            ::vos::OGuard aGuard(Application::GetSolarMutex());
                            maFolderList.push_back(pDir);
                        }
                    }
                }
            }
        }
    }
    catch(::com::sun::star::uno::Exception&)
    {
        //  Ignore all exceptions.
    }
}

void TemplateScanner::Scan (void)
{
    GetTemplateRoot ();
    ScanFolders ();
}

std::vector<TemplateDir*>& TemplateScanner::GetFolderList (void)
{
    return maFolderList;
}

}
<|endoftext|>


<commit_before><commit_msg>[ADDED] load wiggle<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include <map>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "board.h"
#include "search.h"
#include "opening.h"
using namespace std;

map<string, string> parse_query()
{
    const char *qstr = getenv("QUERY_STRING");
    string s;
    if (qstr)
	s = qstr;

    map<string, string> query;
    while (!s.empty()) {
	string::size_type amp = s.find('&');
	string param = s.substr(0, amp);
	s = (amp == string::npos) ? string() : s.substr(amp + 1);

	string::size_type eq = param.find('=');
	if (eq != string::npos)
	    query[param.substr(0, eq)] = param.substr(eq + 1);
	else
	    query[param] = "";
    }
    return query;
}

Move parse_move(string fourcc)
{
    if (fourcc == "----")
	return PASS;
    int x, y, d;
    char c;
    if (fourcc.length() == 4 &&
	sscanf(fourcc.c_str(), "%1X%1X%c%1d", &x, &y, &c, &d) == 4 &&
	x >= 1 && x <= 14 && y >= 1 && y <= 14 &&
	tolower(c) >= 'a' && tolower(c) <= 'u' &&
	d >= 0 && d <= 7)
	return Move(fourcc.c_str());
    else
	return INVALID_MOVE;
}

Move com_move(Board* b, int time_ms)
{
    Move move;
    int score = 100;
    quiet = true;

    move = opening_move(b);
    if (move == INVALID_MOVE) {
	SearchResult r;
	if (b->turn() < 25)
	    r = search_negascout(b, 10, time_ms / 2, time_ms);
	else if (b->turn() < 27)
	    r = wld(b, 1000);
	else
	    r = perfect(b);
	move = r.first;
	score = r.second;
    }

    return move;
}

int main(int argc, char *argv[])
{
    nice(5);
    srand(time(NULL));

    map<string, string> params = parse_query();
    cout << "Content-Type: text/plain\r\n\r\n";

    int time_limit;
    switch (atoi(params["l"].c_str())) {
    case 2:
        time_limit = 3000;
        break;
    case 3:
        time_limit = 10000;
        break;
    default:
        time_limit = 1000;
        break;
    }

    Board b;
    istringstream path(params["b"]);
    string fourcc;
    while (getline(path, fourcc, '/')) {
	if (fourcc.empty())
	    continue;
	Move m = parse_move(fourcc);
	if (m == INVALID_MOVE || !b.is_valid_move(m)) {
	    cout << "XXXX invalid move " << fourcc;
	    return 0;
	}
	b.do_move(m);
    }
    Move m = com_move(&b, time_limit);
    cout << m.fourcc();

    return 0;
}
<commit_msg>Fix missing include.<commit_after>#include <iostream>
#include <sstream>
#include <map>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include "board.h"
#include "search.h"
#include "opening.h"
using namespace std;

map<string, string> parse_query()
{
    const char *qstr = getenv("QUERY_STRING");
    string s;
    if (qstr)
	s = qstr;

    map<string, string> query;
    while (!s.empty()) {
	string::size_type amp = s.find('&');
	string param = s.substr(0, amp);
	s = (amp == string::npos) ? string() : s.substr(amp + 1);

	string::size_type eq = param.find('=');
	if (eq != string::npos)
	    query[param.substr(0, eq)] = param.substr(eq + 1);
	else
	    query[param] = "";
    }
    return query;
}

Move parse_move(string fourcc)
{
    if (fourcc == "----")
	return PASS;
    int x, y, d;
    char c;
    if (fourcc.length() == 4 &&
	sscanf(fourcc.c_str(), "%1X%1X%c%1d", &x, &y, &c, &d) == 4 &&
	x >= 1 && x <= 14 && y >= 1 && y <= 14 &&
	tolower(c) >= 'a' && tolower(c) <= 'u' &&
	d >= 0 && d <= 7)
	return Move(fourcc.c_str());
    else
	return INVALID_MOVE;
}

Move com_move(Board* b, int time_ms)
{
    Move move;
    int score = 100;
    quiet = true;

    move = opening_move(b);
    if (move == INVALID_MOVE) {
	SearchResult r;
	if (b->turn() < 25)
	    r = search_negascout(b, 10, time_ms / 2, time_ms);
	else if (b->turn() < 27)
	    r = wld(b, 1000);
	else
	    r = perfect(b);
	move = r.first;
	score = r.second;
    }

    return move;
}

int main(int argc, char *argv[])
{
    nice(5);
    srand(time(NULL));

    map<string, string> params = parse_query();
    cout << "Content-Type: text/plain\r\n\r\n";

    int time_limit;
    switch (atoi(params["l"].c_str())) {
    case 2:
        time_limit = 3000;
        break;
    case 3:
        time_limit = 10000;
        break;
    default:
        time_limit = 1000;
        break;
    }

    Board b;
    istringstream path(params["b"]);
    string fourcc;
    while (getline(path, fourcc, '/')) {
	if (fourcc.empty())
	    continue;
	Move m = parse_move(fourcc);
	if (m == INVALID_MOVE || !b.is_valid_move(m)) {
	    cout << "XXXX invalid move " << fourcc;
	    return 0;
	}
	b.do_move(m);
    }
    Move m = com_move(&b, time_limit);
    cout << m.fourcc();

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>

using std::cout; using std::cin; using std::endl; using std::string; using std::pair;

int main()
{
    pair<string, int> max_duplicated;
    int count = 0;
    for (string str, prestr; cin >> str; prestr = str)
    {
        if (str == prestr) ++count;
        else count = 0;
        if (count > max_duplicated.second) max_duplicated = {prestr, count};
    }

    if (max_duplicated.first.empty()) cout << "There's no duplicated string." << endl;
    else cout << "the word " << max_duplicated.first << " occurred " << max_duplicated.second + 1 << " times. " << endl;

    return 0;
}

//it's a easy way to understand for primary learner
/*
#include<iostream>
#include <vector>
#include <string>
using namespace std;

int main()
{
	vector<string> svec;
	string str;
	while (cin >> str)
	{
		svec.push_back(str);
	}
	vector<string>::iterator it = svec.begin();//auto it = svec.begin();
	int bigNum = 1, countNum = 1;
	string bigStr, countStr;
	while (it != svec.end()-1)
	{
		if (*it == *(it + 1))
		{
			++countNum;
			countStr = *it;
		}
		else
		{
			if (countNum>bigNum)
			{
				bigStr = countStr;
				bigNum = countNum;
			}
		}
		++it;
	}
	if (bigNum==1)
	{
		cout << " there is no  duplicated string." << endl;
	}
	else
	{
		cout << "the word " << bigStr << " occurred  " << bigNum << "times." << endl;
	}
	system("pause");
	return 0;
}
*/
<commit_msg>Update ex5_14.cpp<commit_after>#include <iostream>
#include <string>

using std::cout; using std::cin; using std::endl; using std::string; using std::pair;

int main()
{
    pair<string, int> max_duplicated;
    int count = 0;
    for (string str, prestr; cin >> str; prestr = str)
    {
        if (str == prestr) ++count;
        else count = 0;
        if (count > max_duplicated.second) max_duplicated = {prestr, count};
    }

    if (max_duplicated.first.empty()) cout << "There's no duplicated string." << endl;
    else cout << "the word " << max_duplicated.first << " occurred " << max_duplicated.second + 1 << " times. " << endl;

    return 0;
}

//it's a easy way to understand for primary learner
/*
#include<iostream>
#include <vector>
#include <string>
using namespace std;

int main()
{
	vector<string> svec;
	string str;
	while (cin>>str )
	{
		svec.push_back(str);
	}

	vector<string>::iterator it = svec.begin();//auto it = svec.begin();
	int bigNum = 1, countNum = 1;
	string bigStr, countStr;
	while (svec.size()>0&&it != svec.end() - 1  )
	{
		if (*it == *(it + 1))
		{
			++countNum;
			countStr = *it;
		}
		else
		{
			countNum = 0;
		}
		if (countNum>bigNum)
		{
			bigStr = countStr;
			bigNum = countNum;
		}
		++it;
	}
	if (bigNum==1)
	{
		cout << " there is no  duplicated string." << endl;
	}
	else
	{
		cout << "the word " << bigStr << " occurred  " << bigNum << " times." << endl;
	}
	system("pause");
	return 0;
}
*/
<|endoftext|>


<commit_before><commit_msg>sin.inl: CORDIC for sin<commit_after>/// @brief provides CORDIC for cos function
/// @ref see H. Dawid, H. Meyr, "CORDIC Algorithms and Architectures"

#include "./../../fixed_point_lib/src/CORDIC/lut/lut.hpp"

namespace std {
    template<typename T, size_t n, size_t f, class op, class up>
    utils::number<T, n, f, op, up> sin(utils::number<T, n, f, op, up> const& val)
    {
        #define pi fixed_point(3.141592653589793)
        #define pi2 fixed_point(6.283185307179586)
        #define pi_half fixed_point(1.5707963267948965)

        typedef utils::number<T, n, f, op, up> fixed_point;
        using utils::cordic::lut;
        BOOST_STATIC_ASSERT(std::numeric_limits<fixed_point>::is_signed);

        // convergence interval for CORDIC rotations is [-pi/2, pi/2].
        // So one has to map input angle to that interval
        fixed_point arg(0);
        int sign(1);
        {
            // reduce argument to interval [-pi, +pi] with sign preserving
            fixed_point const x = pi - std::fmod(val, pi2);
            if (x < -pi_half) {
                arg = x + pi;

                sign = -1;
            }
            else if (x > pi_half) {
                arg = x - pi;

                sign = -1;
            }
            else {
                arg = x;
            }
        }

        typedef lut<f, fixed_point> lut_type;
        static lut_type const angles = lut_type::build_arctan_lut();

        // normalization factor: see page 10, table 24.1 and pages 4-5, equations
        // (5)-(6)
        // factor converges to the limit 1.64676 very fast: it tooks 8 iterations
        // only. 8 iterations correpsonds to precision of size 0.007812 for
        // angle approximation
        static fixed_point norm_factor(1.0 / lut_type::compute_circular_scale(f));

        // rotation mode: see page 6
        // shift sequence is just 0, 1, ... (circular coordinate system)
        fixed_point x(norm_factor), y(0.0), z(arg);
        fixed_point x1, y1, z1;
        BOOST_FOREACH(size_t i, boost::irange<size_t>(0, f, 1))
        {
            int const sign = (z > fixed_point(0)) ? 1 : -1;
            fixed_point const x_scaled = fixed_point::wrap(sign * (x.value() >> i));
            fixed_point const y_scaled = fixed_point::wrap(sign * (y.value() >> i));

            x1 = fixed_point(x - y_scaled);
            y1 = fixed_point(y + x_scaled);
            z1 = fixed_point(z - fixed_point((sign > 0) ? angles[i] : -angles[i]));

            x = x1; y = y1; z = z1;
        }

        return (sign > 0) ? y : -y;

        #undef pi
        #undef pi2
        #undef pi_half
    }
}
<|endoftext|>


<commit_before>#pragma once

#include <memory>

#include <QtCore/QObject>
#include <QtCore/QUuid>
#include <QVariant>

#include "PortType.hpp"
#include "NodeData.hpp"

#include "Serializable.hpp"
#include "ConnectionState.hpp"
#include "ConnectionGeometry.hpp"

class QPointF;

namespace std
{
template<>
struct hash<QUuid>
{
  inline
  std::size_t
  operator()(QUuid const& uid) const
  {
    return qHash(uid);
  }
};
}

namespace QtNodes
{

class Node;
class NodeData;
class ConnectionGraphicsObject;

///
class Connection
  : public QObject
  , public Serializable
{

  Q_OBJECT

public:

  /// New Connection is attached to the port of the given Node.
  /// The port has parameters (portType, portIndex).
  /// The opposite connection end will require anothre port.
  Connection(PortType portType,
             Node& node,
             PortIndex portIndex);

  Connection(Node& nodeIn,
             PortIndex portIndexIn,
             Node& nodeOut,
             PortIndex portIndexOut);

  ~Connection();

public:

  QJsonObject
  save() const override;

public:

  QUuid
  id() const;

  /// Remembers the end being dragged.
  /// Invalidates Node address.
  /// Grabs mouse.
  void
  setRequiredPort(PortType portType);
  PortType
  requiredPort() const;

  void
  setGraphicsObject(std::unique_ptr<ConnectionGraphicsObject>&& graphics);

  /// Assigns a node to the required port.
  /// It is assumed that there is a required port, no extra checks
  void
  setNodeToPort(Node& node,
                PortType portType,
                PortIndex portIndex);

  void
  removeFromNodes() const;

public:

  ConnectionGraphicsObject&
  getConnectionGraphicsObject() const;

  ConnectionState const &
  connectionState() const;
  ConnectionState&
  connectionState();

  ConnectionGeometry&
  connectionGeometry();

  ConnectionGeometry const&
  connectionGeometry() const;

  Node*
  getNode(PortType portType) const;

  Node*&
  getNode(PortType portType);

  PortIndex
  getPortIndex(PortType portType) const;

  void
  clearNode(PortType portType);

  NodeDataType
  dataType() const;

public: // data propagation

  void
  propagateData(std::shared_ptr<NodeData> nodeData) const;
  void
  propagateEmptyData() const;

private:

  QUuid _id;

private:

  Node* _outNode = nullptr;
  Node* _inNode  = nullptr;

  PortIndex _outPortIndex;
  PortIndex _inPortIndex;

private:

  ConnectionState    _connectionState;
  ConnectionGeometry _connectionGeometry;

  std::unique_ptr<ConnectionGraphicsObject> _connectionGraphicsObject;

signals:
  void
  updated(Connection& conn) const;
};
}
<commit_msg>Update Connection.hpp<commit_after>#pragma once

#include <memory>

#include <QtCore/QObject>
#include <QtCore/QUuid>
#include <QVariant>

#include "PortType.hpp"
#include "NodeData.hpp"

#include "Serializable.hpp"
#include "ConnectionState.hpp"
#include "ConnectionGeometry.hpp"

class QPointF;

namespace std
{
template<>
struct hash<QUuid>
{
  inline
  std::size_t
  operator()(QUuid const& uid) const
  {
    return qHash(uid);
  }
};
}

namespace QtNodes
{

class Node;
class NodeData;
class ConnectionGraphicsObject;

///
class NODE_EDITOR_PUBLIC  Connection
  : public QObject
  , public Serializable
{

  Q_OBJECT

public:

  /// New Connection is attached to the port of the given Node.
  /// The port has parameters (portType, portIndex).
  /// The opposite connection end will require anothre port.
  Connection(PortType portType,
             Node& node,
             PortIndex portIndex);

  Connection(Node& nodeIn,
             PortIndex portIndexIn,
             Node& nodeOut,
             PortIndex portIndexOut);

  ~Connection();

public:

  QJsonObject
  save() const override;

public:

  QUuid
  id() const;

  /// Remembers the end being dragged.
  /// Invalidates Node address.
  /// Grabs mouse.
  void
  setRequiredPort(PortType portType);
  PortType
  requiredPort() const;

  void
  setGraphicsObject(std::unique_ptr<ConnectionGraphicsObject>&& graphics);

  /// Assigns a node to the required port.
  /// It is assumed that there is a required port, no extra checks
  void
  setNodeToPort(Node& node,
                PortType portType,
                PortIndex portIndex);

  void
  removeFromNodes() const;

public:

  ConnectionGraphicsObject&
  getConnectionGraphicsObject() const;

  ConnectionState const &
  connectionState() const;
  ConnectionState&
  connectionState();

  ConnectionGeometry&
  connectionGeometry();

  ConnectionGeometry const&
  connectionGeometry() const;

  Node*
  getNode(PortType portType) const;

  Node*&
  getNode(PortType portType);

  PortIndex
  getPortIndex(PortType portType) const;

  void
  clearNode(PortType portType);

  NodeDataType
  dataType() const;

public: // data propagation

  void
  propagateData(std::shared_ptr<NodeData> nodeData) const;
  void
  propagateEmptyData() const;

private:

  QUuid _id;

private:

  Node* _outNode = nullptr;
  Node* _inNode  = nullptr;

  PortIndex _outPortIndex;
  PortIndex _inPortIndex;

private:

  ConnectionState    _connectionState;
  ConnectionGeometry _connectionGeometry;

  std::unique_ptr<ConnectionGraphicsObject> _connectionGraphicsObject;

signals:
  void
  updated(Connection& conn) const;
};
}
<|endoftext|>


<commit_before><commit_msg>pyuno: some comments<commit_after><|endoftext|>


<commit_before>#ifndef WIDGET_HPP
#define WIDGET_HPP

#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/RenderStates.hpp>

namespace cstr
{
	class Widget : public sf::Drawable
	{
		friend class Window;

		public:
			Widget() {};
			virtual ~Widget() {};

		protected:
			virtual bool contains(sf::Vector2i point) = 0;
			virtual void mousePressed() = 0;
			virtual void mouseReleased() = 0;
			virtual void mouseMovedOn() = 0;
			virtual void mouseMovedOff() = 0;
			virtual void textEntered(char c) = 0;

		private:
			virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const = 0;
	};
}

#endif // WIDGET_HPP
<commit_msg>Added a bool getState() function. Defaults to return false.<commit_after>#ifndef WIDGET_HPP
#define WIDGET_HPP

#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/RenderStates.hpp>

namespace cstr
{
	class Widget : public sf::Drawable
	{
		friend class Window;

		public:
			Widget() {};
			virtual ~Widget() {};

			virtual bool getState() const
			{
				return false;
			}

		protected:
			virtual bool contains(sf::Vector2i point) = 0;
			virtual void mousePressed() = 0;
			virtual void mouseReleased() = 0;
			virtual void mouseMovedOn() = 0;
			virtual void mouseMovedOff() = 0;
			virtual void textEntered(char c) = 0;

		private:
			virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const = 0;
	};
}

#endif // WIDGET_HPP
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include "IndexReader.h"
#include <fnord-fts/AnalyzerAdapter.h>

using namespace fnord;

namespace cm {

RefPtr<IndexReader> IndexReader::openIndex(const String& index_path) {
  if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) {
    RAISEF(kIllegalArgumentError, "invalid index path: $0", index_path);
  }

  /* set up feature schema */
  FeatureSchema feature_schema;
  feature_schema.registerFeature("shop_id", 1, 1);
  feature_schema.registerFeature("category1", 2, 1);
  feature_schema.registerFeature("category2", 3, 1);
  feature_schema.registerFeature("category3", 4, 1);
  feature_schema.registerFeature("price_cents", 8, 1);

  feature_schema.registerFeature("title~de", 5, 2);
  feature_schema.registerFeature("description~de", 6, 2);
  feature_schema.registerFeature("size_description~de", 14, 2);
  feature_schema.registerFeature("material_description~de", 15, 2);
  feature_schema.registerFeature("basic_attributes~de", 16, 2);
  feature_schema.registerFeature("tags_as_text~de", 7, 2);
  feature_schema.registerFeature("title~pl", 18, 2);
  feature_schema.registerFeature("description~pl", 19, 2);
  feature_schema.registerFeature("size_description~pl", 20, 2);
  feature_schema.registerFeature("material_description~pl", 21, 2);
  feature_schema.registerFeature("basic_attributes~pl", 22, 2);
  feature_schema.registerFeature("tags_as_text~pl", 23, 2);
  feature_schema.registerFeature("image_filename", 24, 2);

  feature_schema.registerFeature("shop_name", 26, 3);
  feature_schema.registerFeature("shop_platform", 27, 3);
  feature_schema.registerFeature("shop_country", 28, 3);
  feature_schema.registerFeature("shop_rating_alt", 9, 3);
  feature_schema.registerFeature("shop_rating_alt2", 15, 3);
  feature_schema.registerFeature("shop_products_count", 10, 3);
  feature_schema.registerFeature("shop_orders_count", 11, 3);
  feature_schema.registerFeature("shop_rating_count", 12, 3);
  feature_schema.registerFeature("shop_rating_avg", 13, 3);

  /* open mdb */
  auto db_path = FileUtil::joinPaths(index_path, "db");
  FileUtil::mkdir_p(db_path);
  auto db = mdb::MDB::open(db_path, true);

  /* open lucene */
  auto fts_path = FileUtil::joinPaths(index_path, "fts");
  auto fts = fts::IndexReader::open(
      fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)),
      true);

  return RefPtr<IndexReader>(new IndexReader(feature_schema, db, fts));
}

IndexReader::IndexReader(
    FeatureSchema schema,
    RefPtr<mdb::MDB> db,
    std::shared_ptr<fts::IndexReader> fts) :
    schema_(schema),
    db_(db),
    fts_(fts),
    fts_searcher_(new fnord::fts::IndexSearcher(fts_)),
    doc_idx_(new FeatureIndexWriter(&schema_)) {}

IndexReader::~IndexReader() {
  fts_->close();
}

std::shared_ptr<fts::IndexSearcher> IndexReader::ftsSearcher() {
  return fts_searcher_;
}

RefPtr<FeatureIndexWriter> IndexReader::docIndex() {
  return doc_idx_;
}

} // namespace cm
<commit_msg>open mdb with proper map size in IndexReader<commit_after>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include "IndexReader.h"
#include <fnord-fts/AnalyzerAdapter.h>

using namespace fnord;

namespace cm {

RefPtr<IndexReader> IndexReader::openIndex(const String& index_path) {
  if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) {
    RAISEF(kIllegalArgumentError, "invalid index path: $0", index_path);
  }

  /* set up feature schema */
  FeatureSchema feature_schema;
  feature_schema.registerFeature("shop_id", 1, 1);
  feature_schema.registerFeature("category1", 2, 1);
  feature_schema.registerFeature("category2", 3, 1);
  feature_schema.registerFeature("category3", 4, 1);
  feature_schema.registerFeature("price_cents", 8, 1);

  feature_schema.registerFeature("title~de", 5, 2);
  feature_schema.registerFeature("description~de", 6, 2);
  feature_schema.registerFeature("size_description~de", 14, 2);
  feature_schema.registerFeature("material_description~de", 15, 2);
  feature_schema.registerFeature("basic_attributes~de", 16, 2);
  feature_schema.registerFeature("tags_as_text~de", 7, 2);
  feature_schema.registerFeature("title~pl", 18, 2);
  feature_schema.registerFeature("description~pl", 19, 2);
  feature_schema.registerFeature("size_description~pl", 20, 2);
  feature_schema.registerFeature("material_description~pl", 21, 2);
  feature_schema.registerFeature("basic_attributes~pl", 22, 2);
  feature_schema.registerFeature("tags_as_text~pl", 23, 2);
  feature_schema.registerFeature("image_filename", 24, 2);

  feature_schema.registerFeature("shop_name", 26, 3);
  feature_schema.registerFeature("shop_platform", 27, 3);
  feature_schema.registerFeature("shop_country", 28, 3);
  feature_schema.registerFeature("shop_rating_alt", 9, 3);
  feature_schema.registerFeature("shop_rating_alt2", 15, 3);
  feature_schema.registerFeature("shop_products_count", 10, 3);
  feature_schema.registerFeature("shop_orders_count", 11, 3);
  feature_schema.registerFeature("shop_rating_count", 12, 3);
  feature_schema.registerFeature("shop_rating_avg", 13, 3);

  /* open mdb */
  auto db_path = FileUtil::joinPaths(index_path, "db");
  FileUtil::mkdir_p(db_path);
  auto db = mdb::MDB::open(db_path, true, 68719476736lu); // 64 GiB

  /* open lucene */
  auto fts_path = FileUtil::joinPaths(index_path, "fts");
  auto fts = fts::IndexReader::open(
      fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)),
      true);

  return RefPtr<IndexReader>(new IndexReader(feature_schema, db, fts));
}

IndexReader::IndexReader(
    FeatureSchema schema,
    RefPtr<mdb::MDB> db,
    std::shared_ptr<fts::IndexReader> fts) :
    schema_(schema),
    db_(db),
    fts_(fts),
    fts_searcher_(new fnord::fts::IndexSearcher(fts_)),
    doc_idx_(new FeatureIndexWriter(&schema_)) {}

IndexReader::~IndexReader() {
  fts_->close();
}

std::shared_ptr<fts::IndexSearcher> IndexReader::ftsSearcher() {
  return fts_searcher_;
}

RefPtr<FeatureIndexWriter> IndexReader::docIndex() {
  return doc_idx_;
}

} // namespace cm
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: MNSProfileDiscover.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 __MNSProfileDiscover_h___
#define __MNSProfileDiscover_h___

#include "mozilla_profile_discover.h"

#include <sal/types.h>
#include <osl/diagnose.h>
#include <osl/conditn.hxx>
#ifndef _COM_SUN_STAR_MOZILLA_MOZILLPRODUCTTYPE_HPP_
#include <com/sun/star/mozilla/MozillaProductType.hpp>
#endif
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/uno/Sequence.hxx>
#include <rtl/ustring.hxx>

#include <vector>
#include <map>

#ifdef XP_OS2
#define INCL_DOSERRORS
#define INCL_DOSFILEMGR
#include <os2.h>
#endif

using namespace com::sun::star::mozilla;
namespace connectivity
{
    namespace mozab
    {
        class ProfileStruct;
    }
}
typedef ::std::map < ::rtl::OUString, ::connectivity::mozab::ProfileStruct* > ProfileList;
namespace connectivity
{
    namespace mozab
    {
        class ProfileStruct
        {
        public:
            ProfileStruct(MozillaProductType aProduct,::rtl::OUString aProfileName,nsILocalFile * aProfilePath);
            MozillaProductType getProductType() { return product;}
            ::rtl::OUString getProfileName(){ return profileName;}
            ::rtl::OUString getProfilePath() ;
            nsILocalFile    *getProfileLocal(){ return profilePath;}
        protected:
            MozillaProductType product;
            ::rtl::OUString profileName;
            nsCOMPtr<nsILocalFile> profilePath;
        };

        class ProductStruct
        {
        public:
            void setCurrentProfile(::rtl::OUString aProfileName){mCurrentProfileName = aProfileName;}

            ::rtl::OUString mCurrentProfileName;

            ProfileList mProfileList;
        };

        //Used to query profiles information
        class ProfileAccess
        {
        public:

            virtual ~ProfileAccess();
            ProfileAccess();
            ::rtl::OUString getProfilePath( ::com::sun::star::mozilla::MozillaProductType product, const ::rtl::OUString& profileName ) throw (::com::sun::star::uno::RuntimeException);
            ::sal_Int32 getProfileCount( ::com::sun::star::mozilla::MozillaProductType product ) throw (::com::sun::star::uno::RuntimeException);
            ::sal_Int32 getProfileList( ::com::sun::star::mozilla::MozillaProductType product, ::com::sun::star::uno::Sequence< ::rtl::OUString >& list ) throw (::com::sun::star::uno::RuntimeException);
            ::rtl::OUString getDefaultProfile( ::com::sun::star::mozilla::MozillaProductType product ) throw (::com::sun::star::uno::RuntimeException);
            ::sal_Bool SAL_CALL isProfileLocked( ::com::sun::star::mozilla::MozillaProductType product, const ::rtl::OUString& profileName ) throw (::com::sun::star::uno::RuntimeException);
            ::sal_Bool SAL_CALL getProfileExists( ::com::sun::star::mozilla::MozillaProductType product, const ::rtl::OUString& profileName ) throw (::com::sun::star::uno::RuntimeException);

        protected:
            ProductStruct m_ProductProfileList[4];
            sal_Int32 LoadProductsInfo();
            nsresult  LoadMozillaProfiles();
            sal_Int32 LoadXPToolkitProfiles(MozillaProductType product);

            //used by isProfileLocked
            nsresult isExistFileOrSymlink(nsILocalFile* aFile,PRBool *bExist);
            nsresult isLockExist(nsILocalFile* aFile);
        };

    }
}

#endif // __MNSProfileDiscover_h___

<commit_msg>INTEGRATION: CWS cmcfixes48 (1.5.52); FILE MERGED 2008/07/24 13:16:23 cmc 1.5.52.1: #i92087# minimal firefox/etc profile finder implementation<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: MNSProfileDiscover.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 __MNSProfileDiscover_h___
#define __MNSProfileDiscover_h___

#ifndef MINIMAL_PROFILEDISCOVER
#include "mozilla_profile_discover.h"
#endif

#include <sal/types.h>
#include <osl/diagnose.h>
#include <osl/conditn.hxx>
#ifndef _COM_SUN_STAR_MOZILLA_MOZILLPRODUCTTYPE_HPP_
#include <com/sun/star/mozilla/MozillaProductType.hpp>
#endif
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/uno/Sequence.hxx>
#include <rtl/ustring.hxx>

#include <vector>
#include <map>

#ifdef XP_OS2
#define INCL_DOSERRORS
#define INCL_DOSFILEMGR
#include <os2.h>
#endif

using namespace com::sun::star::mozilla;
namespace connectivity
{
    namespace mozab
    {
        class ProfileStruct;
    }
}
typedef ::std::map < ::rtl::OUString, ::connectivity::mozab::ProfileStruct* > ProfileList;
namespace connectivity
{
    namespace mozab
    {
        class ProfileStruct
        {
        public:
            ProfileStruct(MozillaProductType aProduct,::rtl::OUString aProfileName,
#ifdef MINIMAL_PROFILEDISCOVER
                          const ::rtl::OUString &aProfilePath
#else
                          nsILocalFile * aProfilePath
#endif
                            );
            MozillaProductType getProductType() { return product;}
            ::rtl::OUString getProfileName(){ return profileName;}
            ::rtl::OUString getProfilePath() ;
#ifndef MINIMAL_PROFILEDISCOVER
            nsILocalFile    *getProfileLocal(){ return profilePath;}
#endif
        protected:
            MozillaProductType product;
            ::rtl::OUString profileName;
#ifdef MINIMAL_PROFILEDISCOVER
            ::rtl::OUString profilePath;
#else
            nsCOMPtr<nsILocalFile> profilePath;
#endif
        };

        class ProductStruct
        {
        public:
            void setCurrentProfile(::rtl::OUString aProfileName){mCurrentProfileName = aProfileName;}

            ::rtl::OUString mCurrentProfileName;

            ProfileList mProfileList;
        };

        //Used to query profiles information
        class ProfileAccess
        {
        public:

            virtual ~ProfileAccess();
            ProfileAccess();
            ::rtl::OUString getProfilePath( ::com::sun::star::mozilla::MozillaProductType product, const ::rtl::OUString& profileName ) throw (::com::sun::star::uno::RuntimeException);
            ::sal_Int32 getProfileCount( ::com::sun::star::mozilla::MozillaProductType product ) throw (::com::sun::star::uno::RuntimeException);
            ::sal_Int32 getProfileList( ::com::sun::star::mozilla::MozillaProductType product, ::com::sun::star::uno::Sequence< ::rtl::OUString >& list ) throw (::com::sun::star::uno::RuntimeException);
            ::rtl::OUString getDefaultProfile( ::com::sun::star::mozilla::MozillaProductType product ) throw (::com::sun::star::uno::RuntimeException);
            ::sal_Bool SAL_CALL isProfileLocked( ::com::sun::star::mozilla::MozillaProductType product, const ::rtl::OUString& profileName ) throw (::com::sun::star::uno::RuntimeException);
            ::sal_Bool SAL_CALL getProfileExists( ::com::sun::star::mozilla::MozillaProductType product, const ::rtl::OUString& profileName ) throw (::com::sun::star::uno::RuntimeException);
        protected:
            ProductStruct m_ProductProfileList[4];
            sal_Int32 LoadProductsInfo();
#ifndef MINIMAL_PROFILEDISCOVER
            nsresult  LoadMozillaProfiles();
#endif
            sal_Int32 LoadXPToolkitProfiles(MozillaProductType product);
#ifndef MINIMAL_PROFILEDISCOVER
            //used by isProfileLocked
            nsresult isExistFileOrSymlink(nsILocalFile* aFile,PRBool *bExist);
            nsresult isLockExist(nsILocalFile* aFile);
#endif
        };

    }
}

#endif // __MNSProfileDiscover_h___

<|endoftext|>


<commit_before><commit_msg>fix for viewer embedding<commit_after><|endoftext|>


<commit_before><commit_msg>When searching for child windows when dragging a float only take our own<commit_after><|endoftext|>


<commit_before>/*
    Copyright 2002-2013 CEA LIST

    This file is part of LIMA.

    LIMA is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    LIMA 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with LIMA.  If not, see <http://www.gnu.org/licenses/>
*/
/************************************************************************
 *
 * @file       DynamicLibrariesManager.cpp
 * @author      (romaric.besancon@cea.fr)
 * @date       Wed Feb  6 2008
 * copyright   Copyright (C) 2008-2012 by CEA LIST
 *
 ***********************************************************************/

#include "DynamicLibrariesManager.h"

#include <iostream>

using namespace std;

namespace Lima {
namespace Common {

DynamicLibrariesManager::DynamicLibrariesManager()
{
}

DynamicLibrariesManager::~DynamicLibrariesManager()
{
  for (std::map<std::string,QLibrary*>::iterator
         it=m_handles.begin(),it_end=m_handles.end(); it!=it_end; it++)
  {
    delete (*it).second;
  }
}

bool DynamicLibrariesManager::
isLoaded(const std::string& libName)
{
  std::map<std::string,QLibrary*>::const_iterator
    it=m_handles.find(libName);
  return (it!=m_handles.end());
}

bool DynamicLibrariesManager::
loadLibrary(const std::string& libName)
{
  std::map<std::string,QLibrary*>::const_iterator
    it=m_handles.find(libName);
  if (it!=m_handles.end()) {
#ifdef DEBUG_CD
    std::cerr << "DEBUG_CD: trying to reload dynamic library " << libName.c_str() << std::endl;
#endif
  }

  QLibrary* libhandle = 0;
  // try supplementary search path
  for (std::vector<std::string>::const_iterator it = m_supplementarySearchPath.begin(); it != m_supplementarySearchPath.end(); it++)
  {
#ifdef DEBUG_FACTORIES
    std::cerr << "Trying supplementary " << ((*it)+"/"+libName).c_str() << std::endl;
#endif
    libhandle = new QLibrary( ((*it)+"/"+libName).c_str() );
    libhandle->setLoadHints(QLibrary::ResolveAllSymbolsHint | QLibrary::ExportExternalSymbolsHint);
    if (libhandle->load())
    {
      m_handles.insert(std::make_pair(libName,libhandle));
      return true;
    }
    else
    {
//      if ( QLibrary::isLibrary(((*it)+"/"+libName).c_str()) )
        std::cerr << "Failed to open lib " << libhandle->errorString().toUtf8().data() << std::endl;
      delete libhandle;
      libhandle = 0;
    }
  }
  // now try system default search path
  if (libhandle == 0)
  {
#ifdef DEBUG_FACTORIES
    std::cerr << "Trying " << libName.c_str() << std::endl;
#endif
    libhandle = new QLibrary( libName.c_str() );
    libhandle->setLoadHints(QLibrary::ResolveAllSymbolsHint | QLibrary::ExportExternalSymbolsHint);
    if (libhandle->load())
    {
      m_handles.insert(std::make_pair(libName,libhandle));
      return true;
    }
    else
    {
      std::cerr << "Failed to open lib " << libhandle->errorString().toUtf8().data() << std::endl;
      delete libhandle;
      libhandle = 0;
      return false;
    }
  }
  else {
#ifdef DEBUG_CD
    std::cerr << "the library " << libName.c_str() << " was loaded" << std::endl;
#endif
    m_handles[libName]=libhandle;
    return true;
  }
}

void DynamicLibrariesManager::
addSearchPath(const std::string& searchPath)
{
#ifdef DEBUG_CD
  std::cerr << "adding search path '"<<searchPath.c_str()<<"'" << std::endl;
#endif
  m_supplementarySearchPath.push_back(searchPath);
}

} // end namespace
} // end namespace
<commit_msg>Comment out noisy debug message not necessary for daily use<commit_after>/*
    Copyright 2002-2013 CEA LIST

    This file is part of LIMA.

    LIMA is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    LIMA 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with LIMA.  If not, see <http://www.gnu.org/licenses/>
*/
/************************************************************************
 *
 * @file       DynamicLibrariesManager.cpp
 * @author      (romaric.besancon@cea.fr)
 * @date       Wed Feb  6 2008
 * copyright   Copyright (C) 2008-2012 by CEA LIST
 *
 ***********************************************************************/

#include "DynamicLibrariesManager.h"

#include <iostream>

using namespace std;

namespace Lima {
namespace Common {

DynamicLibrariesManager::DynamicLibrariesManager()
{
}

DynamicLibrariesManager::~DynamicLibrariesManager()
{
  for (std::map<std::string,QLibrary*>::iterator
         it=m_handles.begin(),it_end=m_handles.end(); it!=it_end; it++)
  {
    delete (*it).second;
  }
}

bool DynamicLibrariesManager::
isLoaded(const std::string& libName)
{
  std::map<std::string,QLibrary*>::const_iterator
    it=m_handles.find(libName);
  return (it!=m_handles.end());
}

bool DynamicLibrariesManager::
loadLibrary(const std::string& libName)
{
  std::map<std::string,QLibrary*>::const_iterator
    it=m_handles.find(libName);
  if (it!=m_handles.end()) {
// #ifdef DEBUG_CD
//     std::cerr << "DEBUG_CD: trying to reload dynamic library " << libName.c_str() << std::endl;
// #endif
  }

  QLibrary* libhandle = 0;
  // try supplementary search path
  for (std::vector<std::string>::const_iterator it = m_supplementarySearchPath.begin(); it != m_supplementarySearchPath.end(); it++)
  {
#ifdef DEBUG_FACTORIES
    std::cerr << "Trying supplementary " << ((*it)+"/"+libName).c_str() << std::endl;
#endif
    libhandle = new QLibrary( ((*it)+"/"+libName).c_str() );
    libhandle->setLoadHints(QLibrary::ResolveAllSymbolsHint | QLibrary::ExportExternalSymbolsHint);
    if (libhandle->load())
    {
      m_handles.insert(std::make_pair(libName,libhandle));
      return true;
    }
    else
    {
//      if ( QLibrary::isLibrary(((*it)+"/"+libName).c_str()) )
        std::cerr << "Failed to open lib " << libhandle->errorString().toUtf8().data() << std::endl;
      delete libhandle;
      libhandle = 0;
    }
  }
  // now try system default search path
  if (libhandle == 0)
  {
#ifdef DEBUG_FACTORIES
    std::cerr << "Trying " << libName.c_str() << std::endl;
#endif
    libhandle = new QLibrary( libName.c_str() );
    libhandle->setLoadHints(QLibrary::ResolveAllSymbolsHint | QLibrary::ExportExternalSymbolsHint);
    if (libhandle->load())
    {
      m_handles.insert(std::make_pair(libName,libhandle));
      return true;
    }
    else
    {
      std::cerr << "Failed to open lib " << libhandle->errorString().toUtf8().data() << std::endl;
      delete libhandle;
      libhandle = 0;
      return false;
    }
  }
  else {
#ifdef DEBUG_CD
    std::cerr << "the library " << libName.c_str() << " was loaded" << std::endl;
#endif
    m_handles[libName]=libhandle;
    return true;
  }
}

void DynamicLibrariesManager::
addSearchPath(const std::string& searchPath)
{
#ifdef DEBUG_CD
  std::cerr << "adding search path '"<<searchPath.c_str()<<"'" << std::endl;
#endif
  m_supplementarySearchPath.push_back(searchPath);
}

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


<commit_before><commit_msg>add LD_LIBRARY_PATH support when loading apps on Linux<commit_after><|endoftext|>


<commit_before>#include <nan.h>
#include <chrono>
#include <thread>
#include <iostream>
#include <fstream>
#include "ghostpdl/base/gserrors.h"
#include "ghostpdl/psi/iapi.h"

using namespace std;
using namespace Nan;
using namespace v8;

extern "C" {
  int gsapi_new_instance (void **pinstance, void *caller_handle);
  void gsapi_delete_instance (void *instance);
  int gsapi_set_arg_encoding (void *instance, int encoding);
  int gsapi_init_with_args (void *instance, int argc, char **argv);
  int gsapi_exit (void *instance);
};

class Ghostscript : public AsyncWorker {
  public: Ghostscript(Callback * callback) : AsyncWorker(callback) {}

  // Executes in worker thread
  void Execute() {
    std::this_thread::sleep_for(chrono::milliseconds(1000));
    gsargv[0] = (char *) "gs";
    gsargv[1] = (char *) "-q";
    gsargv[2] = (char *) "-dNOPAUSE";
    gsargv[3] = (char *) "-dBATCH";
    gsargv[4] = (char *) "-sDEVICE=tiff24nc";
    gsargv[5] = (char *) "-r300";
    gsargv[6] = (char *) "-sOutputFile=test-%03d.tiff";
    gsargv[7] = (char *) "test.pdf";
    gsargc = 8;

    gscode = gsapi_new_instance(&minst, NULL);
    if (gscode < 0) return;
    gscode = gsapi_set_arg_encoding(minst, GS_ARG_ENCODING_UTF8);

    if (gscode == 0)
        gscode = gsapi_init_with_args(minst, gsargc, gsargv);
    gscode1 = gsapi_exit(minst);

    if ((gscode == 0) || (gscode == gs_error_Quit))
        gscode = gscode1;

    gsapi_delete_instance(minst);

  }
  // Executes in event loop
  void HandleOKCallback () {
    if ((gscode == 0) || (gscode == gs_error_Quit)) {
      Local<String> allOK = Nan::New<String>("All is ok !").ToLocalChecked();
      Local<Value> argv[] = { Nan::Null(), allOK };
      callback->Call(2, argv);
    } else {
      Local<String> error = Nan::New<String>("Something is wrong, dude !").ToLocalChecked();
      Local<Value> argv[] = { error };
      callback->Call(1, argv);
    }
  }

  private:
    void *minst;
    int gscode = 0;
    int gscode1;
    char *gsargv[8];
    int gsargc;
};

NAN_METHOD(exec) {
  Callback *callback = new Callback(info[0].As<Function>());
  AsyncQueueWorker(new Ghostscript(callback));
}

NAN_MODULE_INIT(Init) {
  Nan::Set(target, New<String>("exec").ToLocalChecked(),
    GetFunction(New<FunctionTemplate>(exec)).ToLocalChecked());
}

NODE_MODULE(addon, Init)
<commit_msg>cleaning some unecessary code<commit_after>#include <nan.h>
#include "ghostpdl/base/gserrors.h"
#include "ghostpdl/psi/iapi.h"

using namespace std;
using namespace Nan;
using namespace v8;

extern "C" {
  int gsapi_new_instance (void **pinstance, void *caller_handle);
  void gsapi_delete_instance (void *instance);
  int gsapi_set_arg_encoding (void *instance, int encoding);
  int gsapi_init_with_args (void *instance, int argc, char **argv);
  int gsapi_exit (void *instance);
};

class Ghostscript : public AsyncWorker {
  public: Ghostscript(Callback * callback) : AsyncWorker(callback) {}

  // Executes in worker thread
  void Execute() {
    gsargv[0] = (char *) "gs";
    gsargv[1] = (char *) "-q";
    gsargv[2] = (char *) "-dNOPAUSE";
    gsargv[3] = (char *) "-dBATCH";
    gsargv[4] = (char *) "-sDEVICE=tiff24nc";
    gsargv[5] = (char *) "-r300";
    gsargv[6] = (char *) "-sOutputFile=test-%03d.tiff";
    gsargv[7] = (char *) "test.pdf";
    gsargc = 8;

    gscode = gsapi_new_instance(&minst, NULL);
    if (gscode < 0) return;
    gscode = gsapi_set_arg_encoding(minst, GS_ARG_ENCODING_UTF8);

    if (gscode == 0)
        gscode = gsapi_init_with_args(minst, gsargc, gsargv);
    gscode1 = gsapi_exit(minst);

    if ((gscode == 0) || (gscode == gs_error_Quit))
        gscode = gscode1;

    gsapi_delete_instance(minst);

  }
  // Executes in event loop
  void HandleOKCallback () {
    if ((gscode == 0) || (gscode == gs_error_Quit)) {
      Local<String> allOK = Nan::New<String>("All is ok !").ToLocalChecked();
      Local<Value> argv[] = { Nan::Null(), allOK };
      callback->Call(2, argv);
    } else {
      Local<String> error = Nan::New<String>("Something is wrong, dude !").ToLocalChecked();
      Local<Value> argv[] = { error };
      callback->Call(1, argv);
    }
  }

  private:
    void *minst;
    int gscode = 0;
    int gscode1;
    char *gsargv[8];
    int gsargc;
};

NAN_METHOD(exec) {
  Callback *callback = new Callback(info[0].As<Function>());
  AsyncQueueWorker(new Ghostscript(callback));
}

NAN_MODULE_INIT(Init) {
  Nan::Set(target, New<String>("exec").ToLocalChecked(),
    GetFunction(New<FunctionTemplate>(exec)).ToLocalChecked());
}

NODE_MODULE(addon, Init)
<|endoftext|>