<commit_before>/*************************************************************************
 *
 *  $RCSfile: elements.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: kz $ $Date: 2004-12-16 11:47:13 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/
#if !defined INCLUDED_JVMFWK_ELEMENTS_HXX
#define INCLUDED_JVMFWK_ELEMENTS_HXX

#include <vector>
#include "jvmfwk/framework.h"
#include "rtl/ustring.hxx"
#include "rtl/byteseq.hxx"
#include "libxml/parser.h"

#define NS_JAVA_FRAMEWORK "http://openoffice.org/2004/java/framework/1.0"
#define NS_SCHEMA_INSTANCE "http://www.w3.org/2001/XMLSchema-instance"

namespace jfw
{

xmlNode* findChildNode(const xmlNode * pParent, const xmlChar* pName);

/** gets the value of the updated element from the javavendors.xml.
 */
rtl::OString getElementUpdated();

/** creates the javasettings.xml in the users home directory.

    If javasettings.xml does not exist then it creates the file
    and inserts the root element with its namespaces.
    The content should look like this:

    <?xml version="1.0" encoding="UTF-8"?>
    <!--This is a generated file. Do not alter this file!-->
    <java xmlns:="http://openoffice.org/2004/java/framework/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    </java>

 */
void createUserSettingsDocument();

/** create the child elements within the root structure for each platform.

    @param bNeedsSave
    [out]If true then the respective structure of elements was added and the
    document needs to be saved.
 */
void createSettingsStructure(
    xmlDoc * document, bool * bNeedsSave);

/** copies shared settings to user settings.

    This must only occur the first time when the javasettings.xml is
    prepared for the user. The shared settings shall be provided as bootstrap
    parameters.

    @param userParent
    The node under which the values are to be copied.

 */
void copyShareSettings(xmlDoc * userDoc, xmlNode* userParent);

/** creates the structure of the documend.

    When this function is called the first time for a user then it creates the
    javasettings.xml in th ~/<office>/user/config/ unless it already exists
    (see createUserSettingsDocument). Then
    it creates a section for the current platform unless it already exist and
    creates all children elements. If the respective platform section did not exist
    then after creating the children, the values from the share/config/javasettings.xml
    are copied.

    @return
    JFW_E_CONFIG_READWRITE
 */
void prepareSettingsDocument();

class CXmlCharPtr;
class CNodeJavaInfo
{
public:
    CNodeJavaInfo();
    ~CNodeJavaInfo();
    /**
       sUpdated is the value from the <updated> element from the
       javavendors.xml.
     */
    CNodeJavaInfo(const JavaInfo * pInfo);

    /** if true, then javaInfo is empty. When writeToNode is called
        then all child elements are deleted.
     */
    bool m_bEmptyNode;
    /** Contains the value of the <updated> element of
        the javavendors.xml after loadFromNode was called.
        It is not used, when the javaInfo node is written.
        see writeToNode
     */
    rtl::OString sAttrVendorUpdate;
    /** contains the nil value of the /java/javaInfo@xsi:nil attribute.
        Default is true;
     */
    bool bNil;
    /** contains the value of the /java/javaInfo@autoSelect attribute.
        Default is true. If it is false then the user has modified the JRE
        selection by actively choosing a JRE from the options dialog. That is,
        the function jfw_setSelectedJRE was called. Contrary, the function
        jfw_findAndSelectJRE sets the attribute to true.
     */
    bool bAutoSelect;
    rtl::OUString sVendor;
    rtl::OUString sLocation;
    rtl::OUString sVersion;
    sal_uInt64 nFeatures;
    sal_uInt64 nRequirements;
    rtl::ByteSequence arVendorData;

    /** reads the node /java/javaInfo.
        If javaInfo@xsi:nil = true then member bNil is set to true
        an no further elements are read.
     */
    void loadFromNode(xmlDoc * pDoc,xmlNode * pJavaInfo);
    /** Only writes user settings. The attribut nil always gets the value
        false. The function gets the value javaSettings/updated from the
        javavendors.xml and writes it to javaInfo@vendorUpdate in javasettings.xml
     */
    void writeToNode(xmlDoc * pDoc, xmlNode * pJavaInfo) const;

    /** returns NULL if javaInfo is nil in both, user and share, settings.
     */
    JavaInfo * makeJavaInfo() const;
};

/** this class represents the javasettings.xml file
 */
class CNodeJava
{
    /** Share settings are a special case. Per default
        there are only user settings. Currently there need not be
        a share settings file. In that case the function returns
        without throwing an exception.
     */
    void loadShareSettings();
    /** This function is called after loadShareSettings. Elements which have been
        modified by the user, that is, the attribute xsi:nil = false, overwrite the
        values which have been retrieved with loadShareSettings.
    */
    void loadUserSettings();

    /** User configurable option.  /java/enabled
        The value is valid after loadFromSettings has been called
        successfully.
        The value is that of the user setting. If it is nil
        (/java/enabled[@xsi:nil = true]) then it represents the share setting.
        If there are no share settings or the node is also nil then the default
        is true.
    */
    sal_Bool m_bEnabled;
    /** Determines if m_bEnabled has been modified */
    bool m_bEnabledModified;
    /** User configurable option. /java/userClassPath
        The value is valid after loadFromSettings has been called successfully.
        The value is that of the user setting. If it is nil
        (/java/userClassPath[@xsi:nil = true]) then it represents the share setting.
        If there are no share settings or the node is also nil then the default
        is an empty string.
    */
    rtl::OUString m_sUserClassPath;
    /** Determines if m_sUserClassPath has been modified */
    bool m_bUserClassPathModified;
    /** User configurable option.  /java/javaInfo
        The value is valid after loadFromSettings has been called successfully.
        The value is that of the user setting. If it is nil
        (/java/javaInfo[@xsi:nil = true]) then it represents the share setting.
        If there are no share settings then the structure is regarded as empty.
     */
    CNodeJavaInfo m_aInfo;
    /** Determines if m_aInfo has been modified */
    bool m_bJavaInfoModified;

    /** User configurable option. /java/vmParameters
        The value is valid after loadFromSettings has been called successfully.
        The value is that of the user setting. If it is nil
        (/java/vmParameters[@xsi:nil = true]) then it represents the share setting.
        If there are no share settings then array is empty.
    */
    std::vector<rtl::OString>  m_arVmParameters;
    bool m_bVmParametersModified;

    /** User configurable option. /java/jreLocations
        The value is valid after loadFromSettings has been called successfully.
        The value is that of the user setting. If it is nil
        (/java/jreLocations[@xsi:nil = true]) then it represents the share setting.
        If there are no share settings then array is empty.
    */
    std::vector<rtl::OString>  m_arJRELocations;
    bool m_bJRELocationsModified;

public:
    CNodeJava();
    /** sets m_bEnabled. It also sets a flag, that the value has been
        modified. This will cause that /java/enabled[@xsi:nil] will be
        set to false. The nil value and the value of enabled are only
        written when write Settings is called.
     */
    void setEnabled(sal_Bool bEnabled);
    /** returns the value of the element /java/enabled
     */
    sal_Bool getEnabled() const;
    /** sets m_sUserClassPath. Analog to setEnabled.
     */
    void setUserClassPath(const rtl::OUString & sClassPath);
    /** returns the value of the element /java/userClassPath.
     */
    rtl::OUString const & getUserClassPath() const;
    /** sets m_aInfo. Analog to setEnabled.
        @param bAutoSelect
        true- called by jfw_setSelectedJRE
        false called by jfw_findAndSelectJRE
     */
    void setJavaInfo(const JavaInfo * pInfo, bool bAutoSelect);
    /** returns a JavaInfo structure representing the node
        /java/javaInfo. Every time a new JavaInfo structure is created
        which needs to be freed by the caller.
        If both, user and share settings are nil, then NULL is returned.
    */
    JavaInfo * createJavaInfo() const;
    /** returns the value of the attribute /java/javaInfo[@vendorUpdate].
     */
    rtl::OString const & getJavaInfoAttrVendorUpdate() const;

    /** returns the javaInfo@autoSelect attribute.
        Before calling this function loadFromSettings must be called.
        It uses the javaInfo@autoSelect attribute  to determine
        the return value;
     */
    bool getJavaInfoAttrAutoSelect() const;

    /** sets the /java/vmParameters/param elements.
        The values are kept in a vector m_arVmParameters. When this method is
        called then the vector is cleared and the new values are inserted.
        The xsi:nil attribute of vmParameters will be set to true;
     */
    void setVmParameters(rtl_uString  * * arParameters, sal_Int32 size);
    /** returns the parameters from the element /java/vmParameters/param.
     */
    const std::vector<rtl::OString> & getVmParameters() const;

    /** returns an array.
        Caller must free the strings and the array.
     */
    void getVmParametersArray(rtl_uString *** parParameters, sal_Int32 * size) const;

    /** sets the /java/jreLocations/location elements.
        The values are kept in a vector m_arJRELocations. When this method is
        called then the vector is cleared and the new values are inserted.
        The xsi:nil attribute of vmParameters will be set to true;
     */
    void setJRELocations(rtl_uString  * * arParameters, sal_Int32 size);

    void addJRELocation(rtl_uString * sLocation);
    /** returns the parameters from the element /java/jreLocations/location.
     */
    const std::vector<rtl::OString> & getJRELocations() const;

    /** returns an array.
        Caller must free the strings and the array.
     */
    void getJRELocations(rtl_uString *** parLocations, sal_Int32 * size) const;

    /** reads user and share settings. user data supersede
        share data. These elements can be changed by the user:
        <enabled>, <userClasspath>, <javaInfo>, <vmParameters>
        If the user has not changed them then the nil attribute is
        set to true;
     */
    void loadFromSettings();
    /** writes the data to user settings.
     */
    void writeSettings() const;

};

class VersionInfo
{
    std::vector<rtl::OUString> vecExcludeVersions;
    rtl_uString ** arVersions;

public:
    VersionInfo();
    ~VersionInfo();

    void addExcludeVersion(const rtl::OUString& sVersion);

    rtl::OUString sMinVersion;
    rtl::OUString sMaxVersion;

