<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: unchss.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-26 17:01:17 $
 *
 *  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"

#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _SFXSTYLE_HXX //autogen
#include <svtools/style.hxx>
#endif
#ifndef _SFXSMPLHINT_HXX //autogen
#include <svtools/smplhint.hxx>
#endif
#ifndef _SVDOBJ_HXX
#include <svx/svdobj.hxx>
#endif

#include "unchss.hxx"

#include "strings.hrc"
#include "glob.hxx"
#include "sdresid.hxx"
#include "drawdoc.hxx"
#include "stlsheet.hxx"
#include "glob.hrc"

TYPEINIT1(StyleSheetUndoAction, SdUndoAction);

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

StyleSheetUndoAction::StyleSheetUndoAction(SdDrawDocument* pTheDoc,
                                           SfxStyleSheet* pTheStyleSheet,
                                           const SfxItemSet* pTheNewItemSet) :
                      SdUndoAction(pTheDoc)
{
    DBG_ASSERT(pTheStyleSheet, "Undo ohne StyleSheet ???");
    pStyleSheet = pTheStyleSheet;

    // ItemSets anlegen; Vorsicht, das neue koennte aus einem anderen Pool
    // stammen, also mitsamt seinen Items clonen
    pNewSet = new SfxItemSet((SfxItemPool&)SdrObject::GetGlobalDrawObjectItemPool(), pTheNewItemSet->GetRanges());
    pTheDoc->MigrateItemSet( pTheNewItemSet, pNewSet, pTheDoc );

    pOldSet = new SfxItemSet((SfxItemPool&)SdrObject::GetGlobalDrawObjectItemPool(),pStyleSheet->GetItemSet().GetRanges());
    pTheDoc->MigrateItemSet( &pStyleSheet->GetItemSet(), pOldSet, pTheDoc );

    aComment = String(SdResId(STR_UNDO_CHANGE_PRES_OBJECT));
    String aName(pStyleSheet->GetName());

    // Layoutnamen und Separator loeschen
    String aSep( RTL_CONSTASCII_USTRINGPARAM( SD_LT_SEPARATOR ) );
    USHORT nPos = aName.Search(aSep);
    if( nPos != STRING_NOTFOUND )
        aName.Erase(0, nPos + aSep.Len());

    if (aName == String(SdResId(STR_LAYOUT_TITLE)))
    {
        aName = String(SdResId(STR_PSEUDOSHEET_TITLE));
    }
    else if (aName == String(SdResId(STR_LAYOUT_SUBTITLE)))
    {
        aName = String(SdResId(STR_PSEUDOSHEET_SUBTITLE));
    }
    else if (aName == String(SdResId(STR_LAYOUT_BACKGROUND)))
    {
        aName = String(SdResId(STR_PSEUDOSHEET_BACKGROUND));
    }
    else if (aName == String(SdResId(STR_LAYOUT_BACKGROUNDOBJECTS)))
    {
        aName = String(SdResId(STR_PSEUDOSHEET_BACKGROUNDOBJECTS));
    }
    else if (aName == String(SdResId(STR_LAYOUT_NOTES)))
    {
        aName = String(SdResId(STR_PSEUDOSHEET_NOTES));
    }
    else
    {
        String aOutlineStr(SdResId(STR_PSEUDOSHEET_OUTLINE));
        nPos = aName.Search(aOutlineStr);
        if (nPos != STRING_NOTFOUND)
        {
            String aNumStr(aName.Copy(aOutlineStr.Len()));
            aName = String(SdResId(STR_LAYOUT_OUTLINE));
            aName += aNumStr;
        }
    }

    // Platzhalter durch Vorlagennamen ersetzen
    nPos = aComment.Search(sal_Unicode('$'));
    aComment.Erase(nPos, 1);
    aComment.Insert(aName, nPos);
}

/*************************************************************************
|*
|* Undo()
|*
\************************************************************************/

void StyleSheetUndoAction::Undo()
{
    SfxItemSet aNewSet( mpDoc->GetItemPool(), pOldSet->GetRanges() );
    mpDoc->MigrateItemSet( pOldSet, &aNewSet, mpDoc );

    pStyleSheet->GetItemSet().Set(aNewSet);
    if( pStyleSheet->GetFamily() == SFX_STYLE_FAMILY_PSEUDO )
        ( (SdStyleSheet*)pStyleSheet )->GetRealStyleSheet()->Broadcast(SfxSimpleHint(SFX_HINT_DATACHANGED));
    else
        pStyleSheet->Broadcast(SfxSimpleHint(SFX_HINT_DATACHANGED));
}

/*************************************************************************
|*
|* Redo()
|*
\************************************************************************/

void StyleSheetUndoAction::Redo()
{
    SfxItemSet aNewSet( mpDoc->GetItemPool(), pOldSet->GetRanges() );
    mpDoc->MigrateItemSet( pNewSet, &aNewSet, mpDoc );

    pStyleSheet->GetItemSet().Set(aNewSet);
    if( pStyleSheet->GetFamily() == SFX_STYLE_FAMILY_PSEUDO )
        ( (SdStyleSheet*)pStyleSheet )->GetRealStyleSheet()->Broadcast(SfxSimpleHint(SFX_HINT_DATACHANGED));
    else
        pStyleSheet->Broadcast(SfxSimpleHint(SFX_HINT_DATACHANGED));
}

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/

StyleSheetUndoAction::~StyleSheetUndoAction()
{
    delete pNewSet;
    delete pOldSet;
}

/*************************************************************************
|*
|* Kommentar liefern
|*
\************************************************************************/

String StyleSheetUndoAction::GetComment() const
{
    return aComment;
}
<commit_msg>INTEGRATION: CWS impresstables2 (1.7.44); FILE MERGED 2007/12/01 19:19:40 cl 1.7.44.2: RESYNC: (1.7-1.8); FILE MERGED 2007/07/26 18:08:21 cl 1.7.44.1: #i68103# added cell styles<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: unchss.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2008-03-12 11:37:35 $
 *
 *  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"

#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _SFXSTYLE_HXX //autogen
#include <svtools/style.hxx>
#endif
#ifndef _SFXSMPLHINT_HXX //autogen
#include <svtools/smplhint.hxx>
#endif
#ifndef _SVDOBJ_HXX
#include <svx/svdobj.hxx>
#endif

#include "unchss.hxx"

#include "strings.hrc"
#include "glob.hxx"
#include "sdresid.hxx"
#include "drawdoc.hxx"
#include "stlsheet.hxx"
#include "glob.hrc"

TYPEINIT1(StyleSheetUndoAction, SdUndoAction);

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

StyleSheetUndoAction::StyleSheetUndoAction(SdDrawDocument* pTheDoc,
                                           SfxStyleSheet* pTheStyleSheet,
                                           const SfxItemSet* pTheNewItemSet) :
                      SdUndoAction(pTheDoc)
{
    DBG_ASSERT(pTheStyleSheet, "Undo ohne StyleSheet ???");
    pStyleSheet = pTheStyleSheet;

    // ItemSets anlegen; Vorsicht, das neue koennte aus einem anderen Pool
    // stammen, also mitsamt seinen Items clonen
    pNewSet = new SfxItemSet((SfxItemPool&)SdrObject::GetGlobalDrawObjectItemPool(), pTheNewItemSet->GetRanges());
    pTheDoc->MigrateItemSet( pTheNewItemSet, pNewSet, pTheDoc );

    pOldSet = new SfxItemSet((SfxItemPool&)SdrObject::GetGlobalDrawObjectItemPool(),pStyleSheet->GetItemSet().GetRanges());
    pTheDoc->MigrateItemSet( &pStyleSheet->GetItemSet(), pOldSet, pTheDoc );

    aComment = String(SdResId(STR_UNDO_CHANGE_PRES_OBJECT));
    String aName(pStyleSheet->GetName());

    // Layoutnamen und Separator loeschen
    String aSep( RTL_CONSTASCII_USTRINGPARAM( SD_LT_SEPARATOR ) );
    USHORT nPos = aName.Search(aSep);
    if( nPos != STRING_NOTFOUND )
        aName.Erase(0, nPos + aSep.Len());

    if (aName == String(SdResId(STR_LAYOUT_TITLE)))
    {
        aName = String(SdResId(STR_PSEUDOSHEET_TITLE));
    }
    else if (aName == String(SdResId(STR_LAYOUT_SUBTITLE)))
    {
        aName = String(SdResId(STR_PSEUDOSHEET_SUBTITLE));
    }
    else if (aName == String(SdResId(STR_LAYOUT_BACKGROUND)))
    {
        aName = String(SdResId(STR_PSEUDOSHEET_BACKGROUND));
    }
    else if (aName == String(SdResId(STR_LAYOUT_BACKGROUNDOBJECTS)))
    {
        aName = String(SdResId(STR_PSEUDOSHEET_BACKGROUNDOBJECTS));
    }
    else if (aName == String(SdResId(STR_LAYOUT_NOTES)))
    {
        aName = String(SdResId(STR_PSEUDOSHEET_NOTES));
    }
    else
    {
        String aOutlineStr(SdResId(STR_PSEUDOSHEET_OUTLINE));
        nPos = aName.Search(aOutlineStr);
        if (nPos != STRING_NOTFOUND)
        {
            String aNumStr(aName.Copy(aOutlineStr.Len()));
            aName = String(SdResId(STR_LAYOUT_OUTLINE));
            aName += aNumStr;
        }
    }

    // Platzhalter durch Vorlagennamen ersetzen
    nPos = aComment.Search(sal_Unicode('$'));
    aComment.Erase(nPos, 1);
    aComment.Insert(aName, nPos);
}

/*************************************************************************
|*
|* Undo()
|*
\************************************************************************/

void StyleSheetUndoAction::Undo()
{
    SfxItemSet aNewSet( mpDoc->GetItemPool(), pOldSet->GetRanges() );
    mpDoc->MigrateItemSet( pOldSet, &aNewSet, mpDoc );

    pStyleSheet->GetItemSet().Set(aNewSet);
    if( pStyleSheet->GetFamily() == SD_STYLE_FAMILY_PSEUDO )
        ( (SdStyleSheet*)pStyleSheet )->GetRealStyleSheet()->Broadcast(SfxSimpleHint(SFX_HINT_DATACHANGED));
    else
        pStyleSheet->Broadcast(SfxSimpleHint(SFX_HINT_DATACHANGED));
}

