<commit_before>// ToolbarHandler for fluxbox
// Copyright (c) 2003 Simon Bowden (rathnor at fluxbox.org)
//                and Henrik Kinnunen (fluxgen at fluxbox.org)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

// $Id: ToolbarHandler.cc,v 1.21 2003/07/04 14:06:20 rathnor Exp $

/**
 * The ToolbarHandler class acts as a rough interface to the toolbar.
 * It deals with whether it should be there or not, so anything that
 * always needs to be accessible must come through the handler.
 */

#include "ToolbarHandler.hh"
#include "Window.hh"
#include "Screen.hh"
#include "Workspace.hh"
#include "MenuItem.hh"
#include "Menu.hh"
#include "FbCommands.hh"
#include "RefCount.hh"
#include "SimpleCommand.hh"
#include "MacroCommand.hh"
#include "IntResMenuItem.hh"
#include "BoolMenuItem.hh"

#include <string>

using namespace std;

template<>
void FbTk::Resource<ToolbarHandler::ToolbarMode>::
setFromString(const char *strval) {
    if (strcasecmp(strval, "Off") == 0)
        m_value = ToolbarHandler::OFF;
    else if (strcasecmp(strval, "None") == 0)
        m_value = ToolbarHandler::NONE;
    else if (strcasecmp(strval, "Icons") == 0)
        m_value = ToolbarHandler::ICONS;
    else if (strcasecmp(strval, "WorkspaceIcons") == 0)
        m_value = ToolbarHandler::WORKSPACEICONS;
    else if (strcasecmp(strval, "Workspace") == 0)
        m_value = ToolbarHandler::WORKSPACE;
    else if (strcasecmp(strval, "AllWindows") == 0)
        m_value = ToolbarHandler::ALLWINDOWS;
    else
        setDefaultValue();
}

template<>
string FbTk::Resource<ToolbarHandler::ToolbarMode>::
getString() {
    switch (m_value) {
    case ToolbarHandler::OFF:
        return string("Off");
        break;
    case ToolbarHandler::NONE:
        return string("None");
        break;
    case ToolbarHandler::LASTMODE:
    case ToolbarHandler::ICONS:
        return string("Icons");
        break;
    case ToolbarHandler::WORKSPACEICONS:
        return string("WorkspaceIcons");
        break;
    case ToolbarHandler::WORKSPACE:
        return string("Workspace");
        break;
    case ToolbarHandler::ALLWINDOWS:
        return string("AllWindows");
        break;
    }
    // default string
    return string("Icons");
}

namespace {

class ToolbarModeMenuItem : public FbTk::MenuItem {
public:
    ToolbarModeMenuItem(const char *label, ToolbarHandler &handler,
                        ToolbarHandler::ToolbarMode mode,
                        FbTk::RefCount<FbTk::Command> &cmd):
        FbTk::MenuItem(label, cmd), m_handler(handler), m_mode(mode) {
    }
    bool isEnabled() const { return m_handler.mode() != m_mode; }
    void click(int button, int time) {
        m_handler.setMode(m_mode);
        FbTk::MenuItem::click(button, time);
    }

private:
    ToolbarHandler &m_handler;
    ToolbarHandler::ToolbarMode m_mode;
};

void setupModeMenu(FbTk::Menu &menu, ToolbarHandler &handler) {
    //I18n *i18n = I18n::instance();
    //using namespace FBNLS;
    using namespace FbTk;

    RefCount<Command> saverc_cmd(new SimpleCommand<Fluxbox>(
        *Fluxbox::instance(),
        &Fluxbox::save_rc));

    //TODO: nls
    menu.insert(new ToolbarModeMenuItem("Off", handler,
                                        ToolbarHandler::OFF, saverc_cmd));
    menu.insert(new ToolbarModeMenuItem("None", handler,
                                        ToolbarHandler::NONE, saverc_cmd));
    menu.insert(new ToolbarModeMenuItem("Icons", handler,
                                        ToolbarHandler::ICONS, saverc_cmd));
    menu.insert(new ToolbarModeMenuItem("Workspace Icons", handler,
                                        ToolbarHandler::WORKSPACEICONS, saverc_cmd));
    menu.insert(new ToolbarModeMenuItem("Workspace", handler,
                                        ToolbarHandler::WORKSPACE, saverc_cmd));
    menu.insert(new ToolbarModeMenuItem("All Windows", handler,
                                        ToolbarHandler::ALLWINDOWS, saverc_cmd));
    menu.update();
}

}; // end anonymous namespace

ToolbarHandler::ToolbarHandler(BScreen &screen)
    : m_screen(screen),
      m_rc_mode(screen.resourceManager(), ToolbarHandler::ICONS,
                screen.name() + ".toolbar.mode", screen.altName() + ".Toolbar.Mode"),
      m_toolbar(0),
      m_current_workspace(0),
      m_modemenu(*screen.menuTheme(),
                 screen.screenNumber(), screen.imageControl()),
      m_toolbarmenu(*screen.menuTheme(),
                    screen.screenNumber(), screen.imageControl()) {
    m_modemenu.setInternalMenu();
    m_toolbarmenu.setInternalMenu();
    setupModeMenu(m_modemenu, *this);
    setMode(*m_rc_mode, false); // the atomhandler part will initialise it shortly
}

void ToolbarHandler::setMode(ToolbarMode newmode, bool initialise) {
    if (newmode < 0 || newmode >= LASTMODE || (newmode == mode() && initialise))
        return;

    *m_rc_mode = newmode;

    if (newmode == OFF) {
        m_toolbarmenu.removeAll();
        //TODO: nls
        m_toolbarmenu.insert("Mode...", &m_modemenu);
        m_toolbar.reset(0);
        m_toolbarmenu.update();

        return;
    } else if (!m_toolbar.get()) {
        m_toolbarmenu.removeAll();
        m_toolbar.reset(new Toolbar(m_screen,
                                    *m_screen.layerManager().getLayer(Fluxbox::instance()->getNormalLayer()), m_toolbarmenu));
        Fluxbox::instance()->load_rc(m_screen);
        m_toolbar->reconfigure();

        m_toolbarmenu.insert("Mode...", &m_modemenu);
        m_toolbarmenu.update();
    }

    if (newmode == NONE) {
        // disableIconBar will clean up
        m_toolbar->disableIconBar();
    } else {
        // rebuild it
        // be sure the iconbar is on
        m_toolbar->enableIconBar();
        m_toolbar->delAllIcons();
    }

    if (initialise)
        initForScreen(m_screen);
}

void ToolbarHandler::initForScreen(BScreen &screen) {
    if (&m_screen != &screen)
        return;

    if (m_toolbar.get() != 0)
        m_toolbar->disableUpdates();

    switch (mode()) {
    case OFF:
        break;
    case NONE:
        break;
    case ALLWINDOWS: {
        BScreen::Workspaces::const_iterator workspace_it = m_screen.getWorkspacesList().begin();
        BScreen::Workspaces::const_iterator workspace_it_end = m_screen.getWorkspacesList().end();
        for (; workspace_it != workspace_it_end; ++workspace_it) {
            Workspace::Windows &wins = (*workspace_it)->windowList();
            Workspace::Windows::iterator wit = wins.begin();
            Workspace::Windows::iterator wit_end = wins.end();
            for (; wit != wit_end; ++wit) {
                if (!m_toolbar->containsIcon(**wit))
                    m_toolbar->addIcon(*wit);
/*
                FluxboxWindow::ClientList::iterator cit = (*wit)->clientList().begin();
                FluxboxWindow::ClientList::iterator cit_end = (*wit)->clientList().end();
                for (; cit != cit_end; ++cit)
                    m_toolbar->addIcon(*(*cit));
*/
            }
        }
    }
    // fall through and add icons
    case LASTMODE:
    case ICONS: {
        BScreen::Icons &iconlist = m_screen.getIconList();
        BScreen::Icons::iterator iconit = iconlist.begin();
        BScreen::Icons::iterator iconit_end = iconlist.end();
        for(; iconit != iconit_end; ++iconit) {
            m_toolbar->addIcon(*iconit);
        }
    }
    break;
    case WORKSPACE: {
        Workspace::Windows &wins = m_screen.currentWorkspace()->windowList();
        Workspace::Windows::iterator wit = wins.begin();
        Workspace::Windows::iterator wit_end = wins.end();
        for (; wit != wit_end; ++wit) {
            if (!m_toolbar->containsIcon(**wit))
                m_toolbar->addIcon(*wit);
        }
    }
    // fall through and add icons for this workspace
    case WORKSPACEICONS: {
        m_current_workspace = m_screen.currentWorkspaceID();

        BScreen::Icons &wiconlist = m_screen.getIconList();
        BScreen::Icons::iterator iconit = wiconlist.begin();
        BScreen::Icons::iterator iconit_end = wiconlist.end();
        for(; iconit != iconit_end; ++iconit) {
            if ((*iconit)->workspaceNumber() == m_current_workspace)
                m_toolbar->addIcon(*iconit);
        }
    }
    break;
    }

    if (m_toolbar.get() != 0)
        m_toolbar->enableUpdates();

}

void ToolbarHandler::setupFrame(FluxboxWindow &win) {
    if (&win.screen() != &m_screen)
        return;

    switch (mode()) {
    case OFF:
    case NONE:
        break;
    case WORKSPACE:
        if (win.workspaceNumber() == m_current_workspace)
            m_toolbar->addIcon(&win);
        break;
    case WORKSPACEICONS:
        if (win.workspaceNumber() != m_current_workspace)
            break;
        // else fall through and add the icon
    case LASTMODE:
    case ICONS:
        if (win.isIconic()) {
            m_toolbar->addIcon(&win);
        }
        break;
    case ALLWINDOWS:
        m_toolbar->addIcon(&win);
        break;
    }
}

void ToolbarHandler::updateFrameClose(FluxboxWindow &win) {
    if (&win.screen() != &m_screen)
        return;

    // check status of window (in current workspace, etc) and remove if necessary
    switch (mode()) {
    case OFF:
    case NONE:
        break;
    case WORKSPACEICONS:
        if (win.workspaceNumber() != m_current_workspace)
            break;
        // else fall through and remove the icon
    case LASTMODE:
    case ICONS:
        if (win.isIconic()) {
            m_toolbar->delIcon(&win);
        }
        break;
    case WORKSPACE:
        if (win.isStuck() || win.workspaceNumber() == m_current_workspace)
            m_toolbar->delIcon(&win);
        break;
    case ALLWINDOWS:
        m_toolbar->delIcon(&win);
        break;
    }
}

void ToolbarHandler::updateState(FluxboxWindow &win) {
    if (&win.screen() != &m_screen)
        return;

    // this function only relevant for icons
    switch (mode()) {
    case OFF:
    case NONE:
    case WORKSPACE:
    case ALLWINDOWS:
        break;
    case WORKSPACEICONS:
        if (win.workspaceNumber() != m_current_workspace)
            break;
        // else fall through and do the same as icons (knowing it is the right ws)
    case LASTMODE:
    case ICONS:
        // if the window is iconic (it mustn't have been before), then add it
        // else remove it
        if (win.isIconic()) {
            if (!m_toolbar->containsIcon(win)) {
                m_toolbar->addIcon(&win);
            }
        } else {
            m_toolbar->delIcon(&win);
        }
        break;
    }
}