    /** The caller DOES NOT get ownership of the strings. That is he
        does not need to release the strings.
        The array exists as long as this object exists.
    */

    rtl_uString** getExcludeVersions();
    sal_Int32 getExcludeVersionSize();
};

struct PluginLibrary
{
    PluginLibrary()
    {
    }
    PluginLibrary(rtl::OUString vendor, rtl::OUString path) :
        sVendor(vendor), sPath(path)
    {
    }
    /** contains the vendor string which is later userd in the xml API
     */
    rtl::OUString sVendor;
    /** File URL the plug-in library
     */
    rtl::OUString sPath;
};

} //end namespace
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.8.34); FILE MERGED 2005/09/05 17:12:27 rt 1.8.34.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: elements.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 19:34:08 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#if !defined INCLUDED_JVMFWK_ELEMENTS_HXX
#define INCLUDED_JVMFWK_ELEMENTS_HXX

#include <vector>
#include "jvmfwk/framework.h"
#include "rtl/ustring.hxx"
#include "rtl/byteseq.hxx"
#include "libxml/parser.h"

#define NS_JAVA_FRAMEWORK "http://openoffice.org/2004/java/framework/1.0"
#define NS_SCHEMA_INSTANCE "http://www.w3.org/2001/XMLSchema-instance"

namespace jfw
{

xmlNode* findChildNode(const xmlNode * pParent, const xmlChar* pName);

/** gets the value of the updated element from the javavendors.xml.
 */
rtl::OString getElementUpdated();

/** creates the javasettings.xml in the users home directory.

    If javasettings.xml does not exist then it creates the file
    and inserts the root element with its namespaces.
    The content should look like this:

    <?xml version="1.0" encoding="UTF-8"?>
    <!--This is a generated file. Do not alter this file!-->
    <java xmlns:="http://openoffice.org/2004/java/framework/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    </java>

 */
void createUserSettingsDocument();

/** create the child elements within the root structure for each platform.

    @param bNeedsSave
    [out]If true then the respective structure of elements was added and the
    document needs to be saved.
 */
void createSettingsStructure(
    xmlDoc * document, bool * bNeedsSave);

/** copies shared settings to user settings.

    This must only occur the first time when the javasettings.xml is
    prepared for the user. The shared settings shall be provided as bootstrap
    parameters.

    @param userParent
    The node under which the values are to be copied.

 */
void copyShareSettings(xmlDoc * userDoc, xmlNode* userParent);

/** creates the structure of the documend.

    When this function is called the first time for a user then it creates the
    javasettings.xml in th ~/<office>/user/config/ unless it already exists
    (see createUserSettingsDocument). Then
    it creates a section for the current platform unless it already exist and
    creates all children elements. If the respective platform section did not exist
    then after creating the children, the values from the share/config/javasettings.xml
    are copied.

    @return
    JFW_E_CONFIG_READWRITE
 */
void prepareSettingsDocument();

class CXmlCharPtr;
class CNodeJavaInfo
{
public:
    CNodeJavaInfo();
    ~CNodeJavaInfo();
    /**
       sUpdated is the value from the <updated> element from the
       javavendors.xml.
     */
    CNodeJavaInfo(const JavaInfo * pInfo);

    /** if true, then javaInfo is empty. When writeToNode is called
        then all child elements are deleted.
     */
    bool m_bEmptyNode;
    /** Contains the value of the <updated> element of
        the javavendors.xml after loadFromNode was called.
        It is not used, when the javaInfo node is written.
        see writeToNode
     */
    rtl::OString sAttrVendorUpdate;
    /** contains the nil value of the /java/javaInfo@xsi:nil attribute.
        Default is true;
     */
    bool bNil;
    /** contains the value of the /java/javaInfo@autoSelect attribute.
        Default is true. If it is false then the user has modified the JRE
        selection by actively choosing a JRE from the options dialog. That is,
        the function jfw_setSelectedJRE was called. Contrary, the function
        jfw_findAndSelectJRE sets the attribute to true.
     */
    bool bAutoSelect;
    rtl::OUString sVendor;
    rtl::OUString sLocation;
    rtl::OUString sVersion;
    sal_uInt64 nFeatures;
    sal_uInt64 nRequirements;
    rtl::ByteSequence arVendorData;

    /** reads the node /java/javaInfo.
        If javaInfo@xsi:nil = true then member bNil is set to true
        an no further elements are read.
     */
    void loadFromNode(xmlDoc * pDoc,xmlNode * pJavaInfo);
    /** Only writes user settings. The attribut nil always gets the value
        false. The function gets the value javaSettings/updated from the
        javavendors.xml and writes it to javaInfo@vendorUpdate in javasettings.xml
     */
    void writeToNode(xmlDoc * pDoc, xmlNode * pJavaInfo) const;

    /** returns NULL if javaInfo is nil in both, user and share, settings.
     */
    JavaInfo * makeJavaInfo() const;
};

/** this class represents the javasettings.xml file
 */
class CNodeJava
{
    /** Share settings are a special case. Per default
        there are only user settings. Currently there need not be
        a share settings file. In that case the function returns
        without throwing an exception.
     */
    void loadShareSettings();
    /** This function is called after loadShareSettings. Elements which have been
        modified by the user, that is, the attribute xsi:nil = false, overwrite the
        values which have been retrieved with loadShareSettings.
    */
    void loadUserSettings();

    /** User configurable option.  /java/enabled
        The value is valid after loadFromSettings has been called
        successfully.
        The value is that of the user setting. If it is nil
        (/java/enabled[@xsi:nil = true]) then it represents the share setting.
        If there are no share settings or the node is also nil then the default
        is true.
    */
    sal_Bool m_bEnabled;
    /** Determines if m_bEnabled has been modified */
    bool m_bEnabledModified;
    /** User configurable option. /java/userClassPath
        The value is valid after loadFromSettings has been called successfully.
        The value is that of the user setting. If it is nil
        (/java/userClassPath[@xsi:nil = true]) then it represents the share setting.
        If there are no share settings or the node is also nil then the default
        is an empty string.
    */
    rtl::OUString m_sUserClassPath;
    /** Determines if m_sUserClassPath has been modified */
    bool m_bUserClassPathModified;
    /** User configurable option.  /java/javaInfo
        The value is valid after loadFromSettings has been called successfully.
        The value is that of the user setting. If it is nil
        (/java/javaInfo[@xsi:nil = true]) then it represents the share setting.
        If there are no share settings then the structure is regarded as empty.
     */
    CNodeJavaInfo m_aInfo;
    /** Determines if m_aInfo has been modified */
    bool m_bJavaInfoModified;

    /** User configurable option. /java/vmParameters
        The value is valid after loadFromSettings has been called successfully.
        The value is that of the user setting. If it is nil
        (/java/vmParameters[@xsi:nil = true]) then it represents the share setting.
        If there are no share settings then array is empty.
    */
    std::vector<rtl::OString>  m_arVmParameters;
    bool m_bVmParametersModified;

    /** User configurable option. /java/jreLocations
        The value is valid after loadFromSettings has been called successfully.
        The value is that of the user setting. If it is nil
        (/java/jreLocations[@xsi:nil = true]) then it represents the share setting.
        If there are no share settings then array is empty.
    */
    std::vector<rtl::OString>  m_arJRELocations;
    bool m_bJRELocationsModified;

public:
    CNodeJava();
    /** sets m_bEnabled. It also sets a flag, that the value has been
        modified. This will cause that /java/enabled[@xsi:nil] will be
        set to false. The nil value and the value of enabled are only
        written when write Settings is called.
     */
    void setEnabled(sal_Bool bEnabled);
    /** returns the value of the element /java/enabled
     */
    sal_Bool getEnabled() const;
    /** sets m_sUserClassPath. Analog to setEnabled.
     */
    void setUserClassPath(const rtl::OUString & sClassPath);
    /** returns the value of the element /java/userClassPath.
     */
    rtl::OUString const & getUserClassPath() const;
    /** sets m_aInfo. Analog to setEnabled.
        @param bAutoSelect
        true- called by jfw_setSelectedJRE
        false called by jfw_findAndSelectJRE
     */
    void setJavaInfo(const JavaInfo * pInfo, bool bAutoSelect);
    /** returns a JavaInfo structure representing the node
        /java/javaInfo. Every time a new JavaInfo structure is created
        which needs to be freed by the caller.
        If both, user and share settings are nil, then NULL is returned.
    */
    JavaInfo * createJavaInfo() const;
    /** returns the value of the attribute /java/javaInfo[@vendorUpdate].
     */
    rtl::OString const & getJavaInfoAttrVendorUpdate() const;

    /** returns the javaInfo@autoSelect attribute.
        Before calling this function loadFromSettings must be called.
        It uses the javaInfo@autoSelect attribute  to determine
        the return value;
     */
    bool getJavaInfoAttrAutoSelect() const;

    /** sets the /java/vmParameters/param elements.
        The values are kept in a vector m_arVmParameters. When this method is
        called then the vector is cleared and the new values are inserted.
        The xsi:nil attribute of vmParameters will be set to true;
     */
    void setVmParameters(rtl_uString  * * arParameters, sal_Int32 size);
    /** returns the parameters from the element /java/vmParameters/param.
     */
    const std::vector<rtl::OString> & getVmParameters() const;

    /** returns an array.
        Caller must free the strings and the array.
     */
    void getVmParametersArray(rtl_uString *** parParameters, sal_Int32 * size) const;

    /** sets the /java/jreLocations/location elements.
        The values are kept in a vector m_arJRELocations. When this method is
        called then the vector is cleared and the new values are inserted.
        The xsi:nil attribute of vmParameters will be set to true;
     */
    void setJRELocations(rtl_uString  * * arParameters, sal_Int32 size);

    void addJRELocation(rtl_uString * sLocation);
    /** returns the parameters from the element /java/jreLocations/location.
     */
    const std::vector<rtl::OString> & getJRELocations() const;

    /** returns an array.
        Caller must free the strings and the array.
     */
    void getJRELocations(rtl_uString *** parLocations, sal_Int32 * size) const;