/*************************************************************************
|*
|* Redo()
|*
\************************************************************************/

void StyleSheetUndoAction::Redo()
{
    SfxItemSet aNewSet( mpDoc->GetItemPool(), pOldSet->GetRanges() );
    mpDoc->MigrateItemSet( pNewSet, &aNewSet, mpDoc );

    pStyleSheet->GetItemSet().Set(aNewSet);
    if( pStyleSheet->GetFamily() == SD_STYLE_FAMILY_PSEUDO )
        ( (SdStyleSheet*)pStyleSheet )->GetRealStyleSheet()->Broadcast(SfxSimpleHint(SFX_HINT_DATACHANGED));
    else
        pStyleSheet->Broadcast(SfxSimpleHint(SFX_HINT_DATACHANGED));
}

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/

StyleSheetUndoAction::~StyleSheetUndoAction()
{
    delete pNewSet;
    delete pOldSet;
}

/*************************************************************************
|*
|* Kommentar liefern
|*
\************************************************************************/

String StyleSheetUndoAction::GetComment() const
{
    return aComment;
}
<|endoftext|>


<commit_before>#include "foo_musicbrainz.h"
#include "FileTagMap.h"
#include "Medium.h"
#include "Release.h"
#include "Track.h"

using namespace foo_musicbrainz;

Tag::Tag(Release &release, Medium &medium, Track &track) {
	set("ALBUM", release.get_title());
	pfc::string8 date = release.get_date();
	if (!date.is_empty()) {
		set("DATE", date);
	}

	set("TITLE", track.get_title());
	set("TRACKNUMBER", track.get_position());
	set("TOTALTRACKS", medium.track_count());

	if (auto medium_count = release.medium_count() > 1) {
		set("DISCNUMBER", medium.get_position());
		set("TOTALDISCS", medium_count);
		set("DISCSUBTITLE", medium.get_title());
	}

	// Album type
	if (Preferences::albumtype) {
		auto type = release.get_release_group()->get_type();
		if (type != ReleaseGroup::types[0]) {
			set(Preferences::albumstatus_data, type);
		} else {
			set(Preferences::albumstatus_data, "");
		}
	}

	// Album status
	if (Preferences::albumstatus) {
		auto status = release.get_status();
		if (status != Release::statuses[0]) {
			set(Preferences::albumstatus_data, status);
		} else {
			set(Preferences::albumstatus_data, "");
		}
	}

	// Artist
	bool va = release.is_various();
	set("ARTIST", track.get_artist_credit()->get_name());
	set("ALBUM ARTIST", va ? release.get_artist_credit()->get_name() : "");

	// MusicBrainz IDs
	if (Preferences::write_ids) {
		set("MUSICBRAINZ_ALBUMID", release.get_id());
		set("MUSICBRAINZ_RELEASEGROUPID", release.get_release_group()->get_id());
		set("MUSICBRAINZ_TRACKID", track.get_id());
		base_class::set("MUSICBRAINZ_ARTISTID", track.get_artist_credit()->get_ids());
		if (va) {
			base_class::set("MUSICBRAINZ_ALBUMARTISTID", release.get_artist_credit()->get_ids());
		} else {
			set("MUSICBRAINZ_ALBUMARTISTID", "");
		}
		// TODO: disc id
		//if (strcmp(medium->get_di->getDiscId(), "") != 0) {
		//	set("MUSICBRAINZ_DISCID", mbc->getDiscId());
		//}
	}

	// Barcode
	set("BARCODE", release.get_barcode());

	// Label info
	TagValues labels, catalog_numbers;
	for (auto i = 0; i < release.label_info_count(); i++) {
		// TODO: possibly remove duplicates?
		if (auto label = release.get_label_info(i)->get_label()->get_name()) {
			labels.add_item(label);
		}
		if (auto catalog_number = release.get_label_info(i)->get_catalog_number()) {
			catalog_numbers.add_item(catalog_number);
		}
	}
	base_class::set("LABEL", labels);
	base_class::set("CATALOGNUMBER", catalog_numbers);
}

void Tag::set(pfc::string8 key, pfc::string8 value) {
	TagValues list;
	list.add_item(value);
	base_class::set(key, list);
}

void Tag::set(pfc::string8 key, const char *value) {
	set(key, pfc::string8(value));
}

void Tag::set(pfc::string8 key, int value) {
	pfc::string8 tmp;
	tmp << value;
	set(key, tmp);
}

FileTagMap::FileTagMap(Release &release, pfc::list_t<metadb_handle_ptr> tracks) {
	auto current_medium = 0;
	auto current_track = 0;
	for (unsigned int i = 0; i < tracks.get_count(); i++) {
		auto &medium = *release.get_medium(current_medium);
		auto &track = *medium.get_track(current_track);

		set(tracks[i], Tag(release, medium, track));

		if (++current_track < medium.track_count()) continue;
		if (++current_medium < release.medium_count()) {
			current_track = 0;
			continue;
		}
		return;
	}
}
<commit_msg>medium_count was always written as 1<commit_after>#include "foo_musicbrainz.h"
#include "FileTagMap.h"
#include "Medium.h"
#include "Release.h"
#include "Track.h"

using namespace foo_musicbrainz;

Tag::Tag(Release &release, Medium &medium, Track &track) {
	set("ALBUM", release.get_title());
	pfc::string8 date = release.get_date();
	if (!date.is_empty()) {
		set("DATE", date);
	}

	set("TITLE", track.get_title());
	set("TRACKNUMBER", track.get_position());
	set("TOTALTRACKS", medium.track_count());

	if (release.medium_count() > 1) {
		set("DISCNUMBER", medium.get_position());
		set("TOTALDISCS", release.medium_count());
		set("DISCSUBTITLE", medium.get_title());
	}

	// Album type
	if (Preferences::albumtype) {
		auto type = release.get_release_group()->get_type();
		if (type != ReleaseGroup::types[0]) {
			set(Preferences::albumstatus_data, type);
		} else {
			set(Preferences::albumstatus_data, "");
		}
	}

	// Album status
	if (Preferences::albumstatus) {
		auto status = release.get_status();
		if (status != Release::statuses[0]) {
			set(Preferences::albumstatus_data, status);
		} else {
			set(Preferences::albumstatus_data, "");
		}
	}

	// Artist
	bool va = release.is_various();
	set("ARTIST", track.get_artist_credit()->get_name());
	set("ALBUM ARTIST", va ? release.get_artist_credit()->get_name() : "");

	// MusicBrainz IDs
	if (Preferences::write_ids) {
		set("MUSICBRAINZ_ALBUMID", release.get_id());
		set("MUSICBRAINZ_RELEASEGROUPID", release.get_release_group()->get_id());
		set("MUSICBRAINZ_TRACKID", track.get_id());
		base_class::set("MUSICBRAINZ_ARTISTID", track.get_artist_credit()->get_ids());
		if (va) {
			base_class::set("MUSICBRAINZ_ALBUMARTISTID", release.get_artist_credit()->get_ids());
		} else {
			set("MUSICBRAINZ_ALBUMARTISTID", "");
		}
		// TODO: disc id
		//if (strcmp(medium->get_di->getDiscId(), "") != 0) {
		//	set("MUSICBRAINZ_DISCID", mbc->getDiscId());
		//}
	}

	// Barcode
	set("BARCODE", release.get_barcode());

	// Label info
	TagValues labels, catalog_numbers;
	for (auto i = 0; i < release.label_info_count(); i++) {
		// TODO: possibly remove duplicates?
		if (auto label = release.get_label_info(i)->get_label()->get_name()) {
			labels.add_item(label);
		}
		if (auto catalog_number = release.get_label_info(i)->get_catalog_number()) {
			catalog_numbers.add_item(catalog_number);
		}
	}
	base_class::set("LABEL", labels);
	base_class::set("CATALOGNUMBER", catalog_numbers);
}

void Tag::set(pfc::string8 key, pfc::string8 value) {
	TagValues list;
	list.add_item(value);
	base_class::set(key, list);
}

void Tag::set(pfc::string8 key, const char *value) {
	set(key, pfc::string8(value));
}

void Tag::set(pfc::string8 key, int value) {
	pfc::string8 tmp;
	tmp << value;
	set(key, tmp);
}

FileTagMap::FileTagMap(Release &release, pfc::list_t<metadb_handle_ptr> tracks) {
	auto current_medium = 0;
	auto current_track = 0;
	for (unsigned int i = 0; i < tracks.get_count(); i++) {
		auto &medium = *release.get_medium(current_medium);
		auto &track = *medium.get_track(current_track);

		set(tracks[i], Tag(release, medium, track));

		if (++current_track < medium.track_count()) continue;
		if (++current_medium < release.medium_count()) {
			current_track = 0;
			continue;
		}
		return;
	}
}
<|endoftext|>


<commit_before>/*
 * Filesystem.cpp
 *
 *  Created on: 14 Oct 2016
 *      Author: muttley
 */

#include "Filesystem.h"

#include <sstream>
#include <fstream>
#include <iostream>
#include <cstdlib>

#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>

#include <cstring>

#include "VDF.h"
#include "Utils.h"
#include "Logger.h"

using namespace std;

namespace Filesystem
{
    std::string FILE_NOT_OPEN = "FILE_NOT_OPEN";
    std::string DIR_NOT_FOUND = "DIR_NOT_FOUND";
    std::string NOT_A_SYMLINK = "NOT_A_SYMLINK";

#ifdef __APPLE__
    std::string LocalSharePrefix = "/Library/Application Support";
    std::string BohemiaInteractivePrefix = "/com.vpltd.Arma3";
    std::string SteamPath = LocalSharePrefix + "/Steam";
    std::string LauncherSettingsDirectory = LocalSharePrefix + "/a3unixlauncher";
#else
    std::string LocalSharePrefix = "/.local/share";
    std::string BohemiaInteractivePrefix = "/bohemiainteractive/arma3";
    std::string SteamPath = "/.steam/steam";
    std::string LauncherSettingsDirectory = "/.config/a3unixlauncher";
#endif
    std::string HomeDirectory = getenv("HOME");