void ToolbarHandler::updateWorkspace(FluxboxWindow &win) {
    if (&win.screen() != &m_screen)
        return;

    // don't care about current workspace except if in workspace mode
    if (!(mode() == WORKSPACE ||
          (mode() == WORKSPACEICONS && win.isIconic())))
        return;

    if (win.workspaceNumber() == m_current_workspace) {
        //!! TODO
        // this shouldn't be needed, but is until Workspaces get fixed so that
        // you only move between them, you don't 'add' and 'remove'
        // alternatively, fix reassocaiteWindow so that the iconic stuff is
        // done elsewhere
        if (!m_toolbar->containsIcon(win))
            m_toolbar->addIcon(&win);
    } else {
        // relies on the fact that this runs but does nothing if window isn't contained.
        if (!win.isStuck())
            m_toolbar->delIcon(&win);
    }
}

void ToolbarHandler::updateCurrentWorkspace(BScreen &screen) {
    if (&screen != &m_screen)
        return;

    m_toolbar->redrawWorkspaceLabel(true);
    m_toolbar->disableUpdates();
    m_toolbar->delAllIcons(true);
    initForScreen(m_screen);
    m_toolbar->enableUpdates();

}

<commit_msg>some extra checks on icons<commit_after>// ToolbarHandler for fluxbox
// Copyright (c) 2003 Simon Bowden (rathnor at fluxbox.org)
//                and Henrik Kinnunen (fluxgen at fluxbox.org)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

// $Id: ToolbarHandler.cc,v 1.22 2003/07/10 11:53:44 fluxgen Exp $

/**
 * The ToolbarHandler class acts as a rough interface to the toolbar.
 * It deals with whether it should be there or not, so anything that
 * always needs to be accessible must come through the handler.
 */

#include "ToolbarHandler.hh"
#include "Window.hh"
#include "Screen.hh"
#include "Workspace.hh"
#include "MenuItem.hh"
#include "Menu.hh"
#include "FbCommands.hh"
#include "RefCount.hh"
#include "SimpleCommand.hh"
#include "MacroCommand.hh"
#include "IntResMenuItem.hh"
#include "BoolMenuItem.hh"

#include <string>

using namespace std;

template<>
void FbTk::Resource<ToolbarHandler::ToolbarMode>::
setFromString(const char *strval) {
    if (strcasecmp(strval, "Off") == 0)
        m_value = ToolbarHandler::OFF;
    else if (strcasecmp(strval, "None") == 0)
        m_value = ToolbarHandler::NONE;
    else if (strcasecmp(strval, "Icons") == 0)
        m_value = ToolbarHandler::ICONS;
    else if (strcasecmp(strval, "WorkspaceIcons") == 0)
        m_value = ToolbarHandler::WORKSPACEICONS;
    else if (strcasecmp(strval, "Workspace") == 0)
        m_value = ToolbarHandler::WORKSPACE;
    else if (strcasecmp(strval, "AllWindows") == 0)
        m_value = ToolbarHandler::ALLWINDOWS;
    else
        setDefaultValue();
}

template<>
string FbTk::Resource<ToolbarHandler::ToolbarMode>::
getString() {
    switch (m_value) {
    case ToolbarHandler::OFF:
        return string("Off");
        break;
    case ToolbarHandler::NONE:
        return string("None");
        break;
    case ToolbarHandler::LASTMODE:
    case ToolbarHandler::ICONS:
        return string("Icons");
        break;
    case ToolbarHandler::WORKSPACEICONS:
        return string("WorkspaceIcons");
        break;
    case ToolbarHandler::WORKSPACE:
        return string("Workspace");
        break;
    case ToolbarHandler::ALLWINDOWS:
        return string("AllWindows");
        break;
    }
    // default string
    return string("Icons");
}

namespace {

class ToolbarModeMenuItem : public FbTk::MenuItem {
public:
    ToolbarModeMenuItem(const char *label, ToolbarHandler &handler,
                        ToolbarHandler::ToolbarMode mode,
                        FbTk::RefCount<FbTk::Command> &cmd):
        FbTk::MenuItem(label, cmd), m_handler(handler), m_mode(mode) {
    }
    bool isEnabled() const { return m_handler.mode() != m_mode; }
    void click(int button, int time) {
        m_handler.setMode(m_mode);
        FbTk::MenuItem::click(button, time);
    }

private:
    ToolbarHandler &m_handler;
    ToolbarHandler::ToolbarMode m_mode;
};

void setupModeMenu(FbTk::Menu &menu, ToolbarHandler &handler) {
    //I18n *i18n = I18n::instance();
    //using namespace FBNLS;
    using namespace FbTk;

    RefCount<Command> saverc_cmd(new SimpleCommand<Fluxbox>(
        *Fluxbox::instance(),
        &Fluxbox::save_rc));

    //TODO: nls
    menu.insert(new ToolbarModeMenuItem("Off", handler,
                                        ToolbarHandler::OFF, saverc_cmd));
    menu.insert(new ToolbarModeMenuItem("None", handler,
                                        ToolbarHandler::NONE, saverc_cmd));
    menu.insert(new ToolbarModeMenuItem("Icons", handler,
                                        ToolbarHandler::ICONS, saverc_cmd));
    menu.insert(new ToolbarModeMenuItem("Workspace Icons", handler,
                                        ToolbarHandler::WORKSPACEICONS, saverc_cmd));
    menu.insert(new ToolbarModeMenuItem("Workspace", handler,
                                        ToolbarHandler::WORKSPACE, saverc_cmd));
    menu.insert(new ToolbarModeMenuItem("All Windows", handler,
                                        ToolbarHandler::ALLWINDOWS, saverc_cmd));
    menu.update();
}

}; // end anonymous namespace

ToolbarHandler::ToolbarHandler(BScreen &screen)
    : m_screen(screen),
      m_rc_mode(screen.resourceManager(), ToolbarHandler::ICONS,
                screen.name() + ".toolbar.mode", screen.altName() + ".Toolbar.Mode"),
      m_toolbar(0),
      m_current_workspace(0),
      m_modemenu(*screen.menuTheme(),
                 screen.screenNumber(), screen.imageControl()),
      m_toolbarmenu(*screen.menuTheme(),
                    screen.screenNumber(), screen.imageControl()) {
    m_modemenu.setInternalMenu();
    m_toolbarmenu.setInternalMenu();
    setupModeMenu(m_modemenu, *this);
    setMode(*m_rc_mode, false); // the atomhandler part will initialise it shortly
}

void ToolbarHandler::setMode(ToolbarMode newmode, bool initialise) {
    if (newmode < 0 || newmode >= LASTMODE || (newmode == mode() && initialise))
        return;

    *m_rc_mode = newmode;

    if (newmode == OFF) {
        m_toolbarmenu.removeAll();
        //TODO: nls
        m_toolbarmenu.insert("Mode...", &m_modemenu);
        m_toolbar.reset(0);
        m_toolbarmenu.update();

        return;
    } else if (!m_toolbar.get()) {
        m_toolbarmenu.removeAll();
        m_toolbar.reset(new Toolbar(m_screen,
                                    *m_screen.layerManager().getLayer(Fluxbox::instance()->getNormalLayer()), m_toolbarmenu));
        Fluxbox::instance()->load_rc(m_screen);
        m_toolbar->reconfigure();

        m_toolbarmenu.insert("Mode...", &m_modemenu);
        m_toolbarmenu.update();
    }

    if (newmode == NONE) {
        // disableIconBar will clean up
        m_toolbar->disableIconBar();
    } else {
        // rebuild it
        // be sure the iconbar is on
        m_toolbar->enableIconBar();
        m_toolbar->delAllIcons();
    }

    if (initialise)
        initForScreen(m_screen);
}

void ToolbarHandler::initForScreen(BScreen &screen) {
    if (&m_screen != &screen)
        return;

    if (m_toolbar.get() != 0)
        m_toolbar->disableUpdates();

    switch (mode()) {
    case OFF:
        break;
    case NONE:
        break;
    case ALLWINDOWS: {
        BScreen::Workspaces::const_iterator workspace_it = m_screen.getWorkspacesList().begin();
        BScreen::Workspaces::const_iterator workspace_it_end = m_screen.getWorkspacesList().end();
        for (; workspace_it != workspace_it_end; ++workspace_it) {
            Workspace::Windows &wins = (*workspace_it)->windowList();
            Workspace::Windows::iterator wit = wins.begin();
            Workspace::Windows::iterator wit_end = wins.end();
            for (; wit != wit_end; ++wit) {

                if (!m_toolbar->containsIcon(**wit) && *wit != 0)
                    m_toolbar->addIcon(*wit);
/*
                FluxboxWindow::ClientList::iterator cit = (*wit)->clientList().begin();
                FluxboxWindow::ClientList::iterator cit_end = (*wit)->clientList().end();
                for (; cit != cit_end; ++cit)
                    m_toolbar->addIcon(*(*cit));
*/
            }
        }
    }
    // fall through and add icons
    case LASTMODE:
    case ICONS: {
        BScreen::Icons &iconlist = m_screen.getIconList();
        BScreen::Icons::iterator iconit = iconlist.begin();
        BScreen::Icons::iterator iconit_end = iconlist.end();
        for(; iconit != iconit_end; ++iconit) {
            if (*iconit == 0)
                continue;
            m_toolbar->addIcon(*iconit);
        }
    }
    break;
    case WORKSPACE: {
        Workspace::Windows &wins = m_screen.currentWorkspace()->windowList();
        Workspace::Windows::iterator wit = wins.begin();
        Workspace::Windows::iterator wit_end = wins.end();
        for (; wit != wit_end; ++wit) {

            if (!m_toolbar->containsIcon(**wit) && *wit != 0)
                m_toolbar->addIcon(*wit);
        }
    }
    // fall through and add icons for this workspace
    case WORKSPACEICONS: {
        m_current_workspace = m_screen.currentWorkspaceID();

        BScreen::Icons &wiconlist = m_screen.getIconList();
        BScreen::Icons::iterator iconit = wiconlist.begin();
        BScreen::Icons::iterator iconit_end = wiconlist.end();
        for(; iconit != iconit_end; ++iconit) {
            if ((*iconit)->workspaceNumber() == m_current_workspace)
                m_toolbar->addIcon(*iconit);
        }
    }
    break;
    }

    if (m_toolbar.get() != 0)
        m_toolbar->enableUpdates();

}

void ToolbarHandler::setupFrame(FluxboxWindow &win) {
    if (&win.screen() != &m_screen)
        return;

    switch (mode()) {
    case OFF:
    case NONE:
        break;
    case WORKSPACE:
        if (win.workspaceNumber() == m_current_workspace)
            m_toolbar->addIcon(&win);
        break;
    case WORKSPACEICONS:
        if (win.workspaceNumber() != m_current_workspace)
            break;
        // else fall through and add the icon
    case LASTMODE:
    case ICONS:
        if (win.isIconic())
            m_toolbar->addIcon(&win);
        break;
    case ALLWINDOWS:
        m_toolbar->addIcon(&win);
        break;
    }
}

void ToolbarHandler::updateFrameClose(FluxboxWindow &win) {
    if (&win.screen() != &m_screen)
        return;

    // check status of window (in current workspace, etc) and remove if necessary
    switch (mode()) {
    case OFF:
    case NONE:
        break;
    case WORKSPACEICONS:
        if (win.workspaceNumber() != m_current_workspace)
            break;
        // else fall through and remove the icon
    case LASTMODE:
    case ICONS:
        if (win.isIconic()) {
            m_toolbar->delIcon(&win);
        }
        break;
    case WORKSPACE:
        if (win.isStuck() || win.workspaceNumber() == m_current_workspace)
            m_toolbar->delIcon(&win);
        break;
    case ALLWINDOWS:
        m_toolbar->delIcon(&win);
        break;
    }
}