    /** reads user and share settings. user data supersede
        share data. These elements can be changed by the user:
        <enabled>, <userClasspath>, <javaInfo>, <vmParameters>
        If the user has not changed them then the nil attribute is
        set to true;
     */
    void loadFromSettings();
    /** writes the data to user settings.
     */
    void writeSettings() const;

};

class VersionInfo
{
    std::vector<rtl::OUString> vecExcludeVersions;
    rtl_uString ** arVersions;

public:
    VersionInfo();
    ~VersionInfo();

    void addExcludeVersion(const rtl::OUString& sVersion);

    rtl::OUString sMinVersion;
    rtl::OUString sMaxVersion;

    /** The caller DOES NOT get ownership of the strings. That is he
        does not need to release the strings.
        The array exists as long as this object exists.
    */

    rtl_uString** getExcludeVersions();
    sal_Int32 getExcludeVersionSize();
};

struct PluginLibrary
{
    PluginLibrary()
    {
    }
    PluginLibrary(rtl::OUString vendor, rtl::OUString path) :
        sVendor(vendor), sPath(path)
    {
    }
    /** contains the vendor string which is later userd in the xml API
     */
    rtl::OUString sVendor;
    /** File URL the plug-in library
     */
    rtl::OUString sPath;
};

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


<commit_before>/*
 * Copyright (c) 2013 Nicholas Corgan (n.corgan@gmail.com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */
#include "team_analysis_common.hpp"

#include <boost/assign.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <fstream>
#include <iostream>
#include <map>
#include <pkmnsim/base_pkmn.hpp>
#include <pkmnsim/pkmn_types.hpp>
#include <stdexcept>
#include <string>
#include <vector>

//TODO: take move types into account
//TODO: take counter-effectiveness into account

namespace po = boost::program_options;
using namespace pkmnsim;
using namespace std;

void print_help(po::variables_map vm, po::options_description desc)
{
    cout << endl << "Team Analysis - " << desc << endl;

    cout << "Point the --team_file option at a file with" << endl
         << "one Pokémon name on each line. Using Lance's" << endl
         << "first team from Fire Red/Leaf Green as an" << endl
         << "example:" << endl << endl

         << "Gyarados" << endl
         << "Dragonair" << endl
         << "Dragonair" << endl
         << "Aerodactyl" << endl
         << "Dragonite" << endl << endl;
}

string get_pkmn_effectiveness_string(string pkmn_name, map<string, double> &effectiveness_map)
{
    string output_string = str(boost::format(" * %s") % pkmn_name);
    string good_types_str = "   * Use:";
    string bad_types_str = "   * Don't use:";

    //Iterate over map and add to good/bad_types_str as appropriate
    for(sd_iter i = effectiveness_map.begin(); i != effectiveness_map.end(); ++i)
    {
        if(i->second > 1.0) good_types_str = str(boost::format("%s %s,")
                                                 % good_types_str % i->first);
        else if(i->second < 1.0) bad_types_str = str(boost::format("%s %s,")
                                                     % bad_types_str % i->first);
    }

    //Cut off final comma from good/bad_types_str
    good_types_str = good_types_str.substr(0, good_types_str.size()-1);
    bad_types_str = bad_types_str.substr(0, bad_types_str.size()-1);

    //Only add good/bad_types_str onto output string if applicable
    if(good_types_str != " * Use") output_string = str(boost::format("%s\n%s") %
                                                       output_string % good_types_str);
    if(bad_types_str != " * Don't use") output_string = str(boost::format("%s\n%s") %
                                                       output_string % bad_types_str);

    return output_string;
}

string get_trends_string(map<string, int> &super_effective_map, map<string, int> &not_very_effective_map)
{
    string output_string = " * Use:";
    for(si_iter i = super_effective_map.begin(); i != super_effective_map.end(); ++i)
    {
        if(i->second > 1) output_string = str(boost::format("%s %s,") % output_string % i->first);
    }
    output_string = output_string.substr(0, output_string.size()-1);
    output_string = str(boost::format("%s\n * Don't use:") % output_string);
    for(si_iter i = not_very_effective_map.begin(); i != not_very_effective_map.end(); ++i)
    {
        if(i->second > 1) output_string = str(boost::format("%s %s,") % output_string % i->first);
    }
    output_string = output_string.substr(0, output_string.size()-1);

    return output_string;
}

int main(int argc, char *argv[])
{
    //Taking in and processing user options

    string team_file;
    int gen;

    po::options_description desc("Allowed Options");
    desc.add_options()
        ("help", "Display this help message.")
        ("team_file", po::value<string>(&team_file), "Specify a file with a Pokémon team.")
        ("gen", po::value<int>(&gen)->default_value(5), "Specify a generation (1-5).")
        ("verbose", "Enable verbosity.")
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //Process help or user mistake
    if(vm.count("help") > 0)
    {
        print_help(vm, desc);
        return EXIT_FAILURE;
    }

    if(vm.count("team_file") == 0) throw runtime_error("Specify a team file. Run \"team_analysis --help\" for information.");
    if(gen < 1 or gen > 5) throw runtime_error("Gen must be 1-5.");
    bool verbose = (vm.count("verbose") > 0);

    ifstream team_file_input(team_file.c_str(), ifstream::in);
    if(team_file_input.fail()) throw runtime_error("Specified file doesn't exist.");
    string pkmn_name;

    //Get Pokémon team and output
    vector<base_pkmn::sptr> pkmn_team;
    int count = 0;
    cout << "Analyzing team..." << endl << endl;
    while(getline(team_file_input,pkmn_name))
    {
        if(count > 6) break;
        pkmn_team.push_back(base_pkmn::make(pkmn_name, gen, true));
        if(verbose) cout << "Successfully added Pokémon: " << pkmn_name << endl;
        count++;
    }
    if(verbose) cout << endl;
    team_file_input.close();

    cout << "Team:" << endl;
    for(int i = 0; i < pkmn_team.size(); i++)
    {
        string pkmn_name = pkmn_team[i]->get_display_name();
        string type1 = pkmn_team[i]->get_types()[0];
        string type2 = pkmn_team[i]->get_types()[1];

        if(type2 == "None") cout << boost::format(" * %s (%s)\n") % pkmn_name % type1;
        else cout << boost::format(" * %s (%s/%s)\n") % pkmn_name % type1 % type2;
    }
    cout << endl;

    //Get type overlaps and output
    vector<string> type_list = get_type_names(gen);
    map<string, int> type_overlaps = get_type_overlaps(pkmn_team, type_list);

    cout << "Type overlaps:" << endl;
    for(si_iter i = type_overlaps.begin(); i != type_overlaps.end(); ++i)
    {
        cout << boost::format(" * %s (%d)\n") % i->first % i->second;
    }

    //Get type mods for each Pokémon and output
    map<string, map<string, double> > team_mod_map;
    for(int i = 0; i < pkmn_team.size(); i++) //Iterate over Pokémon team
    {
        string pkmn_name = pkmn_team[i]->get_display_name();

        map<string, double> mod_map;
        for(int j = 0; j < type_list.size(); j++) //Iterate over type list
        {
            string type_name = type_list[j];
            string pkmn_type1 = pkmn_team[i]->get_types()[0];
            string pkmn_type2 = pkmn_team[i]->get_types()[1];
            bool is_gen1 = (gen == 1);

            mod_map[type_name] = get_type_damage_mod(type_name, pkmn_type1, is_gen1);
            if(pkmn_type2 != "None")
            {
                mod_map[type_name] *= get_type_damage_mod(type_name, pkmn_type2, is_gen1);
            }
        }
        team_mod_map[pkmn_name] = mod_map;
    }

    cout << endl << "Individual weaknesses/resistances:" << endl;
    for(int i = 0; i < pkmn_team.size(); i++)
    {
        string pkmn_name = pkmn_team[i]->get_display_name();
        string output_string = get_pkmn_effectiveness_string(pkmn_name, team_mod_map[pkmn_name]);

        cout << output_string << endl;
    }

    //Get number of super effective types and not very effective types
    map<string, int> super_effective_map;
    map<string, int> not_very_effective_map;
    for(int i = 0; i < pkmn_team.size(); i++)
    {
        string pkmn_name = pkmn_team[i]->get_display_name();

        for(int j = 0; j < type_list.size(); j++)
        {
            string type_name = type_list[j];

            if(type_name != "Shadow" and type_name != "None" and type_name != "???") //Don't use nonstandard types
            {
                if(team_mod_map[pkmn_name][type_name] < 1.0) not_very_effective_map[type_name]++; //Not very effective
                else if(team_mod_map[pkmn_name][type_name] > 1.0) super_effective_map[type_name]++;
            }
        }
    }
    trim_effectiveness_maps(super_effective_map, not_very_effective_map);
    string trends_string = get_trends_string(super_effective_map, not_very_effective_map);

    cout << endl << "Trends:" << endl << trends_string << endl << endl;

    return EXIT_SUCCESS;
}
<commit_msg>team_analysis: only allow a team of six members<commit_after>/*
 * Copyright (c) 2013 Nicholas Corgan (n.corgan@gmail.com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */
#include "team_analysis_common.hpp"

#include <boost/assign.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <fstream>
#include <iostream>
#include <map>
#include <pkmnsim/base_pkmn.hpp>
#include <pkmnsim/pkmn_types.hpp>
#include <stdexcept>
#include <string>
#include <vector>

//TODO: take move types into account
//TODO: take counter-effectiveness into account

namespace po = boost::program_options;
using namespace pkmnsim;
using namespace std;

void print_help(po::variables_map vm, po::options_description desc)
{
    cout << endl << "Team Analysis - " << desc << endl;

    cout << "Point the --team_file option at a file with" << endl
         << "one Pokémon name on each line. Using Lance's" << endl
         << "first team from Fire Red/Leaf Green as an" << endl
         << "example:" << endl << endl

         << "Gyarados" << endl
         << "Dragonair" << endl
         << "Dragonair" << endl
         << "Aerodactyl" << endl
         << "Dragonite" << endl << endl;
}

string get_pkmn_effectiveness_string(string pkmn_name, map<string, double> &effectiveness_map)
{
    string output_string = str(boost::format(" * %s") % pkmn_name);
    string good_types_str = "   * Use:";
    string bad_types_str = "   * Don't use:";

    //Iterate over map and add to good/bad_types_str as appropriate
    for(sd_iter i = effectiveness_map.begin(); i != effectiveness_map.end(); ++i)
    {
        if(i->second > 1.0) good_types_str = str(boost::format("%s %s,")
                                                 % good_types_str % i->first);
        else if(i->second < 1.0) bad_types_str = str(boost::format("%s %s,")
                                                     % bad_types_str % i->first);
    }

    //Cut off final comma from good/bad_types_str
    good_types_str = good_types_str.substr(0, good_types_str.size()-1);
    bad_types_str = bad_types_str.substr(0, bad_types_str.size()-1);

    //Only add good/bad_types_str onto output string if applicable
    if(good_types_str != " * Use") output_string = str(boost::format("%s\n%s") %
                                                       output_string % good_types_str);
    if(bad_types_str != " * Don't use") output_string = str(boost::format("%s\n%s") %
                                                       output_string % bad_types_str);

    return output_string;
}

string get_trends_string(map<string, int> &super_effective_map, map<string, int> &not_very_effective_map)
{
    string output_string = " * Use:";
    for(si_iter i = super_effective_map.begin(); i != super_effective_map.end(); ++i)
    {
        if(i->second > 1) output_string = str(boost::format("%s %s,") % output_string % i->first);
    }
    output_string = output_string.substr(0, output_string.size()-1);
    output_string = str(boost::format("%s\n * Don't use:") % output_string);
    for(si_iter i = not_very_effective_map.begin(); i != not_very_effective_map.end(); ++i)
    {
        if(i->second > 1) output_string = str(boost::format("%s %s,") % output_string % i->first);
    }
    output_string = output_string.substr(0, output_string.size()-1);

    return output_string;
}

int main(int argc, char *argv[])
{
    //Taking in and processing user options

    string team_file;
    int gen;

    po::options_description desc("Allowed Options");
    desc.add_options()
        ("help", "Display this help message.")
        ("team_file", po::value<string>(&team_file), "Specify a file with a Pokémon team.")
        ("gen", po::value<int>(&gen)->default_value(5), "Specify a generation (1-5).")
        ("verbose", "Enable verbosity.")
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //Process help or user mistake
    if(vm.count("help") > 0)
    {
        print_help(vm, desc);
        return EXIT_FAILURE;
    }

    if(vm.count("team_file") == 0) throw runtime_error("Specify a team file. Run \"team_analysis --help\" for information.");
    if(gen < 1 or gen > 5) throw runtime_error("Gen must be 1-5.");
    bool verbose = (vm.count("verbose") > 0);

    ifstream team_file_input(team_file.c_str(), ifstream::in);
    if(team_file_input.fail()) throw runtime_error("Specified file doesn't exist.");
    string pkmn_name;

    //Get Pokémon team and output
    vector<base_pkmn::sptr> pkmn_team;
    int count = 0;
    cout << "Analyzing team..." << endl << endl;
    while(getline(team_file_input,pkmn_name))
    {
        //A team can only have six members
        if(count > 6) break;
        pkmn_team.push_back(base_pkmn::make(pkmn_name, gen, true));
        if(verbose) cout << "Successfully added Pokémon: " << pkmn_name << endl;
        count++;
    }
    if(verbose) cout << endl;
    team_file_input.close();

    cout << "Team:" << endl;
    for(int i = 0; i < pkmn_team.size(); i++)
    {
        if(i > 5) break;

        string pkmn_name = pkmn_team[i]->get_display_name();
        string type1 = pkmn_team[i]->get_types()[0];
        string type2 = pkmn_team[i]->get_types()[1];

        if(type2 == "None") cout << boost::format(" * %s (%s)\n") % pkmn_name % type1;
        else cout << boost::format(" * %s (%s/%s)\n") % pkmn_name % type1 % type2;
    }
    cout << endl;

    //Get type overlaps and output
    vector<string> type_list = get_type_names(gen);
    map<string, int> type_overlaps = get_type_overlaps(pkmn_team, type_list);

    cout << "Type overlaps:" << endl;
    for(si_iter i = type_overlaps.begin(); i != type_overlaps.end(); ++i)
    {
        cout << boost::format(" * %s (%d)\n") % i->first % i->second;
    }

    //Get type mods for each Pokémon and output
    map<string, map<string, double> > team_mod_map;
    for(int i = 0; i < pkmn_team.size(); i++) //Iterate over Pokémon team
    {
        string pkmn_name = pkmn_team[i]->get_display_name();

        map<string, double> mod_map;
        for(int j = 0; j < type_list.size(); j++) //Iterate over type list
        {
            string type_name = type_list[j];
            string pkmn_type1 = pkmn_team[i]->get_types()[0];
            string pkmn_type2 = pkmn_team[i]->get_types()[1];
            bool is_gen1 = (gen == 1);

            mod_map[type_name] = get_type_damage_mod(type_name, pkmn_type1, is_gen1);
            if(pkmn_type2 != "None")
            {
                mod_map[type_name] *= get_type_damage_mod(type_name, pkmn_type2, is_gen1);
            }
        }
        team_mod_map[pkmn_name] = mod_map;
    }

    cout << endl << "Individual weaknesses/resistances:" << endl;
    for(int i = 0; i < pkmn_team.size(); i++)
    {
        string pkmn_name = pkmn_team[i]->get_display_name();
        string output_string = get_pkmn_effectiveness_string(pkmn_name, team_mod_map[pkmn_name]);

        cout << output_string << endl;
    }

    //Get number of super effective types and not very effective types
    map<string, int> super_effective_map;
    map<string, int> not_very_effective_map;
    for(int i = 0; i < pkmn_team.size(); i++)
    {
        string pkmn_name = pkmn_team[i]->get_display_name();

        for(int j = 0; j < type_list.size(); j++)
        {
            string type_name = type_list[j];

            if(type_name != "Shadow" and type_name != "None" and type_name != "???") //Don't use nonstandard types
            {
                if(team_mod_map[pkmn_name][type_name] < 1.0) not_very_effective_map[type_name]++; //Not very effective
                else if(team_mod_map[pkmn_name][type_name] > 1.0) super_effective_map[type_name]++;
            }
        }
    }
    trim_effectiveness_maps(super_effective_map, not_very_effective_map);
    string trends_string = get_trends_string(super_effective_map, not_very_effective_map);

    cout << endl << "Trends:" << endl << trends_string << endl << endl;

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <dual_quaternion.hpp>
#include <knn_point_cloud.hpp>
#include <kfusion/types.hpp>
#include <nanoflann.hpp>
#include "kfusion/warp_field.hpp"
#include "internal.hpp"
#include "precomp.hpp"
#include <opencv2/core/affine.hpp>
#define VOXEL_SIZE 100

using namespace kfusion;
std::vector<utils::DualQuaternion<float>> neighbours; //THIS SHOULD BE SOMEWHERE ELSE BUT TOO SLOW TO REINITIALISE
utils::PointCloud cloud;

WarpField::WarpField()
{
    index = new kd_tree_t(3, cloud, nanoflann::KDTreeSingleIndexAdaptorParams(10));
    ret_index = std::vector<size_t>(KNN_NEIGHBOURS);
    out_dist_sqr = std::vector<float>(KNN_NEIGHBOURS);
    resultSet = new nanoflann::KNNResultSet<float>(KNN_NEIGHBOURS);
    resultSet->init(&ret_index[0], &out_dist_sqr[0]);
    neighbours = std::vector<utils::DualQuaternion<float>>(KNN_NEIGHBOURS);

}

WarpField::~WarpField()
{}

/**
 *
 * @param frame
 * \note The pose is assumed to be the identity, as this is the first frame
 */
// maybe remove this later and do everything as part of energy since all this code is written twice. Leave it for now.
void WarpField::init(const cv::Mat& first_frame, const cv::Mat& normals)
{
    assert(first_frame.rows == normals.rows);
    assert(first_frame.cols == normals.cols);
    nodes.resize(first_frame.cols * first_frame.rows);

    for(int i = 0; i < first_frame.rows; i++)
        for(int j = 0; j < first_frame.cols; j++)
        {
            auto point = first_frame.at<Point>(i,j);
            auto norm = normals.at<Normal>(i,j);
            if(!std::isnan(point.x))
            {
                nodes[i*first_frame.cols+j].transform = utils::DualQuaternion<float>(utils::Quaternion<float>(0,point.x, point.y, point.z),
                                                                                utils::Quaternion<float>(Vec3f(norm.x,norm.y,norm.z)));

                nodes[i*first_frame.cols+j].vertex = Vec3f(point.x,point.y,point.z);
                nodes[i*first_frame.cols+j].weight = VOXEL_SIZE;
            }
            else
            {
                nodes[i*first_frame.cols+j].valid = false;
            }
        }
    buildKDTree();
}

/**
 * \brief
 * \param frame
 * \param normals
 * \param pose
 * \param tsdfVolume
 * \param edges
 */
void WarpField::energy(const cuda::Cloud &frame,
                       const cuda::Normals &normals,
                       const Affine3f &pose,
                       const cuda::TsdfVolume &tsdfVolume,
                       const std::vector<std::pair<utils::DualQuaternion<float>, utils::DualQuaternion<float>>> &edges
)
{
    assert(normals.cols()==frame.cols());
    assert(normals.rows()==frame.rows());

    int cols = frame.cols();

    std::vector<Point, std::allocator<Point>> cloud_host(size_t(frame.rows()*frame.cols()));
    frame.download(cloud_host, cols);

    std::vector<Normal, std::allocator<Normal>> normals_host(size_t(normals.rows()*normals.cols()));
    normals.download(normals_host, cols);
    for(size_t i = 0; i < cloud_host.size() && i < nodes.size(); i++)
    {
        break;
        auto point = cloud_host[i];
        auto norm = normals_host[i];
        if(!std::isnan(point.x))
        {

        }
        else
        {
//            std::cout<<"NANS"<<std::endl;
//            break;
        }
    }

//    if (m_pWarpField->getNumNodesInLevel(0) == 0)
//    {
//        printf("no warp nodes, return\n");
//        return FLT_MAX;
//    }
//
//    m_vmap_warp = &vmap_warp;
//    m_nmap_warp = &nmap_warp;
//    m_vmap_live = &vmap_live;
//    m_nmap_live = &nmap_live;
//
//    // perform Gauss-Newton iteration
//    //for (int k = 0; k < 100; k++)
//    float totalEnergy = 0.f, data_energy=0.f, reg_energy=0.f;
//    m_pWarpField->extract_nodes_info_no_allocation(m_nodesKnn, m_twist, m_nodesVw);
//    for (int iter = 0; iter < m_param->fusion_GaussNewton_maxIter; iter++)
//    {
//
//        m_Hd = 0.f;
//        cudaSafeCall(cudaMemset(m_g.ptr(), 0, sizeof(float)*m_g.size()),
//                     "GpuGaussNewtonSolver::solve, setg=0");
//
//        checkNan(m_twist, m_numNodes, ("twist_" + std::to_string(iter)).c_str());
//
//        // 1. calculate data term: Hd += Jd'Jd; g += Jd'fd
//        // 2. calculate reg term: Jr = [Jr0 Jr1; 0 Jr3]; fr;
//        // 3. calculate Hessian: Hd += Jr0'Jr0; B = Jr0'Jr1; Hr = Jr1'Jr1 + Jr3'Jr3; g=-(g+Jr'*fr)
//        // 4. solve H*h = g
//        if (m_param->graph_single_level)
//            singleLevelSolve();
//        else
//            blockSolve()
//        // if not fix step, we perform line search
//        if (m_param->fusion_GaussNewton_fixedStep <= 0.f)
//        {
//            float old_energy = calcTotalEnergy(data_energy, reg_energy);
//            float new_energy = 0.f;
//            float alpha = 1.f;
//            const static float alpha_stop = 1e-2;
//            cudaSafeCall(cudaMemcpy(m_tmpvec.ptr(), m_twist.ptr(), m_Jr->cols()*sizeof(float),
//                                    cudaMemcpyDeviceToDevice), "copy tmp vec to twist");
//            for (; alpha > alpha_stop; alpha *= 0.5)
//            {
//                // x += alpha * h
//                updateTwist_inch(m_h.ptr(), alpha);
//                new_energy = calcTotalEnergy(data_energy, reg_energy);
//                if (new_energy < old_energy)
//                    break;
//                // reset x
//                cudaSafeCall(cudaMemcpy(m_twist.ptr(), m_tmpvec.ptr(),
//                                        m_Jr->cols()*sizeof(float), cudaMemcpyDeviceToDevice), "copy twist to tmp vec");
//            }
//            totalEnergy = new_energy;
//            if (alpha <= alpha_stop)
//                break;
//            float norm_h = 0.f, norm_g = 0.f;
//            cublasStatus_t st = cublasSnrm2(m_cublasHandle, m_Jr->cols(),
//                                            m_h.ptr(), 1, &norm_h);
//            st = cublasSnrm2(m_cublasHandle, m_Jr->cols(),
//                             m_g.ptr(), 1, &norm_g);
//            if (norm_h < (norm_g + 1e-6f) * 1e-6f)
//                break;
//        }
//            // else, we perform fixed step update.
//        else
//        {
//            // 5. accumulate: x += step * h;
//            updateTwist_inch(m_h.ptr(), m_param->fusion_GaussNewton_fixedStep);
//        }
//    }// end for iter
//
//    if (m_param->fusion_GaussNewton_fixedStep > 0.f)
//        totalEnergy = calcTotalEnergy(data_energy, reg_energy);
//
//    if (data_energy_)
//        *data_energy_ = data_energy;
//    if (reg_energy_)
//        *reg_energy_ = reg_energy;
//
//    return totalEnergy;
//}
}

/**
 * \brief
 * \param frame
 * \param pose
 * \param tsdfVolume
 */
void WarpField::energy_data(Vec3f v,
                            Vec3f n
)
{
    if (std::isnan(n[0]) || std::isnan(v[0]))
        return;
}
/**
 * \brief
 * \param frame
 * \param pose
 * \param tsdfVolume
 */
void WarpField::energy_data(const cuda::Depth &frame,
                            const Affine3f &pose,
                            const cuda::TsdfVolume &tsdfVolume
)
{
//    const int x = threadIdx.x + blockIdx.x * blockDim.x;
//    const int y = threadIdx.y + blockIdx.y * blockDim.y;
//    if (x >= imgWidth || y >= imgHeight)
//        return;
//
//    const KnnIdx knn = vmapKnn(y, x);
//    Tbx::Point3 v(convert(read_float3_4(vmap_cano(y, x))));
//    Tbx::Vec3 n(convert(read_float3_4(nmap_cano(y, x))));
//
//    if (isnan(n.x) || isnan(v.x))
//        return;
//
//    // 1. get all nodes params
//    // 2. compute function
//    float wk[KnnK];
//    auto dq = calc_pixel_dq(knn, v, wk);
//    float norm_dq = dq.norm();
//    if (norm_dq < Tbx::Dual_quat_cu::epsilon())
//        return;
//    auto dq_not_normalized = dq;
//    dq = dq * (1.f / norm_dq); // normalize
//
//    // compute vl
//
//    // the grad energy
//    const float f = nwarp.dot(vwarp - vl); //normal * (v-vl)
//    const float psi_f = data_term_penalty(f);
//
//    // 3. compute jacobi
//    for (int knnK = 0; knnK < KnnK; knnK++)
//    {
//        if (knn_k(knn, knnK) >= nNodes)
//            break;
//        float df[6];
//
//        // 3.0 p_rotation[0:2]
//        for (int i = 0; i < 3; i++)
//        {
//            float inc;
//            Tbx::Dual_quat_cu dq1 = dq_not_normalized;
//            exchange_ri_k(knn, wk, knnK, i, dq1, inc);
//            dq1 *= (1.f / dq1.norm());
//            nwarp = Tlw*dq1.rotate(n);
//            vwarp = Tlw*dq1.transform(v);
//
//            float f1 = nwarp.dot(vwarp - vl);
//            df[i] = (f1 - f) / inc;
//        }// i=0:3
//
//        // 3.1 p_translation[0:2]
//        for (int i = 0; i < 3; i++)
//        {
//            float inc;
//            Tbx::Dual_quat_cu dq1 = dq_not_normalized;
//            exchange_ti_k(knn, wk, knnK, i, dq1, inc);
//            dq1 *= (1.f / dq1.norm());
//            nwarp = Tlw*dq1.rotate(n);
//            vwarp = Tlw*dq1.transform(v);
//
//            float f1 = nwarp.dot(vwarp - vl);
//            df[i+3] = (f1 - f) / inc;
//        }// i=0:3
//
//        //// reduce--------------------------------------------------
//        int shift = knn_k(knn, knnK) * VarPerNode2;
//        int shift_g = knn_k(knn, knnK) * VarPerNode;
//        for (int i = 0; i < VarPerNode; ++i)
//        {
//            for (int j = 0; j <= i; ++j)
//                atomicAdd(&Hd_[shift + j], df[i] * df[j]);
//            atomicAdd(&g_[shift_g + i], df[i] * psi_f);
//            shift += VarPerNode;
//        }
//    }
}
/**
 * \brief
 * \param edges
 */
void WarpField::energy_reg(const std::vector<std::pair<kfusion::utils::DualQuaternion<float>,
        kfusion::utils::DualQuaternion<float>>> &edges)
{

}

/**
 * Tukey loss function as described in http://web.as.uky.edu/statistics/users/pbreheny/764-F11/notes/12-1.pdf
 * \param x
 * \param c
 * \return
 *
 * \note
 * The value c = 4.685 is usually used for this loss function, and
 * it provides an asymptotic efficiency 95% that of linear
 * regression for the normal distribution
 */
float WarpField::tukeyPenalty(float x, float c) const
{
    return std::abs(x) <= c ? x * std::pow((1 - (x * x) / (c * c)), 2) : 0.0;
}

/**
 * Huber penalty function, implemented as described in https://en.wikipedia.org/wiki/Huber_loss
 * \param a
 * \param delta
 * \return
 */
float WarpField::huberPenalty(float a, float delta) const
{
    return std::abs(a) <= delta ? a * a / 2 : delta * std::abs(a) - delta * delta / 2;
}

/**
 * Modifies the
 * @param points
 */
void WarpField::warp(std::vector<Vec3f>& points) const
{
    int i = 0;
    int nans = 0;
    for (auto& point : points)
    {
        i++;
        if(std::isnan(point[0]) || std::isnan(point[1]) || std::isnan(point[2]))
        {
            nans++;
            continue;
        }
        KNN(point);
        utils::DualQuaternion<float> dqb = DQB(point);
        point = warp_to_live * point; // Apply T_lw first. Is this not inverse of the pose?
//        dqb.transform(point);
    }
}

/**
 * Modifies the
 * @param points
 */
void WarpField::warp(cuda::Cloud& points) const
{
    int i = 0;
    int nans = 0;
//    for (auto& point : points)
//    {
//        i++;
//        if(std::isnan(point[0]) || std::isnan(point[1]) || std::isnan(point[2]))
//        {
//            nans++;
//            continue;
//        }
//        KNN(point);
//        utils::DualQuaternion<float> dqb = DQB(point);
//        point = warp_to_live * point; // Apply T_lw first. Is this not inverse of the pose?
//        dqb.transform(point);
//    }
}

/**
 * \brief
 * \param vertex
 * \param weight
 * \return
 */
utils::DualQuaternion<float> WarpField::DQB(const Vec3f& vertex) const
{
    utils::DualQuaternion<float> quaternion_sum;
    for (size_t i = 0; i < KNN_NEIGHBOURS; i++)
        //FIXME: accessing nodes[ret_index[i]].transform VERY SLOW. Assignment also very slow
        quaternion_sum = quaternion_sum + weighting(out_dist_sqr[ret_index[i]], nodes[ret_index[i]].weight) * nodes[ret_index[i]].transform;

    auto norm = quaternion_sum.magnitude();

    return utils::DualQuaternion<float>(quaternion_sum.getRotation() / norm.first,
                                        quaternion_sum.getTranslation() / norm.second);
}

/**
 * \brief
 * \param squared_dist
 * \param weight
 * \return
 */
float WarpField::weighting(float squared_dist, float weight) const
{
    return (float) exp(-squared_dist / (2 * weight * weight));
}

/**
 * \brief
 * \return
 */
void WarpField::KNN(Vec3f point) const
{
    index->findNeighbors(*resultSet, point.val, nanoflann::SearchParams(10));
}

/**
 * \brief
 * \return
 */
const std::vector<deformation_node>* WarpField::getNodes() const
{
    return &nodes;
}

/**
 * \brief
 * \return
 */
void WarpField::buildKDTree()
{
    //    Build kd-tree with current warp nodes.
    cloud.pts.resize(nodes.size());
    for(size_t i = 0; i < nodes.size(); i++)
        nodes[i].transform.getTranslation(cloud.pts[i]);
    index->buildIndex();
}

//TODO: This can be optimised
const cv::Mat WarpField::getNodesAsMat() const
{
    cv::Mat matrix(1, nodes.size(), CV_32FC3);
    for(int i = 0; i < nodes.size(); i++)
        matrix.at<cv::Vec3f>(i) = nodes[i].vertex;
    return matrix;
}

/**
 * \brief
 */
void WarpField::clear()
{

}
void WarpField::setWarpToLive(const Affine3f &pose)
{
    warp_to_live = pose;
}<commit_msg>Removed commented code<commit_after>#include <dual_quaternion.hpp>
#include <knn_point_cloud.hpp>
#include <kfusion/types.hpp>
#include <nanoflann.hpp>
#include "kfusion/warp_field.hpp"
#include "internal.hpp"
#include "precomp.hpp"
#include <opencv2/core/affine.hpp>
#define VOXEL_SIZE 100

using namespace kfusion;
std::vector<utils::DualQuaternion<float>> neighbours; //THIS SHOULD BE SOMEWHERE ELSE BUT TOO SLOW TO REINITIALISE
utils::PointCloud cloud;

WarpField::WarpField()
{
    index = new kd_tree_t(3, cloud, nanoflann::KDTreeSingleIndexAdaptorParams(10));
    ret_index = std::vector<size_t>(KNN_NEIGHBOURS);
    out_dist_sqr = std::vector<float>(KNN_NEIGHBOURS);
    resultSet = new nanoflann::KNNResultSet<float>(KNN_NEIGHBOURS);
    resultSet->init(&ret_index[0], &out_dist_sqr[0]);
    neighbours = std::vector<utils::DualQuaternion<float>>(KNN_NEIGHBOURS);

}

WarpField::~WarpField()
{}

/**
 *
 * @param frame
 * \note The pose is assumed to be the identity, as this is the first frame
 */
// maybe remove this later and do everything as part of energy since all this code is written twice. Leave it for now.
void WarpField::init(const cv::Mat& first_frame, const cv::Mat& normals)
{
    assert(first_frame.rows == normals.rows);
    assert(first_frame.cols == normals.cols);
    nodes.resize(first_frame.cols * first_frame.rows);

    for(int i = 0; i < first_frame.rows; i++)
        for(int j = 0; j < first_frame.cols; j++)
        {
            auto point = first_frame.at<Point>(i,j);
            auto norm = normals.at<Normal>(i,j);
            if(!std::isnan(point.x))
            {
                nodes[i*first_frame.cols+j].transform = utils::DualQuaternion<float>(utils::Quaternion<float>(0,point.x, point.y, point.z),
                                                                                utils::Quaternion<float>(Vec3f(norm.x,norm.y,norm.z)));

                nodes[i*first_frame.cols+j].vertex = Vec3f(point.x,point.y,point.z);
                nodes[i*first_frame.cols+j].weight = VOXEL_SIZE;
            }
            else
            {
                nodes[i*first_frame.cols+j].valid = false;
            }
        }
    buildKDTree();
}

/**
 * \brief
 * \param frame
 * \param normals
 * \param pose
 * \param tsdfVolume
 * \param edges
 */
void WarpField::energy(const cuda::Cloud &frame,
                       const cuda::Normals &normals,
                       const Affine3f &pose,
                       const cuda::TsdfVolume &tsdfVolume,
                       const std::vector<std::pair<utils::DualQuaternion<float>, utils::DualQuaternion<float>>> &edges
)
{
    assert(normals.cols()==frame.cols());
    assert(normals.rows()==frame.rows());

    int cols = frame.cols();

    std::vector<Point, std::allocator<Point>> cloud_host(size_t(frame.rows()*frame.cols()));
    frame.download(cloud_host, cols);

    std::vector<Normal, std::allocator<Normal>> normals_host(size_t(normals.rows()*normals.cols()));
    normals.download(normals_host, cols);
    for(size_t i = 0; i < cloud_host.size() && i < nodes.size(); i++)
    {
        break;
        auto point = cloud_host[i];
        auto norm = normals_host[i];
        if(!std::isnan(point.x))
        {

        }
        else
        {
//            std::cout<<"NANS"<<std::endl;
//            break;
        }
    }

//    if (m_pWarpField->getNumNodesInLevel(0) == 0)
//    {
//        printf("no warp nodes, return\n");
//        return FLT_MAX;
//    }
//
//    m_vmap_warp = &vmap_warp;
//    m_nmap_warp = &nmap_warp;
//    m_vmap_live = &vmap_live;
//    m_nmap_live = &nmap_live;
//
//    // perform Gauss-Newton iteration
//    //for (int k = 0; k < 100; k++)
//    float totalEnergy = 0.f, data_energy=0.f, reg_energy=0.f;
//    m_pWarpField->extract_nodes_info_no_allocation(m_nodesKnn, m_twist, m_nodesVw);
//    for (int iter = 0; iter < m_param->fusion_GaussNewton_maxIter; iter++)
//    {
//
//        m_Hd = 0.f;
//        cudaSafeCall(cudaMemset(m_g.ptr(), 0, sizeof(float)*m_g.size()),
//                     "GpuGaussNewtonSolver::solve, setg=0");
//
//        checkNan(m_twist, m_numNodes, ("twist_" + std::to_string(iter)).c_str());
//
//        // 1. calculate data term: Hd += Jd'Jd; g += Jd'fd
//        // 2. calculate reg term: Jr = [Jr0 Jr1; 0 Jr3]; fr;
//        // 3. calculate Hessian: Hd += Jr0'Jr0; B = Jr0'Jr1; Hr = Jr1'Jr1 + Jr3'Jr3; g=-(g+Jr'*fr)
//        // 4. solve H*h = g
//        if (m_param->graph_single_level)
//            singleLevelSolve();
//        else
//            blockSolve()
//        // if not fix step, we perform line search
//        if (m_param->fusion_GaussNewton_fixedStep <= 0.f)
//        {
//            float old_energy = calcTotalEnergy(data_energy, reg_energy);
//            float new_energy = 0.f;
//            float alpha = 1.f;
//            const static float alpha_stop = 1e-2;
//            cudaSafeCall(cudaMemcpy(m_tmpvec.ptr(), m_twist.ptr(), m_Jr->cols()*sizeof(float),
//                                    cudaMemcpyDeviceToDevice), "copy tmp vec to twist");
//            for (; alpha > alpha_stop; alpha *= 0.5)
//            {
//                // x += alpha * h
//                updateTwist_inch(m_h.ptr(), alpha);
//                new_energy = calcTotalEnergy(data_energy, reg_energy);
//                if (new_energy < old_energy)
//                    break;
//                // reset x
//                cudaSafeCall(cudaMemcpy(m_twist.ptr(), m_tmpvec.ptr(),
//                                        m_Jr->cols()*sizeof(float), cudaMemcpyDeviceToDevice), "copy twist to tmp vec");
//            }
//            totalEnergy = new_energy;
//            if (alpha <= alpha_stop)
//                break;
//            float norm_h = 0.f, norm_g = 0.f;
//            cublasStatus_t st = cublasSnrm2(m_cublasHandle, m_Jr->cols(),
//                                            m_h.ptr(), 1, &norm_h);
//            st = cublasSnrm2(m_cublasHandle, m_Jr->cols(),
//                             m_g.ptr(), 1, &norm_g);
//            if (norm_h < (norm_g + 1e-6f) * 1e-6f)
//                break;
//        }
//            // else, we perform fixed step update.
//        else
//        {
//            // 5. accumulate: x += step * h;
//            updateTwist_inch(m_h.ptr(), m_param->fusion_GaussNewton_fixedStep);
//        }
//    }// end for iter
//
//    if (m_param->fusion_GaussNewton_fixedStep > 0.f)
//        totalEnergy = calcTotalEnergy(data_energy, reg_energy);
//
//    if (data_energy_)
//        *data_energy_ = data_energy;
//    if (reg_energy_)
//        *reg_energy_ = reg_energy;
//
//    return totalEnergy;
//}
}

/**
 * \brief
 * \param frame
 * \param pose
 * \param tsdfVolume
 */
void WarpField::energy_data(Vec3f v,
                            Vec3f n
)
{
    if (std::isnan(n[0]) || std::isnan(v[0]))
        return;
}
/**
 * \brief
 * \param frame
 * \param pose
 * \param tsdfVolume
 */
void WarpField::energy_data(const cuda::Depth &frame,
                            const Affine3f &pose,
                            const cuda::TsdfVolume &tsdfVolume
)
{

}
/**
 * \brief
 * \param edges
 */
void WarpField::energy_reg(const std::vector<std::pair<kfusion::utils::DualQuaternion<float>,
        kfusion::utils::DualQuaternion<float>>> &edges)
{

}

/**
 * Tukey loss function as described in http://web.as.uky.edu/statistics/users/pbreheny/764-F11/notes/12-1.pdf
 * \param x
 * \param c
 * \return
 *
 * \note
 * The value c = 4.685 is usually used for this loss function, and
 * it provides an asymptotic efficiency 95% that of linear
 * regression for the normal distribution
 */
float WarpField::tukeyPenalty(float x, float c) const
{
    return std::abs(x) <= c ? x * std::pow((1 - (x * x) / (c * c)), 2) : 0.0;
}

/**
 * Huber penalty function, implemented as described in https://en.wikipedia.org/wiki/Huber_loss
 * \param a
 * \param delta
 * \return
 */
float WarpField::huberPenalty(float a, float delta) const
{
    return std::abs(a) <= delta ? a * a / 2 : delta * std::abs(a) - delta * delta / 2;
}

/**
 * Modifies the
 * @param points
 */
void WarpField::warp(std::vector<Vec3f>& points) const
{
    int i = 0;
    int nans = 0;
    for (auto& point : points)
    {
        i++;
        if(std::isnan(point[0]) || std::isnan(point[1]) || std::isnan(point[2]))
        {
            nans++;
            continue;
        }
        KNN(point);
        utils::DualQuaternion<float> dqb = DQB(point);
        point = warp_to_live * point; // Apply T_lw first. Is this not inverse of the pose?
//        dqb.transform(point);
    }
}

/**
 * Modifies the
 * @param points
 */
void WarpField::warp(cuda::Cloud& points) const
{
    int i = 0;
    int nans = 0;
//    for (auto& point : points)
//    {
//        i++;
//        if(std::isnan(point[0]) || std::isnan(point[1]) || std::isnan(point[2]))
//        {
//            nans++;
//            continue;
//        }
//        KNN(point);
//        utils::DualQuaternion<float> dqb = DQB(point);
//        point = warp_to_live * point; // Apply T_lw first. Is this not inverse of the pose?
//        dqb.transform(point);
//    }
}

/**
 * \brief
 * \param vertex
 * \param weight
 * \return
 */
utils::DualQuaternion<float> WarpField::DQB(const Vec3f& vertex) const
{
    utils::DualQuaternion<float> quaternion_sum;
    for (size_t i = 0; i < KNN_NEIGHBOURS; i++)
        //FIXME: accessing nodes[ret_index[i]].transform VERY SLOW. Assignment also very slow
        quaternion_sum = quaternion_sum + weighting(out_dist_sqr[ret_index[i]], nodes[ret_index[i]].weight) * nodes[ret_index[i]].transform;

    auto norm = quaternion_sum.magnitude();

    return utils::DualQuaternion<float>(quaternion_sum.getRotation() / norm.first,
                                        quaternion_sum.getTranslation() / norm.second);
}

/**
 * \brief
 * \param squared_dist
 * \param weight
 * \return
 */
float WarpField::weighting(float squared_dist, float weight) const
{
    return (float) exp(-squared_dist / (2 * weight * weight));
}

/**
 * \brief
 * \return
 */
void WarpField::KNN(Vec3f point) const
{
    index->findNeighbors(*resultSet, point.val, nanoflann::SearchParams(10));
}

/**
 * \brief
 * \return
 */
const std::vector<deformation_node>* WarpField::getNodes() const
{
    return &nodes;
}

/**
 * \brief
 * \return
 */
void WarpField::buildKDTree()
{
    //    Build kd-tree with current warp nodes.
    cloud.pts.resize(nodes.size());
    for(size_t i = 0; i < nodes.size(); i++)
        nodes[i].transform.getTranslation(cloud.pts[i]);
    index->buildIndex();
}

//TODO: This can be optimised
const cv::Mat WarpField::getNodesAsMat() const
{
    cv::Mat matrix(1, nodes.size(), CV_32FC3);
    for(int i = 0; i < nodes.size(); i++)
        matrix.at<cv::Vec3f>(i) = nodes[i].vertex;
    return matrix;
}

/**
 * \brief
 */
void WarpField::clear()
{

}
void WarpField::setWarpToLive(const Affine3f &pose)
{
    warp_to_live = pose;
}<|endoftext|>


<commit_before>#include "musicspectrumlayoutwidget.h"
#include "musicuiobject.h"

#include <QScrollArea>
#include <QSignalMapper>

MusicSpectrumLayoutItem::MusicSpectrumLayoutItem(QWidget *parent)
    : MusicClickedLabel(parent)
{
    setFixedSize(250, 40);

    QHBoxLayout *layout = new QHBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);

    m_box = new QCheckBox(this);
    m_box->setStyleSheet(MusicUIObject::MCheckBoxStyle01);
    m_box->setAttribute(Qt::WA_TransparentForMouseEvents);
#ifdef Q_OS_UNIX
    m_box->setFocusPolicy(Qt::NoFocus);
#endif
    m_label = new QLabel(this);
    m_label->setFixedSize(219, 40);
    layout->addWidget(m_box);
    layout->addWidget(m_label);
    layout->addStretch(1);
    setLayout(layout);
}

MusicSpectrumLayoutItem::~MusicSpectrumLayoutItem()
{
    delete m_label;
    delete m_box;
}

void MusicSpectrumLayoutItem::addItem(const QString &item, const QString &tip)
{
    m_label->setPixmap(item);
    setToolTip(tip);
}

void MusicSpectrumLayoutItem::setCheck(bool check)
{
    m_box->setChecked(check);
}

bool MusicSpectrumLayoutItem::isChecked() const
{
    return m_box->isChecked();
}

MusicSpectrumLayoutWidget::MusicSpectrumLayoutWidget(QWidget *parent)
    : MusicToolMenuWidget(parent)
{
    initWidget();
}

MusicSpectrumLayoutWidget::~MusicSpectrumLayoutWidget()
{
    qDeleteAll(m_items);
}

void MusicSpectrumLayoutWidget::popupMenu()
{
    m_menu->exec( mapToGlobal(QPoint(-m_containWidget->width() + width(), 0)));
}

void MusicSpectrumLayoutWidget::labelClicked(int index)
{
    if(m_exclusive)
    {
        foreach(MusicSpectrumLayoutItem *item, m_items)
        {
            item->setCheck(false);
        }
    }

    const QStringList &types = spectrumTypeList();
    bool state = m_items[index]->isChecked();

    state = !state;
    m_items[index]->setCheck(state);

    Q_EMIT stateChanged(state, types[index]);
    if(!state)
    {
        m_items[index]->setCheck(false);
    }
    m_menu->close();
}

void MusicSpectrumLayoutWidget::initWidget()
{
    m_exclusive = false;

    const QString &style = MusicUIObject::MBorderStyle04 + MusicUIObject::MBackgroundStyle17;
    setObjectName("mianWidget");
    setStyleSheet(QString("#mianWidget{%1}").arg(style));

    m_containWidget->setFixedSize(270, 220);
    m_containWidget->setObjectName("containWidget");
    m_containWidget->setStyleSheet(QString("#containWidget{%1}").arg(style));

    QVBoxLayout *layout = new QVBoxLayout(m_containWidget);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);