    std::string SteamConfigFile = HomeDirectory + LocalSharePrefix + "/Steam/config/config.vdf";
    std::string SteamConfigFileNeon = HomeDirectory + "/.steam/steam/config/config.vdf";
    std::string SteamAppsArmaPath = "/steamapps/common/Arma 3";
    std::string SteamAppsModWorkshopPath = "/steamapps/workshop/content/107410";

    std::string LauncherSettingsFilename = "/settings.conf";

    std::string ArmaDirWorkshop = "/!workshop";
    std::string ArmaDirCustom = "/!custom";
    std::string ArmaDirDoNotChange = "/!DO_NOT_CHANGE_FILES_IN_THESE_FOLDERS";
    std::string ArmaDirMark = "~arma";

    std::string ArmaConfigFile = HomeDirectory + LocalSharePrefix + BohemiaInteractivePrefix +
                                 "/GameDocuments/Arma 3/Arma3.cfg";

    std::vector<std::string> GetSteamLibraries()
    {
        vector<string> response;
        string steamConfigFile;
        ifstream configFile;

        std::string config_file_path = SteamConfigFile;
        if (!FileExists(config_file_path))
            config_file_path = SteamConfigFileNeon;

        configFile.open(config_file_path, ios::in);
        if (configFile.is_open())
        {
            LOG(0, "File " + SteamConfigFile + " successfully opened...\nReading libraries list...\n");
            getline(configFile, steamConfigFile, '\0');
            VDF vdfReader(steamConfigFile);
            string currentLibraryPath = "";
            int libraryNumber = 1;

            while (true)
            {
                currentLibraryPath = vdfReader.GetValue("InstallConfigStore/Software/Valve/Steam/BaseInstallFolder_" + to_string(
                        libraryNumber++));
                if (currentLibraryPath == KEY_NOT_FOUND)
                    break;
                response.push_back(currentLibraryPath);
            }
        }
        else
            LOG(1, "Can't open " + SteamConfigFile + "\nCritical error\n");

        string home_steam_dir = HomeDirectory + LocalSharePrefix + "/Steam/steamapps/common";
        if (DirectoryExists(home_steam_dir))
            response.push_back(home_steam_dir);
        return response;
    }

    std::string GetDirectory(DirectoryToFind dtf)
    {
        string DirName = "";
        switch (dtf)
        {
            case DirectoryToFind::ArmaInstall:
                DirName = SteamAppsArmaPath;
                break;
            case DirectoryToFind::WorkshopMods:
                DirName = SteamAppsModWorkshopPath;
                break;
            default:
                DirName = SteamAppsModWorkshopPath;
                break;
        }
        DIR *dir = opendir((HomeDirectory + SteamPath + DirName).c_str());
        if (dir)
        {
            closedir(dir);
            return HomeDirectory + SteamPath + DirName;
        }
        for (string s : GetSteamLibraries())
        {
            DIR *dir = opendir((s + DirName).c_str());
            if (dir)
            {
                closedir(dir);
                return s + DirName;
            }
        }
        return DIR_NOT_FOUND;
    }

    bool FileExists(string path)
    {
        struct stat buffer;
        return (stat(path.c_str(), &buffer) == 0);
    }

    bool DirectoryExists(string path)
    {
        struct stat buffer;
        int errorCode = stat(path.c_str(), &buffer);
        if (errorCode == -1)
        {
            if (errno == ENOENT)
                return false;
            LOG(1, "Stat Error in DirectoryExists(" + path + ");");
            return false;
        }
        else
        {
            if (S_ISDIR(buffer.st_mode))
                return true;
            return false;
        }
    }

    bool WriteAllText(string path, string value)
    {
        LOG(0, "Writing to file " + path);
        ofstream outFile(path);
        if (outFile.is_open())
        {
            LOG(0, "File write success");
            outFile << value;
            outFile.close();
            return true;
        }
        LOG(1, "Can't open file " + path + " for write");
        return false;
    }

    string ReadAllText(string path, bool suppress_log)
    {
        if (!suppress_log)
            LOG(0, "Reading file " + path + "... ");
        string response;
        ifstream inFile;
        inFile.open(path, ios::in);
        if (inFile.is_open())
        {
            getline(inFile, response, '\0');
            inFile.close();
            if (!suppress_log)
                LOG(0, "File read successfully");
            return response;
        }
        if (!suppress_log)
            LOG(1, "Can't open file " + path + " for read");
        return FILE_NOT_OPEN;
    }

    vector<Mod> FindMods(string path)
    {
        vector<Mod> response;

        for (string s : GetSubDirectories(path))
        {
            if (s == "Curator" || s == "Dta" || s == "Expansion" || s == "Heli"
                    || s == "Jets" || s == "Kart" || s == "Mark" || s == "Argo"
                    || s == "Orange" || s == "Tacops" || s == "Tank") //skip DLCs
                continue;
            if (Utils::ContainsAddons(path + "/" + s) && Utils::ContainsCppFile(path + "/" + s))
            {
                if (isdigit(s.at(0)))
                    response.push_back(Mod(path + "/" + s, s));
                else
                    response.push_back(Mod(path + "/" + s, "-1"));
            }
        }
        return response;
    }

    void CheckFileStructure(string armaDir, string workshopDir, vector<Mod> modList)
    {
        LOG(0, "Checking file structure");
        string armaDirWorkshopPath = armaDir + Filesystem::ArmaDirWorkshop;
        string armaDirCustomPath = armaDir + Filesystem::ArmaDirCustom;

        LOG(0, "!workshop -> " + armaDirWorkshopPath + "\n!custom -> " + armaDirCustomPath);

        if (!DirectoryExists(armaDirWorkshopPath))
        {
            if (!CreateDirectory(armaDirWorkshopPath))
                return;
        }

        if (!DirectoryExists(armaDirWorkshopPath + Filesystem::ArmaDirDoNotChange))
        {
            if (!CreateDirectory(armaDirWorkshopPath + Filesystem::ArmaDirDoNotChange))
                return;
        }

        if (!DirectoryExists(armaDirCustomPath))
        {
            if (!CreateDirectory(armaDirCustomPath))
                return;
        }

        if (!DirectoryExists(armaDirCustomPath + Filesystem::ArmaDirDoNotChange))
        {
            if (!CreateDirectory(armaDirCustomPath + Filesystem::ArmaDirDoNotChange))
                return;
        }

        vector<string> ModDirs = GetSubDirectories(armaDirWorkshopPath);
        CheckSymlinks(armaDirWorkshopPath, armaDir, workshopDir, &ModDirs, &modList);

        ModDirs = GetSubDirectories(armaDirCustomPath);
        CheckSymlinks(armaDirCustomPath, armaDir, workshopDir, &ModDirs, &modList);

        for (Mod m : modList)
        {
            if (m.Path.find(armaDir) != string::npos)
                continue;
            if (!m.IsRepresentedBySymlink)
            {
                string linkName = armaDirWorkshopPath + "/@" + m.DirName;
                if (m.WorkshopId == "-1")
                    linkName = armaDirCustomPath + "/@" + m.DirName;
                if (!DirectoryExists(linkName) || !FileExists(linkName))
                {
                    int result = symlink(m.Path.c_str(), linkName.c_str());
                    if (result != 0)
                        LOG(1, "Symlink creation failed: " + m.Path + "->" + linkName);
                    else
                        LOG(0, "Symlink creation success: " + m.Path + "->" + linkName);
                }
                else
                    LOG(1, "Dir/file " + linkName + " already exists");
            }
        }
    }

    vector<string> GetSubDirectories(string path)
    {
        vector<string> response;
        struct dirent *directoryEntry;

        DIR *pathDir = opendir(path.c_str());

        if (pathDir == NULL)
        {
            LOG(1, "Opening directory " + path + " failed");
            return response;
        }

        while ((directoryEntry = readdir(pathDir)) != NULL)
        {
            struct stat st;

            if ((strcmp(directoryEntry->d_name, ".") == 0) || (strcmp(directoryEntry->d_name, "..") == 0))
                continue;

            if (fstatat(dirfd(pathDir), directoryEntry->d_name, &st, 0) < 0)
            {
                int error = errno;
                string DirName = directoryEntry->d_name;
                DirName += " strerror: ";
                DirName += strerror(errno);
                LOG(1, "Directory error " + DirName);
                continue;
            }

            if (S_ISDIR(st.st_mode))
                response.push_back(directoryEntry->d_name);
        }

        closedir(pathDir);

        return response;
    }

    bool CreateDirectory(string path)
    {
        int status = mkdir(path.c_str(), S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); //d rwx r-x r-x
        if (status != 0)
        {
            LOG(1, "Can't create directory " + path);
            return false;
        }
        LOG(0, "Successfully created directory " + path);
        return true;
    }

    string GetSymlinkTarget(string path)
    {
        struct stat statinfo;
        if (lstat(path.c_str(), &statinfo) < 0)
        {
            LOG(0, "Can't open directory/symlink " + path);
            return NOT_A_SYMLINK;
        }
        if (S_ISLNK(statinfo.st_mode))
        {
            char *buffer = new char[PATH_MAX + 1];
            size_t pathLength = readlink(path.c_str(), buffer, PATH_MAX);
            buffer[pathLength] = '\0';
            string target = buffer;
            delete[] buffer;
            LOG(0, "!workshop/" + path + " points to: " + target);

            return target;
        }
        return NOT_A_SYMLINK;
    }