void ToolbarHandler::updateState(FluxboxWindow &win) {
    if (&win.screen() != &m_screen)
        return;

    // this function only relevant for icons
    switch (mode()) {
    case OFF:
    case NONE:
    case WORKSPACE:
    case ALLWINDOWS:
        break;
    case WORKSPACEICONS:
        if (win.workspaceNumber() != m_current_workspace)
            break;
        // else fall through and do the same as icons (knowing it is the right ws)
    case LASTMODE:
    case ICONS:
        // if the window is iconic (it mustn't have been before), then add it
        // else remove it
        if (win.isIconic()) {
            if (!m_toolbar->containsIcon(win)) {
                m_toolbar->addIcon(&win);
            }
        } else {
            m_toolbar->delIcon(&win);
        }
        break;
    }
}

void ToolbarHandler::updateWorkspace(FluxboxWindow &win) {
    if (&win.screen() != &m_screen)
        return;

    // don't care about current workspace except if in workspace mode
    if (!(mode() == WORKSPACE ||
          (mode() == WORKSPACEICONS && win.isIconic())))
        return;

    if (win.workspaceNumber() == m_current_workspace) {
        //!! TODO
        // this shouldn't be needed, but is until Workspaces get fixed so that
        // you only move between them, you don't 'add' and 'remove'
        // alternatively, fix reassocaiteWindow so that the iconic stuff is
        // done elsewhere
        if (!m_toolbar->containsIcon(win))
            m_toolbar->addIcon(&win);
    } else {
        // relies on the fact that this runs but does nothing if window isn't contained.
        if (!win.isStuck())
            m_toolbar->delIcon(&win);
    }
}

void ToolbarHandler::updateCurrentWorkspace(BScreen &screen) {
    if (&screen != &m_screen)
        return;

    m_toolbar->redrawWorkspaceLabel(true);
    m_toolbar->disableUpdates();
    m_toolbar->delAllIcons(true);
    initForScreen(m_screen);
    m_toolbar->enableUpdates();

}

<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include <algorithm>
#include "UserInterface.h"

using namespace std;

void UserInterface::enterMenu (istream& in, ostream& out) {
	bool quit = false;

	cout << "REMOVE THIS" << endl;
	this->room.loadFromXMLFile("xmlfiles/Level3.xml");
	this->room.loadMovesFromXMLFile("xmlfiles/Bewegingen1.0.xml");

	this->printHelp(out);

	while (!quit) {
		string command;

		out << "Give a command: ";
		getline(in, command);
		out << endl;

		this->parseCommand(out, command);
	}
}

 void UserInterface::parseCommand (ostream& out, string command) {
	string actual_command;
	istringstream iss(command);

	// Extract the first word
	iss >> actual_command;
	std::transform(actual_command.begin(), actual_command.end(), actual_command.begin(), ::tolower);

	out << "You executed: " << actual_command << endl;

	if (actual_command == "help") {
		printHelp(out);
	}

	else if (actual_command == "loadlevel") {
		string filename;
		iss >> filename;
		this->room.loadFromXMLFile(filename.c_str());
	}

	else if (actual_command == "loadmoves") {
		string filename;
		iss >> filename;
		this->room.loadMovesFromXMLFile(filename.c_str());
	}

	else if (actual_command == "print") {
		out << "Printing: " << endl;
		this->room.printRoom(out);
	}

	else if (actual_command == "printtofile") {
		string filename;
		iss >> filename;
		filename = "game_board_" + filename;

		out << "Printing to file '" << filename << "'" << endl;

		std::ofstream file;
		file.open(filename);

		this->room.printRoom(file);
	}

	else if (actual_command == "printtoxmlfile") {
		string filename;
		iss >> filename;
		filename = "xml_game_board_" + filename;

		out << "Printing to file '" << filename << "'" << endl;

		std::ofstream file;
		file.open(filename);

		this->room.saveToXMLFile(file);
	}

	else if (actual_command == "printmovestoxmlfile") {
		string filename;
		iss >> filename;
		filename = "xml_moves_" + filename;

		out << "Printing to file '" << filename << "'" << endl;

		std::ofstream file;
		file.open(filename);

		this->room.saveMovesToXMLFile(file);
	}

	else if (actual_command == "run") {
		string moves;
		iss >> moves;
		this->room.executeMoves("HuidigSpeelveld.txt", "ResterendeBewegingen.txt", atoi(moves.c_str()));
	}
}

void UserInterface::printHelp (ostream& out) {
	out << "The following commands are available:" << endl << endl;

	out << "- help" << endl;
	out << "\t Prints this help menu" << endl << endl;

	out << "- loadLevel [filename]" << endl;
	out << "\t Parses the given xml file as a level" << endl << endl;

	out << "- loadMoves [filename]" << endl;
	out << "\t Parses the given xml file as moves" << endl << endl;

	out << "- print" << endl;
	out << "\t Prints the current room" << endl << endl;

	out << "- printToFile [filename]" << endl;
	out << "\t Prints the current room to a file called game_board_[filename]" << endl << endl;

	out << "- printToXMLFile [filename]" << endl;
	out << "\t Prints the current room to a file called game_board_[filename]" << endl << endl;

	out << "- printMovesToXMLFile [filename]" << endl;
	out << "\t Prints the currently left moves to a file called game_board_[filename]" << endl << endl;

	out << "- run [maxsteps]" << endl;
	out << "\t Runs the simulation untill the end" << endl;
	out << "\t If maxsteps is a positive number the simulation is run till the end or till maxsteps steps have been executed whichever comes first." << endl << endl;
}<commit_msg>Remove quickloading<commit_after>#include <iostream>
#include <sstream>
#include <algorithm>
#include "UserInterface.h"

using namespace std;

void UserInterface::enterMenu (istream& in, ostream& out) {
	bool quit = false;

	this->printHelp(out);

	while (!quit) {
		string command;

		out << "Give a command: ";
		getline(in, command);
		out << endl;

		this->parseCommand(out, command);
	}
}

 void UserInterface::parseCommand (ostream& out, string command) {
	string actual_command;
	istringstream iss(command);

	// Extract the first word
	iss >> actual_command;
	std::transform(actual_command.begin(), actual_command.end(), actual_command.begin(), ::tolower);

	out << "You executed: " << actual_command << endl;

	if (actual_command == "help") {
		printHelp(out);
	}

	else if (actual_command == "loadlevel") {
		string filename;
		iss >> filename;
		this->room.loadFromXMLFile(filename.c_str());
	}

	else if (actual_command == "loadmoves") {
		string filename;
		iss >> filename;
		this->room.loadMovesFromXMLFile(filename.c_str());
	}

	else if (actual_command == "print") {
		out << "Printing: " << endl;
		this->room.printRoom(out);
	}

	else if (actual_command == "printtofile") {
		string filename;
		iss >> filename;
		filename = "game_board_" + filename;

		out << "Printing to file '" << filename << "'" << endl;

		std::ofstream file;
		file.open(filename);

		this->room.printRoom(file);
	}

	else if (actual_command == "printtoxmlfile") {
		string filename;
		iss >> filename;
		filename = "xml_game_board_" + filename;

		out << "Printing to file '" << filename << "'" << endl;

		std::ofstream file;
		file.open(filename);

		this->room.saveToXMLFile(file);
	}

	else if (actual_command == "printmovestoxmlfile") {
		string filename;
		iss >> filename;
		filename = "xml_moves_" + filename;

		out << "Printing to file '" << filename << "'" << endl;

		std::ofstream file;
		file.open(filename);

		this->room.saveMovesToXMLFile(file);
	}

	else if (actual_command == "run") {
		string moves;
		iss >> moves;
		this->room.executeMoves("HuidigSpeelveld.txt", "ResterendeBewegingen.txt", atoi(moves.c_str()));
	}
}

void UserInterface::printHelp (ostream& out) {
	out << "The following commands are available:" << endl << endl;

	out << "- help" << endl;
	out << "\t Prints this help menu" << endl << endl;

	out << "- loadLevel [filename]" << endl;
	out << "\t Parses the given xml file as a level" << endl << endl;

	out << "- loadMoves [filename]" << endl;
	out << "\t Parses the given xml file as moves" << endl << endl;

	out << "- print" << endl;
	out << "\t Prints the current room" << endl << endl;

	out << "- printToFile [filename]" << endl;
	out << "\t Prints the current room to a file called game_board_[filename]" << endl << endl;

	out << "- printToXMLFile [filename]" << endl;
	out << "\t Prints the current room to a file called game_board_[filename]" << endl << endl;

	out << "- printMovesToXMLFile [filename]" << endl;
	out << "\t Prints the currently left moves to a file called game_board_[filename]" << endl << endl;

	out << "- run [maxsteps]" << endl;
	out << "\t Runs the simulation untill the end" << endl;
	out << "\t If maxsteps is a positive number the simulation is run till the end or till maxsteps steps have been executed whichever comes first." << endl << endl;
}<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(XALAN_KEYTABLE_HEADER_GUARD)
#define XALAN_KEYTABLE_HEADER_GUARD

/**
 * $Id$
 *
 * $State$
 *
 * @author Myriam Midy (Myriam_Midy @lotus.com
 */

// Base include file.  Must be first.
#include "XSLTDefinitions.hpp"

#if defined(XALAN_HASH_CONTAINERS_AVAILABLE)
#include <hash_map>
#else
#include <map>
#endif

#include<vector>

// Base class header file.
//#include "UnImplNode.hpp"
//#include "PrefixResolver.hpp"
//#include "Constants.hpp"

// Xerces XML4C header files.
#include <dom/DOM_Node.hpp>
#include <dom/DOMString.hpp>

#include <XPath/MutableNodeRefList.hpp>

class DOM_Element;
class DOM_Node;
class KeyDeclaration;
class NodeRefListBase;
class PrefixResolver;
class XPathExecutionContext;

/**
 * Table of element keys, keyed by document node.  An instance of this
 * class is keyed by a Document node that should be matched with the
 * root of the current context.  It contains a table of name mappings
 * to tables that contain mappings of identifier values to nodes.
 */
class KeyTable
{
public:

	/**
	 * Build a keys table.
	 *
	 * @param doc The owner document key (normally the same as startNode).
	 * @param startNode The node to start itterating from to build the keys index.
	 * @param nscontext The stylesheet's namespace context.
	 * @param keyDeclarations The stylesheet's xsl:key declarations.
	 * @param executionContext The current execution context.
	 */
	KeyTable(
			const DOM_Node&						doc,
			const DOM_Node&						startNode,
			const PrefixResolver&				resolver,
			const std::vector<KeyDeclaration>&	keyDeclarations,
			XPathExecutionContext&				executionContext);

	virtual
	~KeyTable();

	/**
	 * Given a valid element key, return the corresponding node list. If the
	 * name was not declared with xsl:key, this will return null, the
	 * identifier is not found, it will return an empty node set, otherwise it
	 * will return a nodeset of nodes.
	 *
	 * @param name name of the key, which must match the 'name' attribute on
	 *             xsl:key
	 * @param ref  value that must match the value found by the 'match'
	 *             attribute on xsl:key
	 * @return		pointer to nodeset for key
	 */
	const NodeRefListBase*
	getNodeSetByKey(
				  const DOMString&	name,
				  const DOMString&	ref) const;

	/**
	 * Retrieve the document key.  This table should only be used with contexts
	 * whose Document root matches this key.
	 *
	 * @return Node for document
	 */
	DOM_Node
	getDocKey() const
	{
		return m_docKey;
	}

private:

	/**
	 * The document key.  This table should only be used with contexts
	 * whose Document roots match this key.
	 */
	DOM_Node	m_docKey;