    QScrollArea *scrollArea = new QScrollArea(m_containWidget);
    QWidget *containWidget = new QWidget(scrollArea);
    containWidget->setStyleSheet(MusicUIObject::MBackgroundStyle17);
    m_containLayout = new QVBoxLayout(containWidget);

    m_containLayout->setContentsMargins(5, 0, 0, 0);
    m_containLayout->setSpacing(20);
    containWidget->setLayout(m_containLayout);

    scrollArea->setStyleSheet(MusicUIObject::MScrollBarStyle01);
    scrollArea->setWidgetResizable(true);
    scrollArea->setFrameShape(QFrame::NoFrame);
    scrollArea->setAlignment(Qt::AlignLeft);
    scrollArea->setWidget(containWidget);
    scrollArea->viewport()->setStyleSheet(MusicUIObject::MBackgroundStyle17);
    layout->addWidget(scrollArea);

    m_containWidget->setLayout(layout);
}

void MusicSpectrumLayoutWidget::addItems(const ItemInfos &items)
{
    QSignalMapper *mapper = new QSignalMapper(this);
    connect(mapper, SIGNAL(mapped(int)), SLOT(labelClicked(int)));

    for(int i=0; i<items.count(); ++i)
    {
        const ItemInfo &info = items[i];
        MusicSpectrumLayoutItem *item = new MusicSpectrumLayoutItem(this);
        item->addItem(info.first, info.second);
        connect(item, SIGNAL(clicked()), mapper, SLOT(map()));
        mapper->setMapping(item, i);
        m_containLayout->addWidget(item);
        m_items << item;
    }
}