    void CheckSymlinks(std::string path, std::string armaDir, std::string workshopDir, vector<string> *ModDirs,
                       vector<Mod> *modList)
    {
        for (int i = 0; i < ModDirs->size(); i++)
        {
            string s = ModDirs->operator [](i);
            string target = GetSymlinkTarget(path + "/" + s);
            if (target != NOT_A_SYMLINK)
            {
                int targetLength = target.length();
                target = Utils::Replace(target, workshopDir + "/", "");

                //outside workshop dir
                if (targetLength == target.length())
                {
                    for (int i = 0; i < modList->size(); i++)
                    {
                        if (modList->operator[](i).Path == target)
                        {
                            modList->operator[](i).IsRepresentedBySymlink = true;
                            break;
                        }
                    }
                }
                else
                {
                    string newWorkshopId = target;
                    for (int i = 0; i < modList->size(); i++)
                    {
                        if (modList->operator[](i).WorkshopId == newWorkshopId)
                        {
                            modList->operator[](i).IsRepresentedBySymlink = true;
                            break;
                        }
                    }
                }
            }
            else
                LOG(1, "Not a symlink found in ModDirs!");
        }
    }

    string GenerateArmaCfg(string armaPath, string source, vector<Mod *> modList)
    {
        LOG(1, "Generating Arma3.cfg");
        string response;
        string inputFile = ReadAllText(source);
        if (inputFile == FILE_NOT_OPEN) {
            inputFile = "";
            std::string command = "mkdir -p $(realpath -m $(dirname \"" + source + "\"))";
            LOG(1, "Cannot read Arma3.cfg, creating directory " + command);
            system(command.c_str());
        }

        string modLauncherList = "class ModLauncherList\n{\n";
        int i;

        for (i = 0; i < modList.size(); i++)
        {
            string fullPath = armaPath;
            string symlinkAt = "@";
            if (modList[i]->WorkshopId == "-1")
            {
                if (fullPath.find(armaPath) == std::string::npos)
                    fullPath += Filesystem::ArmaDirCustom;
                else
                    symlinkAt = "";
            }
            else
                fullPath += Filesystem::ArmaDirWorkshop;
            fullPath += "/" + symlinkAt + modList[i]->DirName;
            string testPath = GetSymlinkTarget(fullPath);
            if (testPath != NOT_A_SYMLINK) {
                fullPath = testPath;
            };
            string dirName = symlinkAt + modList[i]->DirName;

            string disk = "C:";
            if (IsProton(GetDirectory(DirectoryToFind::ArmaInstall)))
                disk = "Z:";
            string windowsPath = disk + Utils::Replace(fullPath, "/", "\\");
            modLauncherList += "\tclass Mod" + to_string(i + 1) + "\n\t{"
                               + "\n\t\tdir=\"" + dirName + "\";"
                               + "\n\t\tname=\"" + modList[i]->Name + "\";"
                               + "\n\t\torigin=\"GAME DIR\";"
                               + "\n\t\tfullPath=\"" + windowsPath + "\";"
                               + "\n\t};\n";
        }

        modLauncherList += "};";

        int leftBracketsOpen = 0;
        bool ignoreAll = false;

        vector<string> lines = Utils::Split(inputFile, "\n");
        for (string s : lines)
        {
            string logMsg = "Line: " + s + "\n";
            if (Utils::Trim(s) == "{")
            {
                leftBracketsOpen++;
                logMsg += "Left brackets opened: " + to_string(leftBracketsOpen);
            }
            else if (Utils::Trim(s) == "};")
            {
                leftBracketsOpen--;
                if (leftBracketsOpen == 0)
                    ignoreAll = false;
                logMsg += "Left brackets opened: " + to_string(leftBracketsOpen)
                          + "\nignoreAll = " + Utils::ToString(ignoreAll);
            }
            else
            {
                if (Utils::Trim(s) == "class ModLauncherList")
                    ignoreAll = true;
                if (!ignoreAll)
                    response += s + "\n";
                logMsg += "\nignoreAll = " + Utils::ToString(ignoreAll);
            }
            LOG(0, logMsg);
        }
        response += modLauncherList + "\n";
        return response;
    }

    bool IsProton(std::string path)
    {
        return Filesystem::FileExists(path + "/arma3launcher.exe");
    }
}
<commit_msg>update symlinks when mod name gets changed<commit_after>/*
 * Filesystem.cpp
 *
 *  Created on: 14 Oct 2016
 *      Author: muttley
 */

#include "Filesystem.h"

#include <sstream>
#include <fstream>
#include <iostream>
#include <cstdlib>

#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>

#include <cstring>

#include "VDF.h"
#include "Utils.h"
#include "Logger.h"

using namespace std;

namespace Filesystem
{
    std::string FILE_NOT_OPEN = "FILE_NOT_OPEN";
    std::string DIR_NOT_FOUND = "DIR_NOT_FOUND";
    std::string NOT_A_SYMLINK = "NOT_A_SYMLINK";

#ifdef __APPLE__
    std::string LocalSharePrefix = "/Library/Application Support";
    std::string BohemiaInteractivePrefix = "/com.vpltd.Arma3";
    std::string SteamPath = LocalSharePrefix + "/Steam";
    std::string LauncherSettingsDirectory = LocalSharePrefix + "/a3unixlauncher";
#else
    std::string LocalSharePrefix = "/.local/share";
    std::string BohemiaInteractivePrefix = "/bohemiainteractive/arma3";
    std::string SteamPath = "/.steam/steam";
    std::string LauncherSettingsDirectory = "/.config/a3unixlauncher";
#endif
    std::string HomeDirectory = getenv("HOME");

    std::string SteamConfigFile = HomeDirectory + LocalSharePrefix + "/Steam/config/config.vdf";
    std::string SteamConfigFileNeon = HomeDirectory + "/.steam/steam/config/config.vdf";
    std::string SteamAppsArmaPath = "/steamapps/common/Arma 3";
    std::string SteamAppsModWorkshopPath = "/steamapps/workshop/content/107410";

    std::string LauncherSettingsFilename = "/settings.conf";

    std::string ArmaDirWorkshop = "/!workshop";
    std::string ArmaDirCustom = "/!custom";
    std::string ArmaDirDoNotChange = "/!DO_NOT_CHANGE_FILES_IN_THESE_FOLDERS";
    std::string ArmaDirMark = "~arma";

    std::string ArmaConfigFile = HomeDirectory + LocalSharePrefix + BohemiaInteractivePrefix +
                                 "/GameDocuments/Arma 3/Arma3.cfg";

    std::vector<std::string> GetSteamLibraries()
    {
        vector<string> response;
        string steamConfigFile;
        ifstream configFile;

        std::string config_file_path = SteamConfigFile;
        if (!FileExists(config_file_path))
            config_file_path = SteamConfigFileNeon;

        configFile.open(config_file_path, ios::in);
        if (configFile.is_open())
        {
            LOG(0, "File " + SteamConfigFile + " successfully opened...\nReading libraries list...\n");
            getline(configFile, steamConfigFile, '\0');
            VDF vdfReader(steamConfigFile);
            string currentLibraryPath = "";
            int libraryNumber = 1;

            while (true)
            {
                currentLibraryPath = vdfReader.GetValue("InstallConfigStore/Software/Valve/Steam/BaseInstallFolder_" + to_string(
                        libraryNumber++));
                if (currentLibraryPath == KEY_NOT_FOUND)
                    break;
                response.push_back(currentLibraryPath);
            }
        }
        else
            LOG(1, "Can't open " + SteamConfigFile + "\nCritical error\n");

        string home_steam_dir = HomeDirectory + LocalSharePrefix + "/Steam/steamapps/common";
        if (DirectoryExists(home_steam_dir))
            response.push_back(home_steam_dir);
        return response;
    }

    std::string GetDirectory(DirectoryToFind dtf)
    {
        string DirName = "";
        switch (dtf)
        {
            case DirectoryToFind::ArmaInstall:
                DirName = SteamAppsArmaPath;
                break;
            case DirectoryToFind::WorkshopMods:
                DirName = SteamAppsModWorkshopPath;
                break;
            default:
                DirName = SteamAppsModWorkshopPath;
                break;
        }
        DIR *dir = opendir((HomeDirectory + SteamPath + DirName).c_str());
        if (dir)
        {
            closedir(dir);
            return HomeDirectory + SteamPath + DirName;
        }
        for (string s : GetSteamLibraries())
        {
            DIR *dir = opendir((s + DirName).c_str());
            if (dir)
            {
                closedir(dir);
                return s + DirName;
            }
        }
        return DIR_NOT_FOUND;
    }

    bool FileExists(string path)
    {
        struct stat buffer;
        return (stat(path.c_str(), &buffer) == 0);
    }

    bool DirectoryExists(string path)
    {
        struct stat buffer;
        int errorCode = stat(path.c_str(), &buffer);
        if (errorCode == -1)
        {
            if (errno == ENOENT)
                return false;
            LOG(1, "Stat Error in DirectoryExists(" + path + ");");
            return false;
        }
        else
        {
            if (S_ISDIR(buffer.st_mode))
                return true;
            return false;
        }
    }

    bool WriteAllText(string path, string value)
    {
        LOG(0, "Writing to file " + path);
        ofstream outFile(path);
        if (outFile.is_open())
        {
            LOG(0, "File write success");
            outFile << value;
            outFile.close();
            return true;
        }
        LOG(1, "Can't open file " + path + " for write");
        return false;
    }

    string ReadAllText(string path, bool suppress_log)
    {
        if (!suppress_log)
            LOG(0, "Reading file " + path + "... ");
        string response;
        ifstream inFile;
        inFile.open(path, ios::in);
        if (inFile.is_open())
        {
            getline(inFile, response, '\0');
            inFile.close();
            if (!suppress_log)
                LOG(0, "File read successfully");
            return response;
        }
        if (!suppress_log)
            LOG(1, "Can't open file " + path + " for read");
        return FILE_NOT_OPEN;
    }

    vector<Mod> FindMods(string path)
    {
        vector<Mod> response;

        for (string s : GetSubDirectories(path))
        {
            if (s == "Curator" || s == "Dta" || s == "Expansion" || s == "Heli"
                    || s == "Jets" || s == "Kart" || s == "Mark" || s == "Argo"
                    || s == "Orange" || s == "Tacops" || s == "Tank") //skip DLCs
                continue;
            if (Utils::ContainsAddons(path + "/" + s) && Utils::ContainsCppFile(path + "/" + s))
            {
                if (isdigit(s.at(0)))
                    response.push_back(Mod(path + "/" + s, s));
                else
                    response.push_back(Mod(path + "/" + s, "-1"));
            }
        }
        return response;
    }