	/**
	 * Hashtable of keys.
	 * The table is:
	 * a) keyed by name,
	 * b) each with a value of a hashtable, keyed by the value returned by
	 *    the use attribute,
	 * c) each with a value that is a nodelist.
	 * Thus, for a given key or keyref, look up hashtable by name,
	 * look up the nodelist by the given reference.
	 */

	/**
	 * Table of element keys.  The table will be built on demand,
	 * when a key is requested, or set by the XMLParserLiaison or
	 * the caller.  The table is:
	 * a) keyed by name,
	 * b) each with a value of a hashtable, keyed by the value returned by
	 *    the use attribute,
	 * c) each with a value that is a nodelist.
	 * Thus, for a given key or keyref, look up hashtable by name,
	 * look up the nodelist by the given reference.
	 */

#if defined(XALAN_HASH_CONTAINERS_AVAILABLE)
	typedef hash_map<DOMString,
					 MutableNodeRefList,
					 DOMStringHashFunction,
					 DOMStringEqualsFunction>	NodeListMapType;

	typedef hash_map<DOMString,
					 NodeListMapType,
					 DOMStringHashFunction,
					 DOMStringEqualsFunction>	KeysMapType;
#else
	typedef std::map<DOMString,
					 MutableNodeRefList>	NodeListMapType;

	typedef std::map<DOMString,
					 NodeListMapType>	KeysMapType;
#endif

	KeysMapType		m_keys;
};

#endif	// XALAN_KEYTABLE_HEADER_GUARD
<commit_msg>Fixed javadoc comments<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(XALAN_KEYTABLE_HEADER_GUARD)
#define XALAN_KEYTABLE_HEADER_GUARD

/**
 * $Id$
 *
 * $State$
 *
 * @author Myriam Midy (Myriam_Midy @lotus.com
 */

// Base include file.  Must be first.
#include "XSLTDefinitions.hpp"

#if defined(XALAN_HASH_CONTAINERS_AVAILABLE)
#include <hash_map>
#else
#include <map>
#endif

#include<vector>

// Base class header file.
//#include "UnImplNode.hpp"
//#include "PrefixResolver.hpp"
//#include "Constants.hpp"

// Xerces XML4C header files.
#include <dom/DOM_Node.hpp>
#include <dom/DOMString.hpp>

#include <XPath/MutableNodeRefList.hpp>

class DOM_Element;
class DOM_Node;
class KeyDeclaration;
class NodeRefListBase;
class PrefixResolver;
class XPathExecutionContext;

/**
 * Table of element keys, keyed by document node.  An instance of this
 * class is keyed by a Document node that should be matched with the
 * root of the current context.  It contains a table of name mappings
 * to tables that contain mappings of identifier values to nodes.
 */
class KeyTable
{
public:

	/**
	 * Build a keys table.
	 *
	 * @param doc              owner document key (normally the same as
	 *                         startNode)
	 * @param startNode        node to start iterating from to build the keys
	 *                         index
	 * @param nscontext        stylesheet's namespace context
	 * @param keyDeclarations  stylesheet's xsl:key declarations
	 * @param executionContext current execution context
	 */
	KeyTable(
			const DOM_Node&						doc,
			const DOM_Node&						startNode,
			const PrefixResolver&				resolver,
			const std::vector<KeyDeclaration>&	keyDeclarations,
			XPathExecutionContext&				executionContext);

	virtual
	~KeyTable();

	/**
	 * Given a valid element key, return the corresponding node list. If the
	 * name was not declared with xsl:key, this will return null, the
	 * identifier is not found, it will return an empty node set, otherwise it
	 * will return a nodeset of nodes.
	 *
	 * @param name name of the key, which must match the 'name' attribute on
	 *             xsl:key
	 * @param ref  value that must match the value found by the 'match'
	 *             attribute on xsl:key
	 * @return		pointer to nodeset for key
	 */
	const NodeRefListBase*
	getNodeSetByKey(
				  const DOMString&	name,
				  const DOMString&	ref) const;

	/**
	 * Retrieve the document key.  This table should only be used with contexts
	 * whose Document root matches this key.
	 *
	 * @return Node for document
	 */
	DOM_Node
	getDocKey() const
	{
		return m_docKey;
	}

private:

	/**
	 * The document key.  This table should only be used with contexts
	 * whose Document roots match this key.
	 */
	DOM_Node	m_docKey;

	/**
	/**
	 * Table of element keys.  The table will be built on demand,
	 * when a key is requested, or set by the XMLParserLiaison or
	 * the caller.  The table is:
	 * a) keyed by name,
	 * b) each with a value of a hashtable, keyed by the value returned by
	 *    the use attribute,
	 * c) each with a value that is a nodelist.
	 * Thus, for a given key or keyref, look up hashtable by name,
	 * look up the nodelist by the given reference.
	 */

#if defined(XALAN_HASH_CONTAINERS_AVAILABLE)
	typedef hash_map<DOMString,
					 MutableNodeRefList,
					 DOMStringHashFunction,
					 DOMStringEqualsFunction>	NodeListMapType;

	typedef hash_map<DOMString,
					 NodeListMapType,
					 DOMStringHashFunction,
					 DOMStringEqualsFunction>	KeysMapType;
#else
	typedef std::map<DOMString,
					 MutableNodeRefList>	NodeListMapType;

	typedef std::map<DOMString,
					 NodeListMapType>	KeysMapType;
#endif

	KeysMapType		m_keys;
};

#endif	// XALAN_KEYTABLE_HEADER_GUARD
<|endoftext|>


<commit_before>// Copyright (c) 2011 Zeex
//
// 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 <cstring>
#include <iterator>

#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>

#include "amxpathfinder.h"

#include "amx/amx.h"
#include "amx/amxaux.h"

AMXPathFinder::AMXFile::AMXFile(const std::string &name)
	: name_(name)
	, last_write_(boost::filesystem::last_write_time(name))
	, amxPtr_(new AMX, FreeAmx)
{
	if (aux_LoadProgram(amxPtr_.get(), const_cast<char*>(name.c_str()), 0) != AMX_ERR_NONE) {
		amxPtr_.reset();
	}
}

void AMXPathFinder::AMXFile::FreeAmx(AMX *amx) {
	aux_FreeProgram(amx);
	delete amx;
}

void AMXPathFinder::AddSearchPath(boost::filesystem::path path) {
	searchPaths_.push_back(path);
}

bool AMXPathFinder::FindAMX(AMX *amx, boost::filesystem::path &result) {
	// Look up in cache first
	std::map<AMX*, std::string>::const_iterator it = foundNames_.find(amx);
	if (it != foundNames_.end()) {
		result = it->second;
		return true;
	}

	// Get and load all .amx files in each of the current search paths (non-recursive)
	for (std::list<boost::filesystem::path>::const_iterator dir = searchPaths_.begin();
			dir != searchPaths_.end(); ++dir) {
		if (!boost::filesystem::exists(*dir) || !boost::filesystem::is_directory(*dir)) {
			continue;
		}
		for (boost::filesystem::directory_iterator file(*dir);
				file != boost::filesystem::directory_iterator(); ++file) {
			if (!boost::filesystem::is_regular_file(file->path()) ||
					!boost::algorithm::ends_with(file->path().string(), ".amx")) {
				continue;
			}

			std::string filename = file->path().string();
			std::time_t last_write = boost::filesystem::last_write_time(filename);

			std::map<std::string, AMXFile>::iterator script_it = loadedScripts_.find(filename);

			if (script_it == loadedScripts_.end() ||
					script_it->second.GetLastWriteTime() < last_write) {
				if (script_it != loadedScripts_.end()) {
					loadedScripts_.erase(script_it);
				}
				AMXFile script(filename);
				if (script.IsLoaded()) {
					loadedScripts_.insert(std::make_pair(filename, script));
				}
			}
		}
	}

	for (std::map<std::string, AMXFile>::const_iterator iterator = loadedScripts_.begin();
			iterator != loadedScripts_.end(); ++iterator)
	{
		const AMX *otherAmx = iterator->second.GetAmx();
		// Compare the two headers
		if (std::memcmp(amx->base, otherAmx->base, sizeof(AMX_HEADER)) == 0) {
			result = boost::filesystem::path(iterator->first);
			foundNames_.insert(std::make_pair(amx, result.string()));
			return true;
		}
	}

	return false;
}

std::string AMXPathFinder::FindAMX(AMX *amx) {
	boost::filesystem::path path;
	FindAMX(amx, path);
	return path.string();
}
<commit_msg>AMXPathFinder: Explicitly state that we want a relative path<commit_after>// Copyright (c) 2011 Zeex
//
// 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 <cstring>
#include <iterator>

#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>

#include "amxpathfinder.h"

#include "amx/amx.h"
#include "amx/amxaux.h"

AMXPathFinder::AMXFile::AMXFile(const std::string &name)
	: name_(name)
	, last_write_(boost::filesystem::last_write_time(name))
	, amxPtr_(new AMX, FreeAmx)
{
	if (aux_LoadProgram(amxPtr_.get(), const_cast<char*>(name.c_str()), 0) != AMX_ERR_NONE) {
		amxPtr_.reset();
	}
}

void AMXPathFinder::AMXFile::FreeAmx(AMX *amx) {
	aux_FreeProgram(amx);
	delete amx;
}

void AMXPathFinder::AddSearchPath(boost::filesystem::path path) {
	searchPaths_.push_back(path);
}

bool AMXPathFinder::FindAMX(AMX *amx, boost::filesystem::path &result) {
	// Look up in cache first
	std::map<AMX*, std::string>::const_iterator it = foundNames_.find(amx);
	if (it != foundNames_.end()) {
		result = it->second;
		return true;
	}

	// Get and load all .amx files in each of the current search paths (non-recursive)
	for (std::list<boost::filesystem::path>::const_iterator dir = searchPaths_.begin();
			dir != searchPaths_.end(); ++dir) {
		if (!boost::filesystem::exists(*dir) || !boost::filesystem::is_directory(*dir)) {
			continue;
		}
		for (boost::filesystem::directory_iterator file(*dir);
				file != boost::filesystem::directory_iterator(); ++file) {
			if (!boost::filesystem::is_regular_file(file->path()) ||
					!boost::algorithm::ends_with(file->path().string(), ".amx")) {
				continue;
			}

			std::string filename = file->path().relative_path().string();
			std::time_t last_write = boost::filesystem::last_write_time(filename);

			std::map<std::string, AMXFile>::iterator script_it = loadedScripts_.find(filename);

			if (script_it == loadedScripts_.end() ||
					script_it->second.GetLastWriteTime() < last_write) {
				if (script_it != loadedScripts_.end()) {
					loadedScripts_.erase(script_it);
				}
				AMXFile script(filename);
				if (script.IsLoaded()) {
					loadedScripts_.insert(std::make_pair(filename, script));
				}
			}
		}
	}

	for (std::map<std::string, AMXFile>::const_iterator iterator = loadedScripts_.begin();
			iterator != loadedScripts_.end(); ++iterator)
	{
		const AMX *otherAmx = iterator->second.GetAmx();
		// Compare the two headers
		if (std::memcmp(amx->base, otherAmx->base, sizeof(AMX_HEADER)) == 0) {
			result = boost::filesystem::path(iterator->first);
			foundNames_.insert(std::make_pair(amx, result.string()));
			return true;
		}
	}

	return false;
}

std::string AMXPathFinder::FindAMX(AMX *amx) {
	boost::filesystem::path path;
	FindAMX(amx, path);
	return path.string();
}
<|endoftext|>