MusicSpectrumNormalLayoutWidget::MusicSpectrumNormalLayoutWidget(QWidget *parent)
    : MusicSpectrumLayoutWidget(parent)
{
    ItemInfos items;
    items << ItemInfo(":/spectrum/normal_1", tr("Analyzer"));
    items << ItemInfo(":/spectrum/normal_2", tr("EWave"));
    items << ItemInfo(":/spectrum/normal_3", tr("FlowWave"));
    items << ItemInfo(":/spectrum/normal_4", tr("Histogram"));
    items << ItemInfo(":/spectrum/normal_5", tr("Line"));
    items << ItemInfo(":/spectrum/normal_6", tr("SpaceWave"));
    addItems(items);
}

MusicSpectrumNormalLayoutWidget::~MusicSpectrumNormalLayoutWidget()
{

}

QStringList MusicSpectrumNormalLayoutWidget::spectrumTypeList() const
{
    return QStringList() << "normalanalyzer" << "normalewave" << "normalflowwave"
                         << "normalhistogram" << "normalline" << "normalspacewave";
}

MusicSpectrumPlusLayoutWidget::MusicSpectrumPlusLayoutWidget(QWidget *parent)
    : MusicSpectrumLayoutWidget(parent)
{
    ItemInfos items;
    items << ItemInfo(":/spectrum/plus_1", tr("FoldWave"));
    items << ItemInfo(":/spectrum/plus_2", tr("Monowave"));
    items << ItemInfo(":/spectrum/plus_3", tr("Multiwave"));
    items << ItemInfo(":/spectrum/plus_4", tr("XRays"));
    items << ItemInfo(":/spectrum/plus_5", tr("PointXRays"));
    items << ItemInfo(":/spectrum/plus_6", tr("VolumeWave"));
    items << ItemInfo(":/spectrum/plus_7", tr("LightEnvelope"));
    addItems(items);
}