    void CheckFileStructure(string armaDir, string workshopDir, vector<Mod> modList)
    {
        LOG(0, "Checking file structure");
        string armaDirWorkshopPath = armaDir + Filesystem::ArmaDirWorkshop;
        string armaDirCustomPath = armaDir + Filesystem::ArmaDirCustom;

        LOG(0, "!workshop -> " + armaDirWorkshopPath + "\n!custom -> " + armaDirCustomPath);

        if (!DirectoryExists(armaDirWorkshopPath))
        {
            if (!CreateDirectory(armaDirWorkshopPath))
                return;
        }

        if (!DirectoryExists(armaDirWorkshopPath + Filesystem::ArmaDirDoNotChange))
        {
            if (!CreateDirectory(armaDirWorkshopPath + Filesystem::ArmaDirDoNotChange))
                return;
        }

        if (!DirectoryExists(armaDirCustomPath))
        {
            if (!CreateDirectory(armaDirCustomPath))
                return;
        }

        if (!DirectoryExists(armaDirCustomPath + Filesystem::ArmaDirDoNotChange))
        {
            if (!CreateDirectory(armaDirCustomPath + Filesystem::ArmaDirDoNotChange))
                return;
        }

        vector<string> ModDirs = GetSubDirectories(armaDirWorkshopPath);
        CheckSymlinks(armaDirWorkshopPath, armaDir, workshopDir, &ModDirs, &modList);

        ModDirs = GetSubDirectories(armaDirCustomPath);
        CheckSymlinks(armaDirCustomPath, armaDir, workshopDir, &ModDirs, &modList);

        for (Mod m : modList)
        {
            if (m.Path.find(armaDir) != string::npos)
                continue;
            if (!m.IsRepresentedBySymlink)
            {
                string linkName = armaDirWorkshopPath + "/@" + m.DirName;
                if (m.WorkshopId == "-1")
                    linkName = armaDirCustomPath + "/@" + m.DirName;
                if (!DirectoryExists(linkName) || !FileExists(linkName))
                {
                    int result = symlink(m.Path.c_str(), linkName.c_str());
                    if (result != 0)
                        LOG(1, "Symlink creation failed: " + m.Path + "->" + linkName);
                    else
                        LOG(0, "Symlink creation success: " + m.Path + "->" + linkName);
                }
                else
                    LOG(1, "Dir/file " + linkName + " already exists");
            }
        }
    }

    vector<string> GetSubDirectories(string path)
    {
        vector<string> response;
        struct dirent *directoryEntry;

        DIR *pathDir = opendir(path.c_str());

        if (pathDir == NULL)
        {
            LOG(1, "Opening directory " + path + " failed");
            return response;
        }

        while ((directoryEntry = readdir(pathDir)) != NULL)
        {
            struct stat st;

            if ((strcmp(directoryEntry->d_name, ".") == 0) || (strcmp(directoryEntry->d_name, "..") == 0))
                continue;

            if (fstatat(dirfd(pathDir), directoryEntry->d_name, &st, 0) < 0)
            {
                int error = errno;
                string DirName = directoryEntry->d_name;
                DirName += " strerror: ";
                DirName += strerror(errno);
                LOG(1, "Directory error " + DirName);
                continue;
            }

            if (S_ISDIR(st.st_mode))
                response.push_back(directoryEntry->d_name);
        }

        closedir(pathDir);

        return response;
    }

    bool CreateDirectory(string path)
    {
        int status = mkdir(path.c_str(), S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); //d rwx r-x r-x
        if (status != 0)
        {
            LOG(1, "Can't create directory " + path);
            return false;
        }
        LOG(0, "Successfully created directory " + path);
        return true;
    }

    string GetSymlinkTarget(string path)
    {
        struct stat statinfo;
        if (lstat(path.c_str(), &statinfo) < 0)
        {
            LOG(0, "Can't open directory/symlink " + path);
            return NOT_A_SYMLINK;
        }
        if (S_ISLNK(statinfo.st_mode))
        {
            char *buffer = new char[PATH_MAX + 1];
            size_t pathLength = readlink(path.c_str(), buffer, PATH_MAX);
            buffer[pathLength] = '\0';
            string target = buffer;
            delete[] buffer;
            LOG(0, "!workshop/" + path + " points to: " + target);

            return target;
        }
        return NOT_A_SYMLINK;
    }

    void CheckSymlinks(std::string path, std::string armaDir, std::string workshopDir, vector<string> *ModDirs,
                       vector<Mod> *modList)
    {
        for (int i = 0; i < ModDirs->size(); i++)
        {
            string s = ModDirs->operator [](i);
            string target = GetSymlinkTarget(path + "/" + s);
            if (target != NOT_A_SYMLINK)
            {
                int targetLength = target.length();
                target = Utils::Replace(target, workshopDir + "/", "");

                //outside workshop dir
                if (targetLength == target.length())
                {
                    for (int i = 0; i < modList->size(); i++)
                    {
                        if (modList->operator[](i).Path == target)
                        {
                            modList->operator[](i).IsRepresentedBySymlink = true;
                            break;
                        }
                    }
                }
                else
                {
                    string newWorkshopId = target;
                    for (int i = 0; i < modList->size(); i++)
                    {
                        if (modList->operator[](i).WorkshopId == newWorkshopId && s == modList->operator[](i).Name)
                        {
                            modList->operator[](i).IsRepresentedBySymlink = true;
                            break;
                        }
                    }
                }
            }
            else
                LOG(1, "Not a symlink found in ModDirs!");
        }
    }

    string GenerateArmaCfg(string armaPath, string source, vector<Mod *> modList)
    {
        LOG(1, "Generating Arma3.cfg");
        string response;
        string inputFile = ReadAllText(source);
        if (inputFile == FILE_NOT_OPEN) {
            inputFile = "";
            std::string command = "mkdir -p $(realpath -m $(dirname \"" + source + "\"))";
            LOG(1, "Cannot read Arma3.cfg, creating directory " + command);
            system(command.c_str());
        }

        string modLauncherList = "class ModLauncherList\n{\n";
        int i;

        for (i = 0; i < modList.size(); i++)
        {
            string fullPath = armaPath;
            string symlinkAt = "@";
            if (modList[i]->WorkshopId == "-1")
            {
                if (fullPath.find(armaPath) == std::string::npos)
                    fullPath += Filesystem::ArmaDirCustom;
                else
                    symlinkAt = "";
            }
            else
                fullPath += Filesystem::ArmaDirWorkshop;
            fullPath += "/" + symlinkAt + modList[i]->DirName;
            string testPath = GetSymlinkTarget(fullPath);
            if (testPath != NOT_A_SYMLINK) {
                fullPath = testPath;
            };
            string dirName = symlinkAt + modList[i]->DirName;

            string disk = "C:";
            if (IsProton(GetDirectory(DirectoryToFind::ArmaInstall)))
                disk = "Z:";
            string windowsPath = disk + Utils::Replace(fullPath, "/", "\\");
            modLauncherList += "\tclass Mod" + to_string(i + 1) + "\n\t{"
                               + "\n\t\tdir=\"" + dirName + "\";"
                               + "\n\t\tname=\"" + modList[i]->Name + "\";"
                               + "\n\t\torigin=\"GAME DIR\";"
                               + "\n\t\tfullPath=\"" + windowsPath + "\";"
                               + "\n\t};\n";
        }

        modLauncherList += "};";

        int leftBracketsOpen = 0;
        bool ignoreAll = false;

        vector<string> lines = Utils::Split(inputFile, "\n");
        for (string s : lines)
        {
            string logMsg = "Line: " + s + "\n";
            if (Utils::Trim(s) == "{")
            {
                leftBracketsOpen++;
                logMsg += "Left brackets opened: " + to_string(leftBracketsOpen);
            }
            else if (Utils::Trim(s) == "};")
            {
                leftBracketsOpen--;
                if (leftBracketsOpen == 0)
                    ignoreAll = false;
                logMsg += "Left brackets opened: " + to_string(leftBracketsOpen)
                          + "\nignoreAll = " + Utils::ToString(ignoreAll);
            }
            else
            {
                if (Utils::Trim(s) == "class ModLauncherList")
                    ignoreAll = true;
                if (!ignoreAll)
                    response += s + "\n";
                logMsg += "\nignoreAll = " + Utils::ToString(ignoreAll);
            }
            LOG(0, logMsg);
        }
        response += modLauncherList + "\n";
        return response;
    }

    bool IsProton(std::string path)
    {
        return Filesystem::FileExists(path + "/arma3launcher.exe");
    }
}
<|endoftext|>


<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "InteriorsEntityIdHighlightVisibilityController.h"
#include "ISearchService.h"
#include "ISearchQueryPerformer.h"
#include "ISearchResultRepository.h"
#include "InteriorController.h"
#include "InteriorsModel.h"
#include "InteriorsFloorModel.h"
#include "IInteriorsLabelController.h"
#include "VectorMath.h"
#include "InteriorHighlightRenderable.h"
#include "InteriorsLabelParser.h"
#include "InteriorsFloorCells.h"
#include "InteriorsFloorCell.h"
#include "PlaceNameModel.h"
#include "InstancedInteriorFloorRenderable.h"
#include "InteriorsCellResource.h"
#include "SearchResultSectionItemSelectedMessage.h"
#include "InteriorsEntityIdHighlightController.h"
#include "document.h"

#include <algorithm>
#include <iterator>

namespace ExampleApp
{
    namespace InteriorsExplorer
    {
        namespace SdkModel
        {
            namespace Highlights
            {
                namespace
                {
                    std::vector<std::string> GetEntityIdsFromSearchResultModel(const Search::SdkModel::SearchResultModel& selectedSearchResult)
                    {
                        rapidjson::Document json;
                        std::string highlightedEntityId = "";

                        if (!json.Parse<0>(selectedSearchResult.GetJsonData().c_str()).HasParseError() && json.HasMember("entity_highlight"))
                        {
                            std::vector<std::string> entities;
                            const rapidjson::Value& entity_highlight = json["entity_highlight"];
                            assert(entity_highlight.IsArray());

                            for (int i  = 0; i < entity_highlight.Size(); i++)
                            {
                                entities.push_back(entity_highlight[i].GetString());
                            }
                            return entities;
                        }
                        return std::vector<std::string>();
                    }