<commit_before>#include "content/nw/src/api/nw_app_api.h"

#include "build/build_config.h"
#include "third_party/widevine/cdm/buildflags.h"

#include "chrome/browser/lifetime/browser_close_manager.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "content/public/common/content_features.h"

#include "base/command_line.h"
#include "base/memory/ptr_util.h"
#include "base/task/current_thread.h"
#include "base/task/post_task.h"
#include "content/public/browser/browser_task_traits.h"
#include "components/browsing_data/content/appcache_helper.h"
#include "components/browsing_data/content/browsing_data_helper.h"
#include "components/component_updater/component_updater_service.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
#include "chrome/browser/devtools/devtools_window.h"
#include "chrome/browser/extensions/devtools_util.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/net/profile_network_context_service.h"
#include "chrome/browser/net/profile_network_context_service_factory.h"
#include "components/keep_alive_registry/keep_alive_registry.h"
#include "components/keep_alive_registry/keep_alive_types.h"
#include "content/nw/src/api/nw_app.h"
#include "content/nw/src/nw_base.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "extensions/browser/app_window/app_window.h"
#include "extensions/browser/app_window/app_window_registry.h"
#include "extensions/browser/app_window/native_app_window.h"
#include "extensions/browser/extension_system.h"
#include "extensions/common/error_utils.h"
#include "net/proxy_resolution/proxy_config.h"
#include "net/proxy_resolution/proxy_config_service_fixed.h"
#include "net/proxy_resolution/configured_proxy_resolution_service.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"

using namespace extensions::nwapi::nw__app;

namespace extensions {
NwAppQuitFunction::NwAppQuitFunction() {

}

NwAppQuitFunction::~NwAppQuitFunction() {
}

void NwAppQuitFunction::DoJob(ExtensionService* service, std::string extension_id) {
  if (base::FeatureList::IsEnabled(::features::kNWNewWin)) {
    chrome::CloseAllBrowsersAndQuit(true);
    // trigger BrowserProcessImpl::Unpin()
    KeepAliveRegistry::GetInstance()->Register(KeepAliveOrigin::APP_CONTROLLER, KeepAliveRestartOption::ENABLED);
    KeepAliveRegistry::GetInstance()->Unregister(KeepAliveOrigin::APP_CONTROLLER, KeepAliveRestartOption::ENABLED);
    return;
  }
  base::ThreadTaskRunnerHandle::Get().get()->PostTask(
                                                      FROM_HERE,
                                                      base::Bind(&ExtensionService::TerminateExtension,
                                                                   service->AsWeakPtr(),
                                                                   extension_id));
}

ExtensionFunction::ResponseAction
NwAppQuitFunction::Run() {
  ExtensionService* service =
    ExtensionSystem::Get(browser_context())->extension_service();
  base::ThreadTaskRunnerHandle::Get().get()->PostTask(
        FROM_HERE,
        base::Bind(&NwAppQuitFunction::DoJob,
                   service,
                   extension_id()));
  return RespondNow(NoArguments());
}

void NwAppCloseAllWindowsFunction::DoJob(AppWindowRegistry* registry, std::string id) {
  if (base::FeatureList::IsEnabled(::features::kNWNewWin)) {
    chrome::CloseAllBrowsers();
  }
  AppWindowRegistry::AppWindowList windows =
    registry->GetAppWindowsForApp(id);

  for (AppWindow* window : windows) {
    if (window->NWCanClose())
      window->GetBaseWindow()->Close();
  }
}

ExtensionFunction::ResponseAction
NwAppCloseAllWindowsFunction::Run() {
  AppWindowRegistry* registry = AppWindowRegistry::Get(browser_context());
  if (!registry)
    return RespondNow(Error(""));
  base::ThreadTaskRunnerHandle::Get().get()->PostTask(
        FROM_HERE,
        base::Bind(&NwAppCloseAllWindowsFunction::DoJob, registry, extension()->id()));

  return RespondNow(NoArguments());
}

ExtensionFunction::ResponseAction
NwAppEnableComponentFunction::Run() {
#if BUILDFLAG(ENABLE_WIDEVINE)
  component_updater::RegisterWidevineCdmComponent(g_browser_process->component_updater(),
                                                  base::BindOnce(&NwAppEnableComponentFunction::OnRegistered,
                                                                 this));
  return RespondLater();
#else
  return RespondNow(NoArguments());
#endif
}

void NwAppEnableComponentFunction::OnRegistered() {
  std::string ret;
  const std::vector<component_updater::ComponentInfo> component_list =
    g_browser_process->component_updater()->GetComponents();

  for (const auto& component : component_list) {
    if (component.id == "oimompecagnajdejgnnjijobebaeigek") {
      ret = component.version.GetString();
    }
  }
  auto result_value = std::make_unique<base::Value>(ret);

  Respond(OneArgument(base::Value::FromUniquePtrValue(std::move(result_value))));
}

ExtensionFunction::ResponseAction
  NwAppUpdateComponentFunction::Run() {
  g_browser_process->component_updater()->GetOnDemandUpdater().OnDemandUpdate(
   "oimompecagnajdejgnnjijobebaeigek", component_updater::OnDemandUpdater::Priority::FOREGROUND,
   base::BindOnce(&NwAppUpdateComponentFunction::OnUpdated, this));

  return RespondLater();
}

void NwAppUpdateComponentFunction::OnUpdated(update_client::Error error) {
  bool ret = (error == update_client::Error::NONE);
  auto result_value = std::make_unique<base::Value>(ret);
  if (ret) {
    Respond(OneArgument(base::Value::FromUniquePtrValue(std::move(result_value))));
  } else {
    VLOG(1) << "update component error: " << (int)error;
    Respond(OneArgument(base::Value::FromUniquePtrValue(std::move(result_value))));
  }
}

NwAppGetArgvSyncFunction::NwAppGetArgvSyncFunction() {
}

NwAppGetArgvSyncFunction::~NwAppGetArgvSyncFunction() {
}

bool NwAppGetArgvSyncFunction::RunNWSync(base::ListValue* response, std::string* error) {

  nw::Package* package = nw::package();
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  base::CommandLine::StringVector args = command_line->GetArgs();
  base::CommandLine::StringVector argv = command_line->original_argv();

  // Ignore first non-switch arg if it's not a standalone package.
  bool ignore_arg = !package->self_extract();
  for (unsigned i = 1; i < argv.size(); ++i) {
    if (ignore_arg && args.size() && argv[i] == args[0]) {
      ignore_arg = false;
      continue;
    }

#if defined(OS_WIN)
    response->AppendString(base::WideToUTF16(argv[i]));
#else
    response->AppendString(argv[i]);
#endif
  }
  return true;
}

NwAppClearAppCacheFunction::NwAppClearAppCacheFunction() {
}

NwAppClearAppCacheFunction::~NwAppClearAppCacheFunction() {
}

bool NwAppClearAppCacheFunction::RunNWSync(base::ListValue* response, std::string* error) {
  std::string manifest;
  EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &manifest));

  GURL manifest_url(manifest);
  scoped_refptr<browsing_data::CannedAppCacheHelper> helper(
                                                            new browsing_data::CannedAppCacheHelper(content::BrowserContext::GetDefaultStoragePartition(browser_context())
                                                                                ->GetAppCacheService()));

  helper->DeleteAppCaches(url::Origin::Create(manifest_url));
  return true;
}

NwAppClearCacheFunction::NwAppClearCacheFunction() {
}

NwAppClearCacheFunction::~NwAppClearCacheFunction() {
}

bool NwAppClearCacheFunction::RunNWSync(base::ListValue* response, std::string* error) {
  content::BrowsingDataRemover* remover = content::BrowserContext::GetBrowsingDataRemover(
                                                                                Profile::FromBrowserContext(browser_context()));

  remover->AddObserver(this);
  remover->RemoveAndReply(base::Time(), base::Time::Max(),
                          content::BrowsingDataRemover::DATA_TYPE_CACHE,
                          content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
                          this);
  // BrowsingDataRemover deletes itself.
  base::CurrentThread::ScopedNestableTaskAllower allow;

  run_loop_.Run();
  remover->RemoveObserver(this);
  return true;
}

void NwAppClearCacheFunction::OnBrowsingDataRemoverDone(uint64_t failed_data_types) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  run_loop_.Quit();
}

NwAppSetProxyConfigFunction::NwAppSetProxyConfigFunction() {
}

NwAppSetProxyConfigFunction::~NwAppSetProxyConfigFunction() {
}

bool NwAppSetProxyConfigFunction::RunNWSync(base::ListValue* response, std::string* error) {
  net::ProxyConfigWithAnnotation config;
  std::unique_ptr<nwapi::nw__app::SetProxyConfig::Params> params(
      nwapi::nw__app::SetProxyConfig::Params::Create(*args_));
  EXTENSION_FUNCTION_VALIDATE(params.get());

  std::string pac_url = params->pac_url.get() ? *params->pac_url : "";
  if (!pac_url.empty()) {
    if (pac_url == "<direct>")
      config = net::ProxyConfigWithAnnotation::CreateDirect();
    else if (pac_url == "<auto>")
      config = net::ProxyConfigWithAnnotation(net::ProxyConfig::CreateAutoDetect(), TRAFFIC_ANNOTATION_FOR_TESTS);
    else
      config = net::ProxyConfigWithAnnotation(net::ProxyConfig::CreateFromCustomPacURL(GURL(pac_url)), TRAFFIC_ANNOTATION_FOR_TESTS);
  } else {
    std::string proxy_config;
    net::ProxyConfig pc;
    EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &proxy_config));
    pc.proxy_rules().ParseFromString(proxy_config);
    config = net::ProxyConfigWithAnnotation(pc, TRAFFIC_ANNOTATION_FOR_TESTS);
  }

  Profile* profile = Profile::FromBrowserContext(browser_context());
  auto* profile_network_context =
    ProfileNetworkContextServiceFactory::GetForContext(profile);
  profile_network_context->UpdateProxyConfig(config);
  return true;
}

bool NwAppGetDataPathFunction::RunNWSync(base::ListValue* response, std::string* error) {
  response->AppendString(base::WideToUTF16(browser_context()->GetPath().value()));
  return true;
}

ExtensionFunction::ResponseAction
NwAppCrashBrowserFunction::Run() {
  int* ptr = nullptr;
  *ptr = 1;
  return RespondNow(NoArguments());
}

} // namespace extensions
<commit_msg>fixup! Fix string conversions<commit_after>#include "content/nw/src/api/nw_app_api.h"

#include "build/build_config.h"
#include "third_party/widevine/cdm/buildflags.h"

#include "chrome/browser/lifetime/browser_close_manager.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "content/public/common/content_features.h"

#include "base/command_line.h"
#include "base/memory/ptr_util.h"
#include "base/task/current_thread.h"
#include "base/task/post_task.h"
#include "content/public/browser/browser_task_traits.h"
#include "components/browsing_data/content/appcache_helper.h"
#include "components/browsing_data/content/browsing_data_helper.h"
#include "components/component_updater/component_updater_service.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
#include "chrome/browser/devtools/devtools_window.h"
#include "chrome/browser/extensions/devtools_util.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/net/profile_network_context_service.h"
#include "chrome/browser/net/profile_network_context_service_factory.h"
#include "components/keep_alive_registry/keep_alive_registry.h"
#include "components/keep_alive_registry/keep_alive_types.h"
#include "content/nw/src/api/nw_app.h"
#include "content/nw/src/nw_base.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "extensions/browser/app_window/app_window.h"
#include "extensions/browser/app_window/app_window_registry.h"
#include "extensions/browser/app_window/native_app_window.h"
#include "extensions/browser/extension_system.h"
#include "extensions/common/error_utils.h"
#include "net/proxy_resolution/proxy_config.h"
#include "net/proxy_resolution/proxy_config_service_fixed.h"
#include "net/proxy_resolution/configured_proxy_resolution_service.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"