MusicSpectrumPlusLayoutWidget::~MusicSpectrumPlusLayoutWidget()
{

}

QStringList MusicSpectrumPlusLayoutWidget::spectrumTypeList() const
{
    return QStringList() << "plusfoldwave" << "plusmonowave" << "plusmultiwave" << "plusxrays"
                         << "pluspointxrays" << "plusvolumewave" << "lightenvelope";
}

MusicSpectrumFloridLayoutWidget::MusicSpectrumFloridLayoutWidget(QWidget *parent)
    : MusicSpectrumLayoutWidget(parent)
{
    m_exclusive = true;

    ItemInfos items;
    items << ItemInfo(":/spectrum/florid_1", tr("Goom"));
    items << ItemInfo(":/spectrum/florid_2", tr("Ethereality"));
    items << ItemInfo(":/spectrum/florid_3", tr("Reverb"));
    items << ItemInfo(":/spectrum/florid_4", tr("Autism"));
    items << ItemInfo(":/spectrum/florid_5", tr("Bass"));
    items << ItemInfo(":/spectrum/florid_6", tr("Surround"));
    items << ItemInfo(":/spectrum/florid_7", tr("Ancient"));
    items << ItemInfo(":/spectrum/florid_8", tr("Electric"));
    addItems(items);
}