                    struct IsInteriorInstancePresentForId
                    {
                        typedef const std::string& argument_type;

                        IsInteriorInstancePresentForId(const Eegeo::Resources::Interiors::InteriorsInstanceRepository& interiorsInstanceRepository)
                        : m_interiorsInstanceRepository(interiorsInstanceRepository)
                        {}

                        bool operator()(argument_type id) const
                        {
                            return m_interiorsInstanceRepository.Contains(id);
                        }
                    private:
                        const Eegeo::Resources::Interiors::InteriorsInstanceRepository& m_interiorsInstanceRepository;
                    };
                }

                InteriorsEntityIdHighlightVisibilityController::InteriorsEntityIdHighlightVisibilityController(
                    Eegeo::Resources::Interiors::InteriorsEntityIdHighlightController& interiorsEntityIdHighlightController,
                    Search::SdkModel::ISearchQueryPerformer& searchQueryPerformer,
                    Search::SdkModel::ISearchResultRepository& searchResultRepository,
                    ExampleAppMessaging::TMessageBus& messageBus,
                    Eegeo::Resources::Interiors::InteriorsInstanceRepository& interiorsInstanceRepository,
                    IHighlightColorMapper& highlightColorMapper)
                : m_interiorsEntityIdHighlightController(interiorsEntityIdHighlightController)
                , m_searchQueryPerformer(searchQueryPerformer)
                , m_searchResultsHandler(this, &InteriorsEntityIdHighlightVisibilityController::OnSearchResultsLoaded)
                , m_searchResultsClearedHandler(this, &InteriorsEntityIdHighlightVisibilityController::OnSearchResultsCleared)
                , m_handleSearchResultSectionItemSelectedMessageBinding(this, &InteriorsEntityIdHighlightVisibilityController::OnSearchItemSelected)
                , m_messageBus(messageBus)
                , m_interiorsInstanceRepository(interiorsInstanceRepository)
                , m_interiorsInstanceRepositoryChangedHandler(this, &InteriorsEntityIdHighlightVisibilityController::OnInteriorsInstanceRepositoryChanged)
                , m_searchResultsIndex(-1)
                , m_highlightColorMapper(highlightColorMapper)
                {
                    m_searchQueryPerformer.InsertOnSearchResultsClearedCallback(m_searchResultsClearedHandler);
                    m_messageBus.SubscribeNative(m_handleSearchResultSectionItemSelectedMessageBinding);
                    m_messageBus.SubscribeUi(m_searchResultsHandler);

                    m_interiorsInstanceRepository.RegisterChangedCallback(m_interiorsInstanceRepositoryChangedHandler);
                }

                InteriorsEntityIdHighlightVisibilityController::~InteriorsEntityIdHighlightVisibilityController()
                {
                    m_searchQueryPerformer.RemoveOnSearchResultsClearedCallback(m_searchResultsClearedHandler);
                    m_messageBus.UnsubscribeNative(m_handleSearchResultSectionItemSelectedMessageBinding);
                    m_messageBus.UnsubscribeUi(m_searchResultsHandler);

                    m_interiorsInstanceRepository.UnregisterChangedCallback(m_interiorsInstanceRepositoryChangedHandler);
                }

                void InteriorsEntityIdHighlightVisibilityController::OnSearchResultsCleared()
                {
                    m_searchResultsIndex = -1;
                    m_searchResults.clear();
                    ClearHighlights();
                }

                void InteriorsEntityIdHighlightVisibilityController::ClearHighlights()
                {
                    for (InstancedRenderableVector::const_iterator iter = m_lastHighlightedRenderables.begin(); iter != m_lastHighlightedRenderables.end(); ++iter)
                    {
                        Eegeo::Rendering::Renderables::InstancedInteriorFloorRenderable& currentRenderable = **iter;
                        Eegeo::Rendering::Renderables::InstancedRenderState currentState = currentRenderable.GetInstancedRenderState();

                        currentState.IsHighlightingActive = false;

                        currentRenderable.SetInstancedRenderState(currentState);
                    }

                    m_lastHighlightedRenderables.clear();
                }

                void InteriorsEntityIdHighlightVisibilityController::OnSearchItemSelected(const SearchResultSection::SearchResultSectionItemSelectedMessage& message)
                {
                    if (message.ItemIndex() >= m_searchResults.size())
                    {
                        m_searchResultsIndex = -1;
                    }
                    else
                    {
                        m_searchResultsIndex = message.ItemIndex();
                    }

                    RefreshHighlights();
                }

                void InteriorsEntityIdHighlightVisibilityController::OnInteriorsInstanceRepositoryChanged()
                {
                    RefreshHighlights();
                }

                void InteriorsEntityIdHighlightVisibilityController::OnSearchResultsLoaded(const Search::SearchQueryResponseReceivedMessage& message)
                {
                    if (m_searchResultsIndex >= 0)
                    {
                        const Search::SdkModel::SearchResultModel& selectedSearchResult = m_searchResults.at(m_searchResultsIndex);

                        const std::vector<Search::SdkModel::SearchResultModel>& newSearchResults = message.GetResults();

                        std::vector<Search::SdkModel::SearchResultModel>::const_iterator iter = std::find(newSearchResults.begin(), newSearchResults.end(), selectedSearchResult);
                        if (iter == newSearchResults.end())
                        {
                            m_searchResultsIndex = -1;
                        }
                        else
                        {
                            m_searchResultsIndex = static_cast<int>(std::distance(newSearchResults.begin(), iter));
                        }
                    }

                    m_searchResults = message.GetResults();

                    RefreshHighlights();
                }

                void InteriorsEntityIdHighlightVisibilityController::RefreshHighlights()
                {
                    ClearHighlights();

                    if (m_searchResultsIndex >= 0)
                    {
                        const Search::SdkModel::SearchResultModel& selectedSearchResult = m_searchResults.at(m_searchResultsIndex);

                        std::vector<std::string> filteredEntityIds = GetEntityIdsFromSearchResultModel(selectedSearchResult);

                        filteredEntityIds.erase(std::remove_if(filteredEntityIds.begin(), filteredEntityIds.end(), std::not1(IsInteriorInstancePresentForId(m_interiorsInstanceRepository))), filteredEntityIds.end());

                        m_interiorsEntityIdHighlightController.SetDefaultHighlightColour(m_highlightColorMapper.GetColor(selectedSearchResult, "entity_highlight_color"));
                        m_interiorsEntityIdHighlightController.HighlightEntityIds(filteredEntityIds, m_lastHighlightedRenderables);
                    }
                }
            }
        }
    }
}
<commit_msg>MPLY-8784 Updated clear highlights method to work with new functionality to allow multiple highlights. Buddy Michael Chan<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "InteriorsEntityIdHighlightVisibilityController.h"
#include "ISearchService.h"
#include "ISearchQueryPerformer.h"
#include "ISearchResultRepository.h"
#include "InteriorController.h"
#include "InteriorsModel.h"
#include "InteriorsFloorModel.h"
#include "IInteriorsLabelController.h"
#include "VectorMath.h"
#include "InteriorHighlightRenderable.h"
#include "InteriorsLabelParser.h"
#include "InteriorsFloorCells.h"
#include "InteriorsFloorCell.h"
#include "PlaceNameModel.h"
#include "InstancedInteriorFloorRenderable.h"
#include "InteriorsCellResource.h"
#include "SearchResultSectionItemSelectedMessage.h"
#include "InteriorsEntityIdHighlightController.h"
#include "document.h"

#include <algorithm>
#include <iterator>

namespace ExampleApp
{
    namespace InteriorsExplorer
    {
        namespace SdkModel
        {
            namespace Highlights
            {
                namespace
                {
                    std::vector<std::string> GetEntityIdsFromSearchResultModel(const Search::SdkModel::SearchResultModel& selectedSearchResult)
                    {
                        rapidjson::Document json;
                        std::string highlightedEntityId = "";

                        if (!json.Parse<0>(selectedSearchResult.GetJsonData().c_str()).HasParseError() && json.HasMember("entity_highlight"))
                        {
                            std::vector<std::string> entities;
                            const rapidjson::Value& entity_highlight = json["entity_highlight"];
                            assert(entity_highlight.IsArray());

                            for (int i  = 0; i < entity_highlight.Size(); i++)
                            {
                                entities.push_back(entity_highlight[i].GetString());
                            }
                            return entities;
                        }
                        return std::vector<std::string>();
                    }

                    struct IsInteriorInstancePresentForId
                    {
                        typedef const std::string& argument_type;

                        IsInteriorInstancePresentForId(const Eegeo::Resources::Interiors::InteriorsInstanceRepository& interiorsInstanceRepository)
                        : m_interiorsInstanceRepository(interiorsInstanceRepository)
                        {}

                        bool operator()(argument_type id) const
                        {
                            return m_interiorsInstanceRepository.Contains(id);
                        }
                    private:
                        const Eegeo::Resources::Interiors::InteriorsInstanceRepository& m_interiorsInstanceRepository;
                    };
                }