using namespace extensions::nwapi::nw__app;

namespace extensions {
NwAppQuitFunction::NwAppQuitFunction() {

}

NwAppQuitFunction::~NwAppQuitFunction() {
}

void NwAppQuitFunction::DoJob(ExtensionService* service, std::string extension_id) {
  if (base::FeatureList::IsEnabled(::features::kNWNewWin)) {
    chrome::CloseAllBrowsersAndQuit(true);
    // trigger BrowserProcessImpl::Unpin()
    KeepAliveRegistry::GetInstance()->Register(KeepAliveOrigin::APP_CONTROLLER, KeepAliveRestartOption::ENABLED);
    KeepAliveRegistry::GetInstance()->Unregister(KeepAliveOrigin::APP_CONTROLLER, KeepAliveRestartOption::ENABLED);
    return;
  }
  base::ThreadTaskRunnerHandle::Get().get()->PostTask(
                                                      FROM_HERE,
                                                      base::Bind(&ExtensionService::TerminateExtension,
                                                                   service->AsWeakPtr(),
                                                                   extension_id));
}

ExtensionFunction::ResponseAction
NwAppQuitFunction::Run() {
  ExtensionService* service =
    ExtensionSystem::Get(browser_context())->extension_service();
  base::ThreadTaskRunnerHandle::Get().get()->PostTask(
        FROM_HERE,
        base::Bind(&NwAppQuitFunction::DoJob,
                   service,
                   extension_id()));
  return RespondNow(NoArguments());
}

void NwAppCloseAllWindowsFunction::DoJob(AppWindowRegistry* registry, std::string id) {
  if (base::FeatureList::IsEnabled(::features::kNWNewWin)) {
    chrome::CloseAllBrowsers();
  }
  AppWindowRegistry::AppWindowList windows =
    registry->GetAppWindowsForApp(id);

  for (AppWindow* window : windows) {
    if (window->NWCanClose())
      window->GetBaseWindow()->Close();
  }
}

ExtensionFunction::ResponseAction
NwAppCloseAllWindowsFunction::Run() {
  AppWindowRegistry* registry = AppWindowRegistry::Get(browser_context());
  if (!registry)
    return RespondNow(Error(""));
  base::ThreadTaskRunnerHandle::Get().get()->PostTask(
        FROM_HERE,
        base::Bind(&NwAppCloseAllWindowsFunction::DoJob, registry, extension()->id()));

  return RespondNow(NoArguments());
}

ExtensionFunction::ResponseAction
NwAppEnableComponentFunction::Run() {
#if BUILDFLAG(ENABLE_WIDEVINE)
  component_updater::RegisterWidevineCdmComponent(g_browser_process->component_updater(),
                                                  base::BindOnce(&NwAppEnableComponentFunction::OnRegistered,
                                                                 this));
  return RespondLater();
#else
  return RespondNow(NoArguments());
#endif
}

void NwAppEnableComponentFunction::OnRegistered() {
  std::string ret;
  const std::vector<component_updater::ComponentInfo> component_list =
    g_browser_process->component_updater()->GetComponents();

  for (const auto& component : component_list) {
    if (component.id == "oimompecagnajdejgnnjijobebaeigek") {
      ret = component.version.GetString();
    }
  }
  auto result_value = std::make_unique<base::Value>(ret);

  Respond(OneArgument(base::Value::FromUniquePtrValue(std::move(result_value))));
}

ExtensionFunction::ResponseAction
  NwAppUpdateComponentFunction::Run() {
  g_browser_process->component_updater()->GetOnDemandUpdater().OnDemandUpdate(
   "oimompecagnajdejgnnjijobebaeigek", component_updater::OnDemandUpdater::Priority::FOREGROUND,
   base::BindOnce(&NwAppUpdateComponentFunction::OnUpdated, this));

  return RespondLater();
}

void NwAppUpdateComponentFunction::OnUpdated(update_client::Error error) {
  bool ret = (error == update_client::Error::NONE);
  auto result_value = std::make_unique<base::Value>(ret);
  if (ret) {
    Respond(OneArgument(base::Value::FromUniquePtrValue(std::move(result_value))));
  } else {
    VLOG(1) << "update component error: " << (int)error;
    Respond(OneArgument(base::Value::FromUniquePtrValue(std::move(result_value))));
  }
}

NwAppGetArgvSyncFunction::NwAppGetArgvSyncFunction() {
}

NwAppGetArgvSyncFunction::~NwAppGetArgvSyncFunction() {
}

bool NwAppGetArgvSyncFunction::RunNWSync(base::ListValue* response, std::string* error) {

  nw::Package* package = nw::package();
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  base::CommandLine::StringVector args = command_line->GetArgs();
  base::CommandLine::StringVector argv = command_line->original_argv();

  // Ignore first non-switch arg if it's not a standalone package.
  bool ignore_arg = !package->self_extract();
  for (unsigned i = 1; i < argv.size(); ++i) {
    if (ignore_arg && args.size() && argv[i] == args[0]) {
      ignore_arg = false;
      continue;
    }

#if defined(OS_WIN)
    response->AppendString(base::WideToUTF16(argv[i]));
#else
    response->AppendString(argv[i]);
#endif
  }
  return true;
}

NwAppClearAppCacheFunction::NwAppClearAppCacheFunction() {
}

NwAppClearAppCacheFunction::~NwAppClearAppCacheFunction() {
}

bool NwAppClearAppCacheFunction::RunNWSync(base::ListValue* response, std::string* error) {
  std::string manifest;
  EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &manifest));

  GURL manifest_url(manifest);
  scoped_refptr<browsing_data::CannedAppCacheHelper> helper(
                                                            new browsing_data::CannedAppCacheHelper(content::BrowserContext::GetDefaultStoragePartition(browser_context())
                                                                                ->GetAppCacheService()));

  helper->DeleteAppCaches(url::Origin::Create(manifest_url));
  return true;
}

NwAppClearCacheFunction::NwAppClearCacheFunction() {
}

NwAppClearCacheFunction::~NwAppClearCacheFunction() {
}

bool NwAppClearCacheFunction::RunNWSync(base::ListValue* response, std::string* error) {
  content::BrowsingDataRemover* remover = content::BrowserContext::GetBrowsingDataRemover(
                                                                                Profile::FromBrowserContext(browser_context()));

  remover->AddObserver(this);
  remover->RemoveAndReply(base::Time(), base::Time::Max(),
                          content::BrowsingDataRemover::DATA_TYPE_CACHE,
                          content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
                          this);
  // BrowsingDataRemover deletes itself.
  base::CurrentThread::ScopedNestableTaskAllower allow;

  run_loop_.Run();
  remover->RemoveObserver(this);
  return true;
}

void NwAppClearCacheFunction::OnBrowsingDataRemoverDone(uint64_t failed_data_types) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  run_loop_.Quit();
}

NwAppSetProxyConfigFunction::NwAppSetProxyConfigFunction() {
}

NwAppSetProxyConfigFunction::~NwAppSetProxyConfigFunction() {
}

bool NwAppSetProxyConfigFunction::RunNWSync(base::ListValue* response, std::string* error) {
  net::ProxyConfigWithAnnotation config;
  std::unique_ptr<nwapi::nw__app::SetProxyConfig::Params> params(
      nwapi::nw__app::SetProxyConfig::Params::Create(*args_));
  EXTENSION_FUNCTION_VALIDATE(params.get());

  std::string pac_url = params->pac_url.get() ? *params->pac_url : "";
  if (!pac_url.empty()) {
    if (pac_url == "<direct>")
      config = net::ProxyConfigWithAnnotation::CreateDirect();
    else if (pac_url == "<auto>")
      config = net::ProxyConfigWithAnnotation(net::ProxyConfig::CreateAutoDetect(), TRAFFIC_ANNOTATION_FOR_TESTS);
    else
      config = net::ProxyConfigWithAnnotation(net::ProxyConfig::CreateFromCustomPacURL(GURL(pac_url)), TRAFFIC_ANNOTATION_FOR_TESTS);
  } else {
    std::string proxy_config;
    net::ProxyConfig pc;
    EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &proxy_config));
    pc.proxy_rules().ParseFromString(proxy_config);
    config = net::ProxyConfigWithAnnotation(pc, TRAFFIC_ANNOTATION_FOR_TESTS);
  }

  Profile* profile = Profile::FromBrowserContext(browser_context());
  auto* profile_network_context =
    ProfileNetworkContextServiceFactory::GetForContext(profile);
  profile_network_context->UpdateProxyConfig(config);
  return true;
}

bool NwAppGetDataPathFunction::RunNWSync(base::ListValue* response, std::string* error) {
#if defined(OS_WIN)
  response->AppendString(base::WideToUTF16(browser_context()->GetPath().value()));
#else
  response->AppendString(browser_context()->GetPath().value());
#endif
  return true;
}

ExtensionFunction::ResponseAction
NwAppCrashBrowserFunction::Run() {
  int* ptr = nullptr;
  *ptr = 1;
  return RespondNow(NoArguments());
}

} // namespace extensions
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2003-2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Steve Reinhardt
 *          Gabe Black
 */

#ifndef __ARCH_ALPHA_IPR_HH__
#define __ARCH_ALPHA_IPR_HH__

namespace AlphaISA
{
    ////////////////////////////////////////////////////////////////////////
    //
    //  Internal Processor Reigsters
    //
    enum md_ipr_names
    {
        RAW_IPR_ISR = 0x100,		// interrupt summary register
        RAW_IPR_ITB_TAG = 0x101,	// ITLB tag register
        RAW_IPR_ITB_PTE = 0x102,	// ITLB page table entry register
        RAW_IPR_ITB_ASN = 0x103,	// ITLB address space register
        RAW_IPR_ITB_PTE_TEMP = 0x104,	// ITLB page table entry temp register
        RAW_IPR_ITB_IA = 0x105,		// ITLB invalidate all register
        RAW_IPR_ITB_IAP = 0x106,	// ITLB invalidate all process register
        RAW_IPR_ITB_IS = 0x107,		// ITLB invalidate select register
        RAW_IPR_SIRR = 0x108,		// software interrupt request register
        RAW_IPR_ASTRR = 0x109,		// asynchronous system trap request register
        RAW_IPR_ASTER = 0x10a,		// asynchronous system trap enable register
        RAW_IPR_EXC_ADDR = 0x10b,	// exception address register
        RAW_IPR_EXC_SUM = 0x10c,	// exception summary register
        RAW_IPR_EXC_MASK = 0x10d,	// exception mask register
        RAW_IPR_PAL_BASE = 0x10e,	// PAL base address register
        RAW_IPR_ICM = 0x10f,		// instruction current mode
        RAW_IPR_IPLR = 0x110,		// interrupt priority level register
        RAW_IPR_INTID = 0x111,		// interrupt ID register
        RAW_IPR_IFAULT_VA_FORM = 0x112,	// formatted faulting virtual addr register
        RAW_IPR_IVPTBR = 0x113,		// virtual page table base register
        RAW_IPR_HWINT_CLR = 0x115,	// H/W interrupt clear register
        RAW_IPR_SL_XMIT = 0x116,	// serial line transmit register
        RAW_IPR_SL_RCV = 0x117,		// serial line receive register
        RAW_IPR_ICSR = 0x118,		// instruction control and status register
        RAW_IPR_IC_FLUSH = 0x119,	// instruction cache flush control
        RAW_IPR_IC_PERR_STAT = 0x11a,	// inst cache parity error status register
        RAW_IPR_PMCTR = 0x11c,		// performance counter register