MusicSpectrumFloridLayoutWidget::~MusicSpectrumFloridLayoutWidget()
{

}

QStringList MusicSpectrumFloridLayoutWidget::spectrumTypeList() const
{
    return QStringList() << "floridgoom" << "floridethereality" << "floridreverb" << "floridautism"
                         << "floridbass" << "floridsurround" << "floridancient" << "floridelectric";
}
<commit_msg>Add projectM module[648259]<commit_after>#include "musicspectrumlayoutwidget.h"
#include "musicuiobject.h"

#include <QScrollArea>
#include <QSignalMapper>

MusicSpectrumLayoutItem::MusicSpectrumLayoutItem(QWidget *parent)
    : MusicClickedLabel(parent)
{
    setFixedSize(250, 40);

    QHBoxLayout *layout = new QHBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);

    m_box = new QCheckBox(this);
    m_box->setStyleSheet(MusicUIObject::MCheckBoxStyle01);
    m_box->setAttribute(Qt::WA_TransparentForMouseEvents);
#ifdef Q_OS_UNIX
    m_box->setFocusPolicy(Qt::NoFocus);
#endif
    m_label = new QLabel(this);
    m_label->setFixedSize(219, 40);
    layout->addWidget(m_box);
    layout->addWidget(m_label);
    layout->addStretch(1);
    setLayout(layout);
}