                InteriorsEntityIdHighlightVisibilityController::InteriorsEntityIdHighlightVisibilityController(
                    Eegeo::Resources::Interiors::InteriorsEntityIdHighlightController& interiorsEntityIdHighlightController,
                    Search::SdkModel::ISearchQueryPerformer& searchQueryPerformer,
                    Search::SdkModel::ISearchResultRepository& searchResultRepository,
                    ExampleAppMessaging::TMessageBus& messageBus,
                    Eegeo::Resources::Interiors::InteriorsInstanceRepository& interiorsInstanceRepository,
                    IHighlightColorMapper& highlightColorMapper)
                : m_interiorsEntityIdHighlightController(interiorsEntityIdHighlightController)
                , m_searchQueryPerformer(searchQueryPerformer)
                , m_searchResultsHandler(this, &InteriorsEntityIdHighlightVisibilityController::OnSearchResultsLoaded)
                , m_searchResultsClearedHandler(this, &InteriorsEntityIdHighlightVisibilityController::OnSearchResultsCleared)
                , m_handleSearchResultSectionItemSelectedMessageBinding(this, &InteriorsEntityIdHighlightVisibilityController::OnSearchItemSelected)
                , m_messageBus(messageBus)
                , m_interiorsInstanceRepository(interiorsInstanceRepository)
                , m_interiorsInstanceRepositoryChangedHandler(this, &InteriorsEntityIdHighlightVisibilityController::OnInteriorsInstanceRepositoryChanged)
                , m_searchResultsIndex(-1)
                , m_highlightColorMapper(highlightColorMapper)
                {
                    m_searchQueryPerformer.InsertOnSearchResultsClearedCallback(m_searchResultsClearedHandler);
                    m_messageBus.SubscribeNative(m_handleSearchResultSectionItemSelectedMessageBinding);
                    m_messageBus.SubscribeUi(m_searchResultsHandler);

                    m_interiorsInstanceRepository.RegisterChangedCallback(m_interiorsInstanceRepositoryChangedHandler);
                }

                InteriorsEntityIdHighlightVisibilityController::~InteriorsEntityIdHighlightVisibilityController()
                {
                    m_searchQueryPerformer.RemoveOnSearchResultsClearedCallback(m_searchResultsClearedHandler);
                    m_messageBus.UnsubscribeNative(m_handleSearchResultSectionItemSelectedMessageBinding);
                    m_messageBus.UnsubscribeUi(m_searchResultsHandler);

                    m_interiorsInstanceRepository.UnregisterChangedCallback(m_interiorsInstanceRepositoryChangedHandler);
                }

                void InteriorsEntityIdHighlightVisibilityController::OnSearchResultsCleared()
                {
                    m_searchResultsIndex = -1;
                    m_searchResults.clear();
                    ClearHighlights();
                }

                void InteriorsEntityIdHighlightVisibilityController::ClearHighlights()
                {
                    m_interiorsEntityIdHighlightController.ClearHighlights(m_lastHighlightedRenderables);
                    m_lastHighlightedRenderables.clear();
                }

                void InteriorsEntityIdHighlightVisibilityController::OnSearchItemSelected(const SearchResultSection::SearchResultSectionItemSelectedMessage& message)
                {
                    if (message.ItemIndex() >= m_searchResults.size())
                    {
                        m_searchResultsIndex = -1;
                    }
                    else
                    {
                        m_searchResultsIndex = message.ItemIndex();
                    }

                    RefreshHighlights();
                }

                void InteriorsEntityIdHighlightVisibilityController::OnInteriorsInstanceRepositoryChanged()
                {
                    RefreshHighlights();
                }

                void InteriorsEntityIdHighlightVisibilityController::OnSearchResultsLoaded(const Search::SearchQueryResponseReceivedMessage& message)
                {
                    if (m_searchResultsIndex >= 0)
                    {
                        const Search::SdkModel::SearchResultModel& selectedSearchResult = m_searchResults.at(m_searchResultsIndex);

                        const std::vector<Search::SdkModel::SearchResultModel>& newSearchResults = message.GetResults();

                        std::vector<Search::SdkModel::SearchResultModel>::const_iterator iter = std::find(newSearchResults.begin(), newSearchResults.end(), selectedSearchResult);
                        if (iter == newSearchResults.end())
                        {
                            m_searchResultsIndex = -1;
                        }
                        else
                        {
                            m_searchResultsIndex = static_cast<int>(std::distance(newSearchResults.begin(), iter));
                        }
                    }

                    m_searchResults = message.GetResults();

                    RefreshHighlights();
                }