        // PAL temporary registers...
        // register meanings gleaned from osfpal.s source code
        RAW_IPR_PALtemp0 = 0x140,	// local scratch
        RAW_IPR_PALtemp1 = 0x141,	// local scratch
        RAW_IPR_PALtemp2 = 0x142,	// entUna
        RAW_IPR_PALtemp3 = 0x143,	// CPU specific impure area pointer
        RAW_IPR_PALtemp4 = 0x144,	// memory management temp
        RAW_IPR_PALtemp5 = 0x145,	// memory management temp
        RAW_IPR_PALtemp6 = 0x146,	// memory management temp
        RAW_IPR_PALtemp7 = 0x147,	// entIF
        RAW_IPR_PALtemp8 = 0x148,	// intmask
        RAW_IPR_PALtemp9 = 0x149,	// entSys
        RAW_IPR_PALtemp10 = 0x14a,	// ??
        RAW_IPR_PALtemp11 = 0x14b,	// entInt
        RAW_IPR_PALtemp12 = 0x14c,	// entArith
        RAW_IPR_PALtemp13 = 0x14d,	// reserved for platform specific PAL
        RAW_IPR_PALtemp14 = 0x14e,	// reserved for platform specific PAL
        RAW_IPR_PALtemp15 = 0x14f,	// reserved for platform specific PAL
        RAW_IPR_PALtemp16 = 0x150,	// scratch / whami<7:0> / mces<4:0>
        RAW_IPR_PALtemp17 = 0x151,	// sysval
        RAW_IPR_PALtemp18 = 0x152,	// usp
        RAW_IPR_PALtemp19 = 0x153,	// ksp
        RAW_IPR_PALtemp20 = 0x154,	// PTBR
        RAW_IPR_PALtemp21 = 0x155,	// entMM
        RAW_IPR_PALtemp22 = 0x156,	// kgp
        RAW_IPR_PALtemp23 = 0x157,	// PCBB

        RAW_IPR_DTB_ASN = 0x200,	// DTLB address space number register
        RAW_IPR_DTB_CM = 0x201,		// DTLB current mode register
        RAW_IPR_DTB_TAG = 0x202,	// DTLB tag register
        RAW_IPR_DTB_PTE = 0x203,	// DTLB page table entry register
        RAW_IPR_DTB_PTE_TEMP = 0x204,	// DTLB page table entry temporary register

        RAW_IPR_MM_STAT = 0x205,	// data MMU fault status register
        RAW_IPR_VA = 0x206,		// fault virtual address register
        RAW_IPR_VA_FORM = 0x207,	// formatted virtual address register
        RAW_IPR_MVPTBR = 0x208,		// MTU virtual page table base register
        RAW_IPR_DTB_IAP = 0x209,	// DTLB invalidate all process register
        RAW_IPR_DTB_IA = 0x20a,		// DTLB invalidate all register
        RAW_IPR_DTB_IS = 0x20b,		// DTLB invalidate single register
        RAW_IPR_ALT_MODE = 0x20c,	// alternate mode register
        RAW_IPR_CC = 0x20d,		// cycle counter register
        RAW_IPR_CC_CTL = 0x20e,		// cycle counter control register
        RAW_IPR_MCSR = 0x20f,		// MTU control register

        RAW_IPR_DC_FLUSH = 0x210,
        RAW_IPR_DC_PERR_STAT = 0x212,	// Dcache parity error status register
        RAW_IPR_DC_TEST_CTL = 0x213,	// Dcache test tag control register
        RAW_IPR_DC_TEST_TAG = 0x214,	// Dcache test tag register
        RAW_IPR_DC_TEST_TAG_TEMP = 0x215, // Dcache test tag temporary register
        RAW_IPR_DC_MODE = 0x216,	// Dcache mode register
        RAW_IPR_MAF_MODE = 0x217,	// miss address file mode register

        MaxInternalProcRegs		// number of IPR registers
    };

    enum MiscRegIpr
    {
        //Write only
        MinWriteOnlyIpr,
        IPR_HWINT_CLR = MinWriteOnlyIpr,
        IPR_SL_XMIT,
        IPR_DC_FLUSH,
        IPR_IC_FLUSH,
        IPR_ALT_MODE,
        IPR_DTB_IA,
        IPR_DTB_IAP,
        IPR_ITB_IA,
        MaxWriteOnlyIpr,
        IPR_ITB_IAP = MaxWriteOnlyIpr,

        //Read only
        MinReadOnlyIpr,
        IPR_INTID = MinReadOnlyIpr,
        IPR_SL_RCV,
        IPR_MM_STAT,
        IPR_ITB_PTE_TEMP,
        MaxReadOnlyIpr,
        IPR_DTB_PTE_TEMP = MaxReadOnlyIpr,

        IPR_ISR,
        IPR_ITB_TAG,
        IPR_ITB_PTE,
        IPR_ITB_ASN,
        IPR_ITB_IS,
        IPR_SIRR,
        IPR_ASTRR,
        IPR_ASTER,
        IPR_EXC_ADDR,
        IPR_EXC_SUM,
        IPR_EXC_MASK,
        IPR_PAL_BASE,
        IPR_ICM,
        IPR_IPLR,
        IPR_IFAULT_VA_FORM,
        IPR_IVPTBR,
        IPR_ICSR,
        IPR_IC_PERR_STAT,
        IPR_PMCTR,

        // PAL temporary registers...
        // register meanings gleaned from osfpal.s source code
        IPR_PALtemp0,
        IPR_PALtemp1,
        IPR_PALtemp2,
        IPR_PALtemp3,
        IPR_PALtemp4,
        IPR_PALtemp5,
        IPR_PALtemp6,
        IPR_PALtemp7,
        IPR_PALtemp8,
        IPR_PALtemp9,
        IPR_PALtemp10,
        IPR_PALtemp11,
        IPR_PALtemp12,
        IPR_PALtemp13,
        IPR_PALtemp14,
        IPR_PALtemp15,
        IPR_PALtemp16,
        IPR_PALtemp17,
        IPR_PALtemp18,
        IPR_PALtemp19,
        IPR_PALtemp20,
        IPR_PALtemp21,
        IPR_PALtemp22,
        IPR_PALtemp23,

        IPR_DTB_ASN,
        IPR_DTB_CM,
        IPR_DTB_TAG,
        IPR_DTB_PTE,

        IPR_VA,
        IPR_VA_FORM,
        IPR_MVPTBR,
        IPR_DTB_IS,
        IPR_CC,
        IPR_CC_CTL,
        IPR_MCSR,

        IPR_DC_PERR_STAT,
        IPR_DC_TEST_CTL,
        IPR_DC_TEST_TAG,
        IPR_DC_TEST_TAG_TEMP,
        IPR_DC_MODE,
        IPR_MAF_MODE,

        NumInternalProcRegs		// number of IPR registers
    };

    inline bool IprIsWritable(int index)
    {
        return index < minReadOnlyIpr || index > maxReadOnlyIpr;
    }

    inline bool IprIsReadable(int index)
    {
        return index < minWriteOnlyIpr || index > maxWriteOnlyIpr;
    }

    extern md_ipr_names MiscRegIndexToIpr[NumInternalProcRegs];
    extern int IprToMiscRegIndex[MaxInternalProcRegs];

    void initializeIprTable();
}

#endif
<commit_msg>Fix stupid typo<commit_after>/*
 * Copyright (c) 2003-2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Steve Reinhardt
 *          Gabe Black
 */

#ifndef __ARCH_ALPHA_IPR_HH__
#define __ARCH_ALPHA_IPR_HH__

namespace AlphaISA
{
    ////////////////////////////////////////////////////////////////////////
    //
    //  Internal Processor Reigsters
    //
    enum md_ipr_names
    {
        RAW_IPR_ISR = 0x100,		// interrupt summary register
        RAW_IPR_ITB_TAG = 0x101,	// ITLB tag register
        RAW_IPR_ITB_PTE = 0x102,	// ITLB page table entry register
        RAW_IPR_ITB_ASN = 0x103,	// ITLB address space register
        RAW_IPR_ITB_PTE_TEMP = 0x104,	// ITLB page table entry temp register
        RAW_IPR_ITB_IA = 0x105,		// ITLB invalidate all register
        RAW_IPR_ITB_IAP = 0x106,	// ITLB invalidate all process register
        RAW_IPR_ITB_IS = 0x107,		// ITLB invalidate select register
        RAW_IPR_SIRR = 0x108,		// software interrupt request register
        RAW_IPR_ASTRR = 0x109,		// asynchronous system trap request register
        RAW_IPR_ASTER = 0x10a,		// asynchronous system trap enable register
        RAW_IPR_EXC_ADDR = 0x10b,	// exception address register
        RAW_IPR_EXC_SUM = 0x10c,	// exception summary register
        RAW_IPR_EXC_MASK = 0x10d,	// exception mask register
        RAW_IPR_PAL_BASE = 0x10e,	// PAL base address register
        RAW_IPR_ICM = 0x10f,		// instruction current mode
        RAW_IPR_IPLR = 0x110,		// interrupt priority level register
        RAW_IPR_INTID = 0x111,		// interrupt ID register
        RAW_IPR_IFAULT_VA_FORM = 0x112,	// formatted faulting virtual addr register
        RAW_IPR_IVPTBR = 0x113,		// virtual page table base register
        RAW_IPR_HWINT_CLR = 0x115,	// H/W interrupt clear register
        RAW_IPR_SL_XMIT = 0x116,	// serial line transmit register
        RAW_IPR_SL_RCV = 0x117,		// serial line receive register
        RAW_IPR_ICSR = 0x118,		// instruction control and status register
        RAW_IPR_IC_FLUSH = 0x119,	// instruction cache flush control
        RAW_IPR_IC_PERR_STAT = 0x11a,	// inst cache parity error status register
        RAW_IPR_PMCTR = 0x11c,		// performance counter register

        // PAL temporary registers...
        // register meanings gleaned from osfpal.s source code
        RAW_IPR_PALtemp0 = 0x140,	// local scratch
        RAW_IPR_PALtemp1 = 0x141,	// local scratch
        RAW_IPR_PALtemp2 = 0x142,	// entUna
        RAW_IPR_PALtemp3 = 0x143,	// CPU specific impure area pointer
        RAW_IPR_PALtemp4 = 0x144,	// memory management temp
        RAW_IPR_PALtemp5 = 0x145,	// memory management temp
        RAW_IPR_PALtemp6 = 0x146,	// memory management temp
        RAW_IPR_PALtemp7 = 0x147,	// entIF
        RAW_IPR_PALtemp8 = 0x148,	// intmask
        RAW_IPR_PALtemp9 = 0x149,	// entSys
        RAW_IPR_PALtemp10 = 0x14a,	// ??
        RAW_IPR_PALtemp11 = 0x14b,	// entInt
        RAW_IPR_PALtemp12 = 0x14c,	// entArith
        RAW_IPR_PALtemp13 = 0x14d,	// reserved for platform specific PAL
        RAW_IPR_PALtemp14 = 0x14e,	// reserved for platform specific PAL
        RAW_IPR_PALtemp15 = 0x14f,	// reserved for platform specific PAL
        RAW_IPR_PALtemp16 = 0x150,	// scratch / whami<7:0> / mces<4:0>
        RAW_IPR_PALtemp17 = 0x151,	// sysval
        RAW_IPR_PALtemp18 = 0x152,	// usp
        RAW_IPR_PALtemp19 = 0x153,	// ksp
        RAW_IPR_PALtemp20 = 0x154,	// PTBR
        RAW_IPR_PALtemp21 = 0x155,	// entMM
        RAW_IPR_PALtemp22 = 0x156,	// kgp
        RAW_IPR_PALtemp23 = 0x157,	// PCBB