MusicSpectrumLayoutItem::~MusicSpectrumLayoutItem()
{
    delete m_label;
    delete m_box;
}

void MusicSpectrumLayoutItem::addItem(const QString &item, const QString &tip)
{
    m_label->setPixmap(item);
    setToolTip(tip);
}

void MusicSpectrumLayoutItem::setCheck(bool check)
{
    m_box->setChecked(check);
}

bool MusicSpectrumLayoutItem::isChecked() const
{
    return m_box->isChecked();
}

MusicSpectrumLayoutWidget::MusicSpectrumLayoutWidget(QWidget *parent)
    : MusicToolMenuWidget(parent)
{
    initWidget();
}

MusicSpectrumLayoutWidget::~MusicSpectrumLayoutWidget()
{
    qDeleteAll(m_items);
}

void MusicSpectrumLayoutWidget::popupMenu()
{
    m_menu->exec( mapToGlobal(QPoint(-m_containWidget->width() + width(), 0)));
}

void MusicSpectrumLayoutWidget::labelClicked(int index)
{
    if(m_exclusive)
    {
        foreach(MusicSpectrumLayoutItem *item, m_items)
        {
            item->setCheck(false);
        }
    }

    const QStringList &types = spectrumTypeList();
    bool state = m_items[index]->isChecked();

    state = !state;
    m_items[index]->setCheck(state);

    Q_EMIT stateChanged(state, types[index]);
    if(!state)
    {
        m_items[index]->setCheck(false);
    }
    m_menu->close();
}

void MusicSpectrumLayoutWidget::initWidget()
{
    m_exclusive = false;

    const QString &style = MusicUIObject::MBorderStyle04 + MusicUIObject::MBackgroundStyle17;
    setObjectName("mianWidget");
    setStyleSheet(QString("#mianWidget{%1}").arg(style));

    m_containWidget->setFixedSize(270, 220);
    m_containWidget->setObjectName("containWidget");
    m_containWidget->setStyleSheet(QString("#containWidget{%1}").arg(style));

    QVBoxLayout *layout = new QVBoxLayout(m_containWidget);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);

    QScrollArea *scrollArea = new QScrollArea(m_containWidget);
    QWidget *containWidget = new QWidget(scrollArea);
    containWidget->setStyleSheet(MusicUIObject::MBackgroundStyle17);
    m_containLayout = new QVBoxLayout(containWidget);

    m_containLayout->setContentsMargins(5, 0, 0, 0);
    m_containLayout->setSpacing(20);
    containWidget->setLayout(m_containLayout);

    scrollArea->setStyleSheet(MusicUIObject::MScrollBarStyle01);
    scrollArea->setWidgetResizable(true);
    scrollArea->setFrameShape(QFrame::NoFrame);
    scrollArea->setAlignment(Qt::AlignLeft);
    scrollArea->setWidget(containWidget);
    scrollArea->viewport()->setStyleSheet(MusicUIObject::MBackgroundStyle17);
    layout->addWidget(scrollArea);

    m_containWidget->setLayout(layout);
}

void MusicSpectrumLayoutWidget::addItems(const ItemInfos &items)
{
    QSignalMapper *mapper = new QSignalMapper(this);
    connect(mapper, SIGNAL(mapped(int)), SLOT(labelClicked(int)));

    for(int i=0; i<items.count(); ++i)
    {
        const ItemInfo &info = items[i];
        MusicSpectrumLayoutItem *item = new MusicSpectrumLayoutItem(this);
        item->addItem(info.first, info.second);
        connect(item, SIGNAL(clicked()), mapper, SLOT(map()));
        mapper->setMapping(item, i);
        m_containLayout->addWidget(item);
        m_items << item;
    }
}

MusicSpectrumNormalLayoutWidget::MusicSpectrumNormalLayoutWidget(QWidget *parent)
    : MusicSpectrumLayoutWidget(parent)
{
    ItemInfos items;
    items << ItemInfo(":/spectrum/normal_1", tr("Analyzer"));
    items << ItemInfo(":/spectrum/normal_2", tr("EWave"));
    items << ItemInfo(":/spectrum/normal_3", tr("FlowWave"));
    items << ItemInfo(":/spectrum/normal_4", tr("Histogram"));
    items << ItemInfo(":/spectrum/normal_5", tr("Line"));
    items << ItemInfo(":/spectrum/normal_6", tr("SpaceWave"));
    addItems(items);
}

MusicSpectrumNormalLayoutWidget::~MusicSpectrumNormalLayoutWidget()
{

}

QStringList MusicSpectrumNormalLayoutWidget::spectrumTypeList() const
{
    return QStringList() << "normalanalyzer" << "normalewave" << "normalflowwave"
                         << "normalhistogram" << "normalline" << "normalspacewave";
}

MusicSpectrumPlusLayoutWidget::MusicSpectrumPlusLayoutWidget(QWidget *parent)
    : MusicSpectrumLayoutWidget(parent)
{
    ItemInfos items;
    items << ItemInfo(":/spectrum/plus_1", tr("FoldWave"));
    items << ItemInfo(":/spectrum/plus_2", tr("Monowave"));
    items << ItemInfo(":/spectrum/plus_3", tr("Multiwave"));
    items << ItemInfo(":/spectrum/plus_4", tr("XRays"));
    items << ItemInfo(":/spectrum/plus_5", tr("PointXRays"));
    items << ItemInfo(":/spectrum/plus_6", tr("VolumeWave"));
    items << ItemInfo(":/spectrum/plus_7", tr("LightEnvelope"));
    addItems(items);
}

MusicSpectrumPlusLayoutWidget::~MusicSpectrumPlusLayoutWidget()
{

}

QStringList MusicSpectrumPlusLayoutWidget::spectrumTypeList() const
{
    return QStringList() << "plusfoldwave" << "plusmonowave" << "plusmultiwave" << "plusxrays"
                         << "pluspointxrays" << "plusvolumewave" << "lightenvelope";
}

MusicSpectrumFloridLayoutWidget::MusicSpectrumFloridLayoutWidget(QWidget *parent)
    : MusicSpectrumLayoutWidget(parent)
{
    m_exclusive = true;

    ItemInfos items;
    items << ItemInfo(":/spectrum/florid_1", tr("Goom"));
    items << ItemInfo(":/spectrum/florid_1", tr("ProjectM"));
    items << ItemInfo(":/spectrum/florid_2", tr("Ethereality"));
    items << ItemInfo(":/spectrum/florid_3", tr("Reverb"));
    items << ItemInfo(":/spectrum/florid_4", tr("Autism"));
    items << ItemInfo(":/spectrum/florid_5", tr("Bass"));
    items << ItemInfo(":/spectrum/florid_6", tr("Surround"));
    items << ItemInfo(":/spectrum/florid_7", tr("Ancient"));
    items << ItemInfo(":/spectrum/florid_8", tr("Electric"));
    addItems(items);
}

MusicSpectrumFloridLayoutWidget::~MusicSpectrumFloridLayoutWidget()
{

}

QStringList MusicSpectrumFloridLayoutWidget::spectrumTypeList() const
{
    return QStringList() << "floridgoom" << "floridprojectm" << "floridethereality" << "floridreverb" << "floridautism"
                         << "floridbass" << "floridsurround" << "floridancient" << "floridelectric";
}
<|endoftext|>