                void InteriorsEntityIdHighlightVisibilityController::RefreshHighlights()
                {
                    ClearHighlights();

                    if (m_searchResultsIndex >= 0)
                    {
                        const Search::SdkModel::SearchResultModel& selectedSearchResult = m_searchResults.at(m_searchResultsIndex);

                        std::vector<std::string> filteredEntityIds = GetEntityIdsFromSearchResultModel(selectedSearchResult);

                        filteredEntityIds.erase(std::remove_if(filteredEntityIds.begin(), filteredEntityIds.end(), std::not1(IsInteriorInstancePresentForId(m_interiorsInstanceRepository))), filteredEntityIds.end());

                        m_interiorsEntityIdHighlightController.SetDefaultHighlightColour(m_highlightColorMapper.GetColor(selectedSearchResult, "entity_highlight_color"));
                        m_interiorsEntityIdHighlightController.HighlightEntityIds(filteredEntityIds, m_lastHighlightedRenderables);
                    }
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow_lite_support/examples/task/audio/desktop/audio_classifier_lib.h"

#include <iostream>
#include <string>
#include <vector>

#include "absl/status/status.h"  // from @com_google_absl
#include "absl/strings/str_format.h"  // from @com_google_absl
#include "tensorflow_lite_support/cc/port/status_macros.h"
#include "tensorflow_lite_support/cc/port/statusor.h"
#include "tensorflow_lite_support/cc/task/audio/audio_classifier.h"
#include "tensorflow_lite_support/cc/task/audio/core/audio_buffer.h"
#include "tensorflow_lite_support/cc/task/audio/proto/classifications_proto_inc.h"
#include "tensorflow_lite_support/cc/task/audio/utils/wav_io.h"
#include "tensorflow_lite_support/cc/task/core/category.h"

namespace tflite {
namespace task {
namespace audio {

tflite::support::StatusOr<AudioBuffer> LoadAudioBufferFromFile(
    const std::string& wav_file, int buffer_size,
    std::vector<float>* wav_data) {
  std::string contents = ReadFile(wav_file);

  uint32 decoded_sample_count;
  uint16 decoded_channel_count;
  uint32 decoded_sample_rate;

  decoded_sample_count = buffer_size;

  RETURN_IF_ERROR(DecodeLin16WaveAsFloatVector(
      contents, wav_data, &decoded_sample_count, &decoded_channel_count,
      &decoded_sample_rate));

  return AudioBuffer(
      wav_data->data(), decoded_sample_count,
      {decoded_channel_count, static_cast<int>(decoded_sample_rate)});
}

tflite::support::StatusOr<ClassificationResult> Classify(
    const std::string& model_path, const std::string& wav_file,
    bool use_coral) {
  AudioClassifierOptions options;
  options.mutable_base_options()->mutable_model_file()->set_file_name(
      model_path);
  if (use_coral) {
    options.mutable_base_options()
        ->mutable_compute_settings()
        ->mutable_tflite_settings()
        ->set_delegate(::tflite::proto::Delegate::EDGETPU_CORAL);
  }
  ASSIGN_OR_RETURN(std::unique_ptr<AudioClassifier> classifier,
                   AudioClassifier::CreateFromOptions(options));

  // `wav_data` holds data loaded from the file and needs to outlive `buffer`.
  std::vector<float> wav_data;
  ASSIGN_OR_RETURN(
      AudioBuffer buffer,
      LoadAudioBufferFromFile(
          wav_file, classifier->GetRequiredInputBufferSize(), &wav_data));

  auto start_classify = std::chrono::steady_clock::now();
  ASSIGN_OR_RETURN(ClassificationResult result, classifier->Classify(buffer));
  auto end_classify = std::chrono::steady_clock::now();
  std::string delegate = use_coral ? "Coral Edge TPU" : "CPU";
  const auto duration_ms =
      std::chrono::duration<float, std::milli>(end_classify - start_classify);
  std::cout << "Time cost to classify the input audio clip on " << delegate
            << ": " << duration_ms.count() << " ms" << std::endl;

  return result;
}

void Display(const ClassificationResult& result, float score_threshold) {
  std::cout << "Note: Only showing classes with score higher than "
            << score_threshold << std::endl;

  for (int i = 0; i < result.classifications_size(); i++) {
    const auto& head = result.classifications(i);
    std::cout << absl::StrFormat("\nHead[%d]: %s\n", i, head.head_name());
    for (int j = 0; j < head.classes_size(); j++) {
      const auto& category = head.classes(j);
      if (category.score() < score_threshold) continue;
      std::cout << absl::StrFormat("\tcategory[%s]: %.5f\t",
                                   category.class_name(), category.score());
      if (!category.display_name().empty()) {
        std::cout << category.display_name();
      }
      std::cout << std::endl;
    }
  }
}

}  // namespace audio
}  // namespace task
}  // namespace tflite
<commit_msg>Undo changes to audio classifier lib cc<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow_lite_support/examples/task/audio/desktop/audio_classifier_lib.h"

#include <iostream>
#include <string>
#include <vector>

#include "absl/status/status.h"  // from @com_google_absl
#include "absl/strings/str_format.h"  // from @com_google_absl
#include "tensorflow_lite_support/cc/port/status_macros.h"
#include "tensorflow_lite_support/cc/port/statusor.h"
#include "tensorflow_lite_support/cc/task/audio/audio_classifier.h"
#include "tensorflow_lite_support/cc/task/audio/core/audio_buffer.h"
#include "tensorflow_lite_support/cc/task/audio/proto/classifications_proto_inc.h"
#include "tensorflow_lite_support/cc/task/audio/utils/wav_io.h"
#include "tensorflow_lite_support/cc/task/core/category.h"

namespace tflite {
namespace task {
namespace audio {

tflite::support::StatusOr<AudioBuffer> LoadAudioBufferFromFile(
    const std::string& wav_file, int buffer_size,
    std::vector<float>* wav_data) {
  std::string contents = ReadFile(wav_file);

  uint32 decoded_sample_count;
  uint16 decoded_channel_count;
  uint32 decoded_sample_rate;
  RETURN_IF_ERROR(DecodeLin16WaveAsFloatVector(
      contents, wav_data, &decoded_sample_count, &decoded_channel_count,
      &decoded_sample_rate));

  if (decoded_sample_count > buffer_size) {
      decoded_sample_count = buffer_size;
  }

  return AudioBuffer(
      wav_data->data(), decoded_sample_count,
      {decoded_channel_count, static_cast<int>(decoded_sample_rate)});
}

tflite::support::StatusOr<ClassificationResult> Classify(
    const std::string& model_path, const std::string& wav_file,
    bool use_coral) {
  AudioClassifierOptions options;
  options.mutable_base_options()->mutable_model_file()->set_file_name(
      model_path);
  if (use_coral) {
    options.mutable_base_options()
        ->mutable_compute_settings()
        ->mutable_tflite_settings()
        ->set_delegate(::tflite::proto::Delegate::EDGETPU_CORAL);
  }
  ASSIGN_OR_RETURN(std::unique_ptr<AudioClassifier> classifier,
                   AudioClassifier::CreateFromOptions(options));

  // `wav_data` holds data loaded from the file and needs to outlive `buffer`.
  std::vector<float> wav_data;
  ASSIGN_OR_RETURN(
      AudioBuffer buffer,
      LoadAudioBufferFromFile(
          wav_file, classifier->GetRequiredInputBufferSize(), &wav_data));

  auto start_classify = std::chrono::steady_clock::now();
  ASSIGN_OR_RETURN(ClassificationResult result, classifier->Classify(buffer));
  auto end_classify = std::chrono::steady_clock::now();
  std::string delegate = use_coral ? "Coral Edge TPU" : "CPU";
  const auto duration_ms =
      std::chrono::duration<float, std::milli>(end_classify - start_classify);
  std::cout << "Time cost to classify the input audio clip on " << delegate
            << ": " << duration_ms.count() << " ms" << std::endl;

  return result;
}

void Display(const ClassificationResult& result, float score_threshold) {
  std::cout << "Note: Only showing classes with score higher than "
            << score_threshold << std::endl;

  for (int i = 0; i < result.classifications_size(); i++) {
    const auto& head = result.classifications(i);
    std::cout << absl::StrFormat("\nHead[%d]: %s\n", i, head.head_name());
    for (int j = 0; j < head.classes_size(); j++) {
      const auto& category = head.classes(j);
      if (category.score() < score_threshold) continue;
      std::cout << absl::StrFormat("\tcategory[%s]: %.5f\t",
                                   category.class_name(), category.score());
      if (!category.display_name().empty()) {
        std::cout << category.display_name();
      }
      std::cout << std::endl;
    }
  }
}

}  // namespace audio
}  // namespace task
}  // namespace tflite
<|endoftext|>


<commit_before>class Graphl : public Graph
{
    private:
        List<Edge>** vertex; // List headers
        int numVertex, numEdge; // Number of vertices, edges
        int *mark; // Pointer to mark array

    public:
        Graphl(int numVert)
        {
            Init(numVert);
        }

        ˜Graphl()
        {
            // Destructor
            delete [] mark; // Return dynamically allocated memory
            for (int i=0; i<numVertex; i++)
                delete [] vertex[i];
            delete [] vertex;
        }

        void Init(int n)
        {
            int i;
            numVertex = n;
            numEdge = 0;
            mark = new int[n]; // Initialize mark array
            for (i=0; i<numVertex; i++)
                mark[i] = UNVISITED;

            // Create and initialize adjacency lists
            vertex = (List<Edge>**) new List<Edge>*[numVertex];
            for (i=0; i<numVertex; i++)
                vertex[i] = new LList<Edge>();
        }

        int n() // Number of vertices
        {
            return numVertex;
        }

        int e() // Number of edges
        {
            return numEdge;
        }

        int first(int v)
        {
            // Return first neighbor of "v"
            if (vertex[v]->length() == 0)
                return numVertex; // No neighbor
            vertex[v]->moveToStart();
            Edge it = vertex[v]->getValue();
            return it.vertex();
        }

        // Get v’s next neighbor after w
        int next(int v, int w)
        {
            Edge it;
            if (isEdge(v, w))
            {
                if ((vertex[v]->currPos()+1) < vertex[v]->length())
                {
                    vertex[v]->next();
                    it = vertex[v]->getValue();
                    return it.vertex();
                }
            }
            return n(); // No neighbor
        }

        // Set edge (i, j) to "weight"
        void setEdge(int i, int j, int weight)
        {
            Assert(weight>0, "May not set weight to 0");
            Edge currEdge(j, weight);
            if (isEdge(i, j))
            {
                // Edge already exists in graph
                vertex[i]->remove();
                vertex[i]->insert(currEdge);
            }
            else
            {
                // Keep neighbors sorted by vertex index
                numEdge++;
                for (vertex[i]->moveToStart(); vertex[i]->currPos() < vertex[i]->length();vertex[i]->next())
                {
                    Edge temp = vertex[i]->getValue();
                    if (temp.vertex() > j)
                        break;
                }
                vertex[i]->insert(currEdge);
            }
        }

        void delEdge(int i, int j)
        {
            // Delete edge (i, j)
            if (isEdge(i,j))
            {
                vertex[i]->remove();
                numEdge--;
            }
        }

        bool isEdge(int i, int j)
        {
            // Is (i,j) an edge?
            Edge it;
            for (vertex[i]->moveToStart(); vertex[i]->currPos() < vertex[i]->length(); vertex[i]->next())
            {
                // Check whole list
                Edge temp = vertex[i]->getValue();
                if (temp.vertex() == j)
                    return true;
            }
            return false;
        }
        int weight(int i, int j)
        {
            // Return weight of (i, j)
            Edge curr;
            if (isEdge(i, j))
            {
                curr = vertex[i]->getValue();
                return curr.weight();
            }
            else return 0;
        }

        int getMark(int v)
        {
        return mark[v];
        }

        void setMark(int v, int val)
        {
            mark[v] = val;
        }
};
<commit_msg>Implementation for the adjacency list representation<commit_after>// Implementation for the adjacency list representation
class Graphl : public Graph
{
    private:
        List<Edge>** vertex; // List headers
        int numVertex, numEdge; // Number of vertices, edges
        int *mark; // Pointer to mark array

    public:
        Graphl(int numVert)
        {
            Init(numVert);
        }

        ˜Graphl()
        {
            // Destructor
            delete [] mark; // Return dynamically allocated memory
            for (int i=0; i<numVertex; i++)
                delete [] vertex[i];
            delete [] vertex;
        }

        void Init(int n)
        {
            int i;
            numVertex = n;
            numEdge = 0;
            mark = new int[n]; // Initialize mark array
            for (i=0; i<numVertex; i++)
                mark[i] = UNVISITED;

            // Create and initialize adjacency lists
            vertex = (List<Edge>**) new List<Edge>*[numVertex];
            for (i=0; i<numVertex; i++)
                vertex[i] = new LList<Edge>();
        }

        int n() // Number of vertices
        {
            return numVertex;
        }

        int e() // Number of edges
        {
            return numEdge;
        }

        int first(int v)
        {
            // Return first neighbor of "v"
            if (vertex[v]->length() == 0)
                return numVertex; // No neighbor
            vertex[v]->moveToStart();
            Edge it = vertex[v]->getValue();
            return it.vertex();
        }

        // Get v’s next neighbor after w
        int next(int v, int w)
        {
            Edge it;
            if (isEdge(v, w))
            {
                if ((vertex[v]->currPos()+1) < vertex[v]->length())
                {
                    vertex[v]->next();
                    it = vertex[v]->getValue();
                    return it.vertex();
                }
            }
            return n(); // No neighbor
        }

        // Set edge (i, j) to "weight"
        void setEdge(int i, int j, int weight)
        {
            Assert(weight>0, "May not set weight to 0");
            Edge currEdge(j, weight);
            if (isEdge(i, j))
            {
                // Edge already exists in graph
                vertex[i]->remove();
                vertex[i]->insert(currEdge);
            }
            else
            {
                // Keep neighbors sorted by vertex index
                numEdge++;
                for (vertex[i]->moveToStart(); vertex[i]->currPos() < vertex[i]->length();vertex[i]->next())
                {
                    Edge temp = vertex[i]->getValue();
                    if (temp.vertex() > j)
                        break;
                }
                vertex[i]->insert(currEdge);
            }
        }

        void delEdge(int i, int j)
        {
            // Delete edge (i, j)
            if (isEdge(i,j))
            {
                vertex[i]->remove();
                numEdge--;
            }
        }

        bool isEdge(int i, int j)
        {
            // Is (i,j) an edge?
            Edge it;
            for (vertex[i]->moveToStart(); vertex[i]->currPos() < vertex[i]->length(); vertex[i]->next())
            {
                // Check whole list
                Edge temp = vertex[i]->getValue();
                if (temp.vertex() == j)
                    return true;
            }
            return false;
        }
        int weight(int i, int j)
        {
            // Return weight of (i, j)
            Edge curr;
            if (isEdge(i, j))
            {
                curr = vertex[i]->getValue();
                return curr.weight();
            }
            else return 0;
        }

        int getMark(int v)
        {
        return mark[v];
        }

        void setMark(int v, int val)
        {
            mark[v] = val;
        }
};
<|endoftext|>


<commit_before>#include "HMDWrapper.h"
#include "interface\DeviceMgrInterface.h"

using namespace MathLib;

class CLocalHMDWrapper : public CHMDWrapper
{
public:

	CLocalHMDWrapper();
	virtual ~CLocalHMDWrapper();
	virtual void                Init();
	virtual void                Update();
	virtual void                Shutdown();
	virtual void                SetUseHMD(int u);
	virtual int                 GetUseHMD() const;
	virtual const MathLib::vec3 &GetLocalDirection() const;
	virtual const MathLib::vec3 &GetLocalUp() const;

}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "HMDWrapper.h"
#include "interface\DeviceMgrInterface.h"

using namespace MathLib;

class CLocalHMDWrapper : public CHMDWrapper
{
public:

	CLocalHMDWrapper();
	virtual ~CLocalHMDWrapper();
	virtual void                Init();
	virtual void                Update();
	virtual void                Shutdown();
	virtual void                SetUseHMD(int u);
	virtual int                 GetUseHMD() const;
	virtual const MathLib::vec3 &GetLocalDirection() const;
	virtual const MathLib::vec3 &GetLocalUp() const;
private:

	int     m_nUseHMD;
	int     m_nHaveHMD;
	vec3    m_vLocalDirection;
	vec3    m_vLocalUp;

};<|endoftext|>