        RAW_IPR_DTB_ASN = 0x200,	// DTLB address space number register
        RAW_IPR_DTB_CM = 0x201,		// DTLB current mode register
        RAW_IPR_DTB_TAG = 0x202,	// DTLB tag register
        RAW_IPR_DTB_PTE = 0x203,	// DTLB page table entry register
        RAW_IPR_DTB_PTE_TEMP = 0x204,	// DTLB page table entry temporary register

        RAW_IPR_MM_STAT = 0x205,	// data MMU fault status register
        RAW_IPR_VA = 0x206,		// fault virtual address register
        RAW_IPR_VA_FORM = 0x207,	// formatted virtual address register
        RAW_IPR_MVPTBR = 0x208,		// MTU virtual page table base register
        RAW_IPR_DTB_IAP = 0x209,	// DTLB invalidate all process register
        RAW_IPR_DTB_IA = 0x20a,		// DTLB invalidate all register
        RAW_IPR_DTB_IS = 0x20b,		// DTLB invalidate single register
        RAW_IPR_ALT_MODE = 0x20c,	// alternate mode register
        RAW_IPR_CC = 0x20d,		// cycle counter register
        RAW_IPR_CC_CTL = 0x20e,		// cycle counter control register
        RAW_IPR_MCSR = 0x20f,		// MTU control register

        RAW_IPR_DC_FLUSH = 0x210,
        RAW_IPR_DC_PERR_STAT = 0x212,	// Dcache parity error status register
        RAW_IPR_DC_TEST_CTL = 0x213,	// Dcache test tag control register
        RAW_IPR_DC_TEST_TAG = 0x214,	// Dcache test tag register
        RAW_IPR_DC_TEST_TAG_TEMP = 0x215, // Dcache test tag temporary register
        RAW_IPR_DC_MODE = 0x216,	// Dcache mode register
        RAW_IPR_MAF_MODE = 0x217,	// miss address file mode register

        MaxInternalProcRegs		// number of IPR registers
    };

    enum MiscRegIpr
    {
        //Write only
        MinWriteOnlyIpr,
        IPR_HWINT_CLR = MinWriteOnlyIpr,
        IPR_SL_XMIT,
        IPR_DC_FLUSH,
        IPR_IC_FLUSH,
        IPR_ALT_MODE,
        IPR_DTB_IA,
        IPR_DTB_IAP,
        IPR_ITB_IA,
        MaxWriteOnlyIpr,
        IPR_ITB_IAP = MaxWriteOnlyIpr,

        //Read only
        MinReadOnlyIpr,
        IPR_INTID = MinReadOnlyIpr,
        IPR_SL_RCV,
        IPR_MM_STAT,
        IPR_ITB_PTE_TEMP,
        MaxReadOnlyIpr,
        IPR_DTB_PTE_TEMP = MaxReadOnlyIpr,

        IPR_ISR,
        IPR_ITB_TAG,
        IPR_ITB_PTE,
        IPR_ITB_ASN,
        IPR_ITB_IS,
        IPR_SIRR,
        IPR_ASTRR,
        IPR_ASTER,
        IPR_EXC_ADDR,
        IPR_EXC_SUM,
        IPR_EXC_MASK,
        IPR_PAL_BASE,
        IPR_ICM,
        IPR_IPLR,
        IPR_IFAULT_VA_FORM,
        IPR_IVPTBR,
        IPR_ICSR,
        IPR_IC_PERR_STAT,
        IPR_PMCTR,

        // PAL temporary registers...
        // register meanings gleaned from osfpal.s source code
        IPR_PALtemp0,
        IPR_PALtemp1,
        IPR_PALtemp2,
        IPR_PALtemp3,
        IPR_PALtemp4,
        IPR_PALtemp5,
        IPR_PALtemp6,
        IPR_PALtemp7,
        IPR_PALtemp8,
        IPR_PALtemp9,
        IPR_PALtemp10,
        IPR_PALtemp11,
        IPR_PALtemp12,
        IPR_PALtemp13,
        IPR_PALtemp14,
        IPR_PALtemp15,
        IPR_PALtemp16,
        IPR_PALtemp17,
        IPR_PALtemp18,
        IPR_PALtemp19,
        IPR_PALtemp20,
        IPR_PALtemp21,
        IPR_PALtemp22,
        IPR_PALtemp23,

        IPR_DTB_ASN,
        IPR_DTB_CM,
        IPR_DTB_TAG,
        IPR_DTB_PTE,

        IPR_VA,
        IPR_VA_FORM,
        IPR_MVPTBR,
        IPR_DTB_IS,
        IPR_CC,
        IPR_CC_CTL,
        IPR_MCSR,

        IPR_DC_PERR_STAT,
        IPR_DC_TEST_CTL,
        IPR_DC_TEST_TAG,
        IPR_DC_TEST_TAG_TEMP,
        IPR_DC_MODE,
        IPR_MAF_MODE,

        NumInternalProcRegs		// number of IPR registers
    };

    inline bool IprIsWritable(int index)
    {
        return index < MinReadOnlyIpr || index > MaxReadOnlyIpr;
    }

    inline bool IprIsReadable(int index)
    {
        return index < MinWriteOnlyIpr || index > MaxWriteOnlyIpr;
    }

    extern md_ipr_names MiscRegIndexToIpr[NumInternalProcRegs];
    extern int IprToMiscRegIndex[MaxInternalProcRegs];

    void initializeIprTable();
}

#endif
<|endoftext|>


<commit_before>/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/

#include <blas.hpp>

#ifdef USE_F77_BLAS
#define ADD_
#include <cblas_f77.h>

static char transChar(CBLAS_TRANSPOSE Trans)
{
    switch(Trans) {
        case CblasNoTrans:      return 'N';
        case CblasTrans:        return 'T';
        case CblasConjTrans:    return 'C';
        default:                return '\0';
    }
}

#define GEMM_F77(X, TS, TV, TY)                                 \
    void cblas_##X##gemm(                                       \
        const CBLAS_ORDER Order, const CBLAS_TRANSPOSE TransA,  \
        const CBLAS_TRANSPOSE TransB, const int M, const int N, \
        const int K, const TS alpha, const TV *A,               \
        const int lda, const TV *B, const int ldb,              \
        const TS beta, TV *C, const int ldc)                    \
    {                                                           \
        char aT = transChar(TransA);                            \
        char bT = transChar(TransB);                            \
        X##gemm_(&aT, &bT, &M, &N, &K,                          \
                 (const TY *)ADDR(alpha), (const TY *)A, &lda,  \
                 (const TY *)B, &ldb,                           \
                 (const TY *)ADDR(beta), (TY *)C, &ldc);        \
    }                                                           \
    void cblas_##X##gemv(                                       \
        const CBLAS_ORDER order, const CBLAS_TRANSPOSE TransA,  \
        const int M, const int N,                               \
        const TS alpha, const TV *A, const int lda,             \
        const TV *X, const int incX, const TS beta,             \
        TV *Y, const int incY)                                  \
    {                                                           \
        char aT = transChar(TransA);                            \
        X##gemv_(&aT, &M, &N,                                   \
                 (const TY *)ADDR(alpha), (const TY *)A, &lda,  \
                 (const TY *)X, &incX,                          \
                 (const TY *)ADDR(beta), (TY *)Y, &incY);       \
    }                                                           \
    void cblas_##X##axpy(                                       \
        const int N, const TS alpha,                            \
        const TV *X, const int incX,                            \
        TV *Y, const int incY)                                  \
    {                                                           \
        X##axpy_(&N,                                            \
                 (const TY *)ADDR(alpha),                       \
                 (const TY *)X, &incX,                          \
                 (TY *)Y, &incY);                               \
    }                                                           \
    void cblas_##X##scal(                                       \
        const int N, const TS alpha,                            \
        TV *X, const int incX)                                  \
    {                                                           \
        X##scal_(&N,                                            \
                 (const TY *)ADDR(alpha),                       \
                 (TY *)X, &incX);                               \
    }                                                           \

#define ADDR(val) &val
GEMM_F77(s, float, float, float)
GEMM_F77(d, double, double, double)
#undef ADDR

#define ADDR(val) val
GEMM_F77(c, void *, void, float)
GEMM_F77(z, void *, void, double)
#undef ADDR

#endif
<commit_msg>fix: opencl backend alone build fails due to this missing header<commit_after>/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/

#include <blas.hpp>

#ifdef USE_F77_BLAS
#define ADD_
#include <cblas.h>
#include <cblas_f77.h>

static char transChar(CBLAS_TRANSPOSE Trans)
{
    switch(Trans) {
        case CblasNoTrans:      return 'N';
        case CblasTrans:        return 'T';
        case CblasConjTrans:    return 'C';
        default:                return '\0';
    }
}

#define GEMM_F77(X, TS, TV, TY)                                 \
    void cblas_##X##gemm(                                       \
        const CBLAS_ORDER Order, const CBLAS_TRANSPOSE TransA,  \
        const CBLAS_TRANSPOSE TransB, const int M, const int N, \
        const int K, const TS alpha, const TV *A,               \
        const int lda, const TV *B, const int ldb,              \
        const TS beta, TV *C, const int ldc)                    \
    {                                                           \
        char aT = transChar(TransA);                            \
        char bT = transChar(TransB);                            \
        X##gemm_(&aT, &bT, &M, &N, &K,                          \
                 (const TY *)ADDR(alpha), (const TY *)A, &lda,  \
                 (const TY *)B, &ldb,                           \
                 (const TY *)ADDR(beta), (TY *)C, &ldc);        \
    }                                                           \
    void cblas_##X##gemv(                                       \
        const CBLAS_ORDER order, const CBLAS_TRANSPOSE TransA,  \
        const int M, const int N,                               \
        const TS alpha, const TV *A, const int lda,             \
        const TV *X, const int incX, const TS beta,             \
        TV *Y, const int incY)                                  \
    {                                                           \
        char aT = transChar(TransA);                            \
        X##gemv_(&aT, &M, &N,                                   \
                 (const TY *)ADDR(alpha), (const TY *)A, &lda,  \
                 (const TY *)X, &incX,                          \
                 (const TY *)ADDR(beta), (TY *)Y, &incY);       \
    }                                                           \
    void cblas_##X##axpy(                                       \
        const int N, const TS alpha,                            \
        const TV *X, const int incX,                            \
        TV *Y, const int incY)                                  \
    {                                                           \
        X##axpy_(&N,                                            \
                 (const TY *)ADDR(alpha),                       \
                 (const TY *)X, &incX,                          \
                 (TY *)Y, &incY);                               \
    }                                                           \
    void cblas_##X##scal(                                       \
        const int N, const TS alpha,                            \
        TV *X, const int incX)                                  \
    {                                                           \
        X##scal_(&N,                                            \
                 (const TY *)ADDR(alpha),                       \
                 (TY *)X, &incX);                               \
    }                                                           \

#define ADDR(val) &val
GEMM_F77(s, float, float, float)
GEMM_F77(d, double, double, double)
#undef ADDR

#define ADDR(val) val
GEMM_F77(c, void *, void, float)
GEMM_F77(z, void *, void, double)
#undef ADDR

#endif
<|endoftext|>