<commit_before>#include "debug.h"
#include "paging.h"
#include "screen.h"
#include "shell.h"
#include "stdlib.h"
#include "string.h"
#include "timer.h"

class Command
{
public:
    virtual const char* getName() = 0;

    virtual const char* getHelp() = 0;

    virtual void execute() = 0;
};

class ClearCommand : public Command
{
public:
    const char* getName() override
    {
        return "clear";
    }

    const char* getHelp() override
    {
        return "Clears the screen\n";
    }

    void execute() override
    {
        if (strtok(nullptr, " ") != nullptr)
        {
            screen << "Unexpected arguments\n";
        }
        else
        {
            screen.clear();
        }
    }
} clearCmd;

class ReadCommand : public Command
{
public:
    const char* getName() override
    {
        return "read";
    }

    const char* getHelp() override
    {
        return
R"(Reads a byte from memory
)";
    }

    void execute() override
    {
        char* arg = strtok(nullptr, " ");
        if (arg == nullptr)
        {
            screen << "Not enough arguments\n";
        }
        else if (strtok(nullptr, " ") != nullptr)
        {
            screen << "Too many arguments\n";
        }
        else
        {
            char* str = nullptr;
            long addr = strtol(arg, &str, 16);
            if (str == nullptr || *str != '\0')
            {
                screen << "Argument is not a valid hexadecimal number\n";
            }
            else
            {
                uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
                uint8_t value = *ptr;
                screen << os::Screen::hex
                       << os::Screen::setfill('0')
                       << os::Screen::setw(2)
                       << value
                       << os::Screen::setfill(' ')
                       << os::Screen::dec
                       << '\n';
            }
        }
    }
} readCmd;

class SetCommand : public Command
{
public:
    const char* getName() override
    {
        return "set";
    }

    const char* getHelp() override
    {
        return
R"(Changes config options:

set bg <0-15>
    Set background color

set fg <0-15>
    Set foreground color
)";
    }

    void execute() override
    {
        char* arg = strtok(nullptr, " ");
        if (arg == nullptr)
        {
            screen << "Not enough arguments\n";
        }
        else if (strcmp(arg, "bg") == 0)
        {
            char* colorStr = strtok(nullptr, " ");
            if (colorStr == nullptr)
            {
                screen << "No color given\n";
            }
            else
            {
                int color = atoi(colorStr);
                if (color < 0 || color > 15)
                {
                    screen << "Invalid color\n";
                }
                else
                {
                    screen.setBackgroundColor(static_cast<os::Screen::EColor>(color));
                }
            }
        }
        else if (strcmp(arg, "fg") == 0)
        {
            char* colorStr = strtok(nullptr, " ");
            if (colorStr == nullptr)
            {
                screen << "No color given\n";
            }
            else
            {
                int color = atoi(colorStr);
                if (color < 0 || color > 15)
                {
                    screen << "Invalid color\n";
                }
                else
                {
                    screen.setForegroundColor(static_cast<os::Screen::EColor>(color));
                }
            }
        }
        else
        {
            screen << "Unexpected argument\n";
        }
    }
} setCmd;

class ShowCommand : public Command
{
public:
    ShowCommand() :
        mbootInfo(nullptr)
    {
    }

    void setMbootInfo(const multiboot_info* mbootInfoPtr)
    {
        mbootInfo = mbootInfoPtr;
    }

    const char* getName() override
    {
        return "show";
    }

    const char* getHelp() override
    {
        return
R"(Displays information:

show drives [all|master|slave]
    List drives

show mboot info
    Display general multiboot information
show mboot mod
    Display multiboot module information
show mboot mem
    Display multiboot memory map
show mboot drives
    Display multiboot drive information

show pagedir <start index> [end index]
    Display page directory entries, index range: 0-1023
show pagetab <page dir index> <start index> [end index]
    Display page table entries, index range: 0-1023

show ticks
    Display timer ticks since system boot
)";
    }

    void execute() override
    {
        char* arg1 = strtok(nullptr, " ");
        if (arg1 == nullptr)
        {
            screen << "Not enough arguments\n";
        }
        else if (strcmp(arg1, "drives") == 0)
        {
            char* arg2 = strtok(nullptr, " ");
            char* arg3 = strtok(nullptr, " ");
            if (arg3 != nullptr)
            {
                screen << "Too many arguments\n";
            }
            else if (arg2 == nullptr || strcmp(arg2, "all") == 0)
            {
                printDrives(true, true);
            }
            else if (strcmp(arg2, "master") == 0)
            {
                printDrives(true, false);
            }
            else if (strcmp(arg2, "slave") == 0)
            {
                printDrives(false, true);
            }
            else
            {
                screen << "Unknown argument: \"" << arg2 << "\"\n";
            }
        }
        else if (strcmp(arg1, "mboot") == 0)
        {
            char* arg2 = strtok(nullptr, " ");
            if (arg2 == nullptr)
            {
                screen << "Not enough arguments\n";
            }
            else if (strcmp(arg2, "info") == 0)
            {
                printMultibootInfo(mbootInfo);
            }
            else if (strcmp(arg2, "mem") == 0)
            {
                printMultibootMemMap(mbootInfo->mmap_addr, mbootInfo->mmap_length);
            }
            else if (strcmp(arg2, "mod") == 0)
            {
                printMultibootModules(mbootInfo->mods_addr, mbootInfo->mods_count);
            }
            else if (strcmp(arg2, "drives") == 0)
            {
                printMultibootDrives(mbootInfo->drives_addr, mbootInfo->drives_length);
            }
            else
            {
                screen << "Unexpected argument\n";
            }
        }
        else if (strcmp(arg1, "pagedir") == 0)
        {
            char* arg2 = strtok(nullptr, " ");
            if (arg2 == nullptr)
            {
                screen << "Not enough arguments\n";
            }
            else
            {
                int startIdx = atoi(arg2);
                int endIdx = startIdx;

                char* arg3 = strtok(nullptr, " ");
                if (arg3 != nullptr)
                {
                    endIdx = atoi(arg3);
                }

                if (startIdx < 0 || startIdx >= 1024)
                {
                    screen << "Invalid start index\n";
                }
                else if (endIdx < 0 || endIdx >= 1024)
                {
                    screen << "Invalid end index\n";
                }
                else
                {
                    printPageDir(startIdx, endIdx);
                }
            }
        }
        else if (strcmp(arg1, "pagetab") == 0)
        {
            char* arg2 = strtok(nullptr, " ");
            char* arg3 = strtok(nullptr, " ");
            if (arg2 == nullptr || arg3 == nullptr)
            {
                screen << "Not enough arguments\n";
            }
            else
            {
                int pageDirIdx = atoi(arg2);
                int startIdx = atoi(arg3);
                int endIdx = startIdx;

                char* arg4 = strtok(nullptr, " ");
                if (arg4 != nullptr)
                {
                    endIdx = atoi(arg4);
                }

                if (startIdx < 0 || startIdx >= 1024)
                {
                    screen << "Invalid start index\n";
                }
                else if (endIdx < 0 || endIdx >= 1024)
                {
                    screen << "Invalid end index\n";
                }
                else
                {
                    printPageTable(pageDirIdx, startIdx, endIdx);
                }
            }
        }
        else if (strcmp(arg1, "smile") == 0 || strcmp(arg1, "smiley") == 0)
        {
            for (int i = 0; i < 20; ++i)
            {
                screen << "\1 \2 ";
            }
        }
        else if (strcmp(arg1, "ticks") == 0)
        {
            char* arg2 = strtok(nullptr, " ");
            if (arg2 != nullptr)
            {
                screen << "Unexpected argument \"" << arg2 << "\"\n";
            }
            else
            {
                screen << os::Timer::getTicks() << '\n';
            }
        }
        else
        {
            screen << "Unexpected argument\n";
        }
    }

private:
    const multiboot_info* mbootInfo;
} showCmd;

class WriteCommand : public Command
{
public:
    const char* getName() override
    {
        return "write";
    }

    const char* getHelp() override
    {
        return
R"(Writes a byte to memory
)";
    }

    void execute() override
    {
        char* addrArg = strtok(nullptr, " ");
        char* valArg = strtok(nullptr, " ");
        if (addrArg == nullptr || valArg == nullptr)
        {
            screen << "Not enough arguments\n";
        }
        else if (strtok(nullptr, " ") != nullptr)
        {
            screen << "Too many arguments\n";
        }
        else
        {
            bool ok = true;

            char* str = nullptr;
            long addr = strtol(addrArg, &str, 16);
            if (str == nullptr || *str != '\0')
            {
                screen << "Address is not a valid hexadecimal number\n";
                ok = false;
            }

            str = nullptr;
            uint8_t val = strtol(valArg, &str, 16);
            if (str == nullptr || *str != '\0')
            {
                screen << "Value is not a valid number\n";
                ok = false;
            }

            if (ok)
            {
                uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
                *ptr = val;
            }
        }
    }
} writeCmd;

Command* Shell::COMMANDS[NUM_COMMANDS] =
{
    &clearCmd,
    &readCmd,
    &setCmd,
    &showCmd,
    &writeCmd,
};

Shell::Shell(const multiboot_info* mbootInfoPtr) :
    mbootInfo(mbootInfoPtr)
{
    showCmd.setMbootInfo(mbootInfo);

    prompt();
}

void Shell::update()
{
    char ch;
    bool avail = screen.read(ch);
    while (avail)
    {
        processChar(ch);

        avail = screen.read(ch);
    }
}

void Shell::prompt()
{
    screen << "> ";
}

void Shell::processChar(char ch)
{
    if (ch == '\n')
    {
        screen << ch;
        cmd[cmdIdx] = '\0';
        processCmd();
    }
    else if (ch == '\b')
    {
        if (cmdIdx > 0)
        {
            // clear the previous char
            screen << "\b \b";
            --cmdIdx;
        }
    }
    else if (cmdIdx == CMD_MAX_SIZE)
    {
        screen << ch;
        screen << "\nError: Command too long\n";
        resetCmd();
        prompt();
    }
    else
    {
        screen << ch;
        cmd[cmdIdx++] = ch;
    }
}

void Shell::processCmd()
{
    char* token = strtok(cmd, " ");
    if (token != nullptr)
    {
        bool found = false;
        if (strcmp(token, "help") == 0)
        {
            found = true;
            displayHelp();
        }

        // look for command object
        if (!found)
        {
            for (unsigned int i = 0; i < NUM_COMMANDS; ++i)
            {
                Command* cmd = COMMANDS[i];
                if (strcmp(token, cmd->getName()) == 0)
                {
                    cmd->execute();
                    found = true;
                    break;
                }
            }

        }

        // look for program
        if (!found)
        {
            uint32_t progAddr = 0;
            found = findProgram(token, progAddr);
            if (found)
            {
                runProgram(progAddr);
            }
        }

        if (!found)
        {
            screen << "Unknown command\n";
        }
    }

    resetCmd();
    prompt();
}

bool Shell::findProgram(const char* name, uint32_t& progAddr)
{
    bool found = false;
    uint32_t addr = mbootInfo->mods_addr;
    uint32_t count = mbootInfo->mods_count;

    for (uint32_t i = 0; i < count; ++i)
    {
        // get module info struct
        const multiboot_mod_list* module = reinterpret_cast<const multiboot_mod_list*>(addr);

        // check if name matches
        const char* modName = reinterpret_cast<const char*>(module->cmdline);
        if (strcmp(name, modName) == 0)
        {
            progAddr = module->mod_start;
            found = true;
            break;
        }

        addr += sizeof(multiboot_mod_list);
    }

    return found;
}

void Shell::runProgram(uint32_t addr)
{
    programPtr program = reinterpret_cast<programPtr>(addr);
    int rc = program();
    screen << "Return code: " << rc << '\n';
}

void Shell::displayHelp()
{
    char* arg = strtok(nullptr, " ");

    // if no argument was given, list the commands
    if (arg == nullptr)
    {
        screen << "Commands:\n";
        for (unsigned int i = 0; i < NUM_COMMANDS; ++i)
        {
            screen << COMMANDS[i]->getName() << '\n';
        }
    }
    else if (strtok(nullptr, " ") != nullptr)
    {
        screen << "Only expected one argument\n";
    }
    else if (strcmp(arg, "help") == 0)
    {
        screen << "Displays help for commands\n";
    }
    else
    {
        bool found = false;
        for (unsigned int i = 0; i < NUM_COMMANDS; ++i)
        {
            Command* cmd = COMMANDS[i];
            if (strcmp(arg, cmd->getName()) == 0)
            {
                screen << cmd->getHelp();
                found = true;
                break;
            }
        }

        if (!found)
        {
            screen << '"' << arg << "\" is not a command\n";
        }
    }
}

void Shell::resetCmd()
{
    cmdIdx = 0;
}
<commit_msg>Adding kernel virtual base to module addresses<commit_after>#include "debug.h"
#include "paging.h"
#include "screen.h"
#include "shell.h"
#include "stdlib.h"
#include "string.h"
#include "system.h"
#include "timer.h"

class Command
{
public:
    virtual const char* getName() = 0;

    virtual const char* getHelp() = 0;

    virtual void execute() = 0;
};

class ClearCommand : public Command
{
public:
    const char* getName() override
    {
        return "clear";
    }

    const char* getHelp() override
    {
        return "Clears the screen\n";
    }

    void execute() override
    {
        if (strtok(nullptr, " ") != nullptr)
        {
            screen << "Unexpected arguments\n";
        }
        else
        {
            screen.clear();
        }
    }
} clearCmd;

class ReadCommand : public Command
{
public:
    const char* getName() override
    {
        return "read";
    }

    const char* getHelp() override
    {
        return
R"(Reads a byte from memory
)";
    }

    void execute() override
    {
        char* arg = strtok(nullptr, " ");
        if (arg == nullptr)
        {
            screen << "Not enough arguments\n";
        }
        else if (strtok(nullptr, " ") != nullptr)
        {
            screen << "Too many arguments\n";
        }
        else
        {
            char* str = nullptr;
            long addr = strtol(arg, &str, 16);
            if (str == nullptr || *str != '\0')
            {
                screen << "Argument is not a valid hexadecimal number\n";
            }
            else
            {
                uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
                uint8_t value = *ptr;
                screen << os::Screen::hex
                       << os::Screen::setfill('0')
                       << os::Screen::setw(2)
                       << value
                       << os::Screen::setfill(' ')
                       << os::Screen::dec
                       << '\n';
            }
        }
    }
} readCmd;

class SetCommand : public Command
{
public:
    const char* getName() override
    {
        return "set";
    }

    const char* getHelp() override
    {
        return
R"(Changes config options:

set bg <0-15>
    Set background color

set fg <0-15>
    Set foreground color
)";
    }

    void execute() override
    {
        char* arg = strtok(nullptr, " ");
        if (arg == nullptr)
        {
            screen << "Not enough arguments\n";
        }
        else if (strcmp(arg, "bg") == 0)
        {
            char* colorStr = strtok(nullptr, " ");
            if (colorStr == nullptr)
            {
                screen << "No color given\n";
            }
            else
            {
                int color = atoi(colorStr);
                if (color < 0 || color > 15)
                {
                    screen << "Invalid color\n";
                }
                else
                {
                    screen.setBackgroundColor(static_cast<os::Screen::EColor>(color));
                }
            }
        }
        else if (strcmp(arg, "fg") == 0)
        {
            char* colorStr = strtok(nullptr, " ");
            if (colorStr == nullptr)
            {
                screen << "No color given\n";
            }
            else
            {
                int color = atoi(colorStr);
                if (color < 0 || color > 15)
                {
                    screen << "Invalid color\n";
                }
                else
                {
                    screen.setForegroundColor(static_cast<os::Screen::EColor>(color));
                }
            }
        }
        else
        {
            screen << "Unexpected argument\n";
        }
    }
} setCmd;

class ShowCommand : public Command
{
public:
    ShowCommand() :
        mbootInfo(nullptr)
    {
    }

    void setMbootInfo(const multiboot_info* mbootInfoPtr)
    {
        mbootInfo = mbootInfoPtr;
    }

    const char* getName() override
    {
        return "show";
    }

    const char* getHelp() override
    {
        return
R"(Displays information:

show drives [all|master|slave]
    List drives

show mboot info
    Display general multiboot information
show mboot mod
    Display multiboot module information
show mboot mem
    Display multiboot memory map
show mboot drives
    Display multiboot drive information

show pagedir <start index> [end index]
    Display page directory entries, index range: 0-1023
show pagetab <page dir index> <start index> [end index]
    Display page table entries, index range: 0-1023

show ticks
    Display timer ticks since system boot
)";
    }

    void execute() override
    {
        char* arg1 = strtok(nullptr, " ");
        if (arg1 == nullptr)
        {
            screen << "Not enough arguments\n";
        }
        else if (strcmp(arg1, "drives") == 0)
        {
            char* arg2 = strtok(nullptr, " ");
            char* arg3 = strtok(nullptr, " ");
            if (arg3 != nullptr)
            {
                screen << "Too many arguments\n";
            }
            else if (arg2 == nullptr || strcmp(arg2, "all") == 0)
            {
                printDrives(true, true);
            }
            else if (strcmp(arg2, "master") == 0)
            {
                printDrives(true, false);
            }
            else if (strcmp(arg2, "slave") == 0)
            {
                printDrives(false, true);
            }
            else
            {
                screen << "Unknown argument: \"" << arg2 << "\"\n";
            }
        }
        else if (strcmp(arg1, "mboot") == 0)
        {
            char* arg2 = strtok(nullptr, " ");
            if (arg2 == nullptr)
            {
                screen << "Not enough arguments\n";
            }
            else if (strcmp(arg2, "info") == 0)
            {
                printMultibootInfo(mbootInfo);
            }
            else if (strcmp(arg2, "mem") == 0)
            {
                printMultibootMemMap(mbootInfo->mmap_addr, mbootInfo->mmap_length);
            }
            else if (strcmp(arg2, "mod") == 0)
            {
                printMultibootModules(mbootInfo->mods_addr, mbootInfo->mods_count);
            }
            else if (strcmp(arg2, "drives") == 0)
            {
                printMultibootDrives(mbootInfo->drives_addr, mbootInfo->drives_length);
            }
            else
            {
                screen << "Unexpected argument\n";
            }
        }
        else if (strcmp(arg1, "pagedir") == 0)
        {
            char* arg2 = strtok(nullptr, " ");
            if (arg2 == nullptr)
            {
                screen << "Not enough arguments\n";
            }
            else
            {
                int startIdx = atoi(arg2);
                int endIdx = startIdx;

                char* arg3 = strtok(nullptr, " ");
                if (arg3 != nullptr)
                {
                    endIdx = atoi(arg3);
                }

                if (startIdx < 0 || startIdx >= 1024)
                {
                    screen << "Invalid start index\n";
                }
                else if (endIdx < 0 || endIdx >= 1024)
                {
                    screen << "Invalid end index\n";
                }
                else
                {
                    printPageDir(startIdx, endIdx);
                }
            }
        }
        else if (strcmp(arg1, "pagetab") == 0)
        {
            char* arg2 = strtok(nullptr, " ");
            char* arg3 = strtok(nullptr, " ");
            if (arg2 == nullptr || arg3 == nullptr)
            {
                screen << "Not enough arguments\n";
            }
            else
            {
                int pageDirIdx = atoi(arg2);
                int startIdx = atoi(arg3);
                int endIdx = startIdx;

                char* arg4 = strtok(nullptr, " ");
                if (arg4 != nullptr)
                {
                    endIdx = atoi(arg4);
                }

                if (startIdx < 0 || startIdx >= 1024)
                {
                    screen << "Invalid start index\n";
                }
                else if (endIdx < 0 || endIdx >= 1024)
                {
                    screen << "Invalid end index\n";
                }
                else
                {
                    printPageTable(pageDirIdx, startIdx, endIdx);
                }
            }
        }
        else if (strcmp(arg1, "smile") == 0 || strcmp(arg1, "smiley") == 0)
        {
            for (int i = 0; i < 20; ++i)
            {
                screen << "\1 \2 ";
            }
        }
        else if (strcmp(arg1, "ticks") == 0)
        {
            char* arg2 = strtok(nullptr, " ");
            if (arg2 != nullptr)
            {
                screen << "Unexpected argument \"" << arg2 << "\"\n";
            }
            else
            {
                screen << os::Timer::getTicks() << '\n';
            }
        }
        else
        {
            screen << "Unexpected argument\n";
        }
    }

private:
    const multiboot_info* mbootInfo;
} showCmd;

class WriteCommand : public Command
{
public:
    const char* getName() override
    {
        return "write";
    }

    const char* getHelp() override
    {
        return
R"(Writes a byte to memory
)";
    }

    void execute() override
    {
        char* addrArg = strtok(nullptr, " ");
        char* valArg = strtok(nullptr, " ");
        if (addrArg == nullptr || valArg == nullptr)
        {
            screen << "Not enough arguments\n";
        }
        else if (strtok(nullptr, " ") != nullptr)
        {
            screen << "Too many arguments\n";
        }
        else
        {
            bool ok = true;

            char* str = nullptr;
            long addr = strtol(addrArg, &str, 16);
            if (str == nullptr || *str != '\0')
            {
                screen << "Address is not a valid hexadecimal number\n";
                ok = false;
            }

            str = nullptr;
            uint8_t val = strtol(valArg, &str, 16);
            if (str == nullptr || *str != '\0')
            {
                screen << "Value is not a valid number\n";
                ok = false;
            }

            if (ok)
            {
                uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
                *ptr = val;
            }
        }
    }
} writeCmd;

Command* Shell::COMMANDS[NUM_COMMANDS] =
{
    &clearCmd,
    &readCmd,
    &setCmd,
    &showCmd,
    &writeCmd,
};

Shell::Shell(const multiboot_info* mbootInfoPtr) :
    mbootInfo(mbootInfoPtr)
{
    showCmd.setMbootInfo(mbootInfo);

    prompt();
}

void Shell::update()
{
    char ch;
    bool avail = screen.read(ch);
    while (avail)
    {
        processChar(ch);

        avail = screen.read(ch);
    }
}

void Shell::prompt()
{
    screen << "> ";
}

void Shell::processChar(char ch)
{
    if (ch == '\n')
    {
        screen << ch;
        cmd[cmdIdx] = '\0';
        processCmd();
    }
    else if (ch == '\b')
    {
        if (cmdIdx > 0)
        {
            // clear the previous char
            screen << "\b \b";
            --cmdIdx;
        }
    }
    else if (cmdIdx == CMD_MAX_SIZE)
    {
        screen << ch;
        screen << "\nError: Command too long\n";
        resetCmd();
        prompt();
    }
    else
    {
        screen << ch;
        cmd[cmdIdx++] = ch;
    }
}

void Shell::processCmd()
{
    char* token = strtok(cmd, " ");
    if (token != nullptr)
    {
        bool found = false;
        if (strcmp(token, "help") == 0)
        {
            found = true;
            displayHelp();
        }

        // look for command object
        if (!found)
        {
            for (unsigned int i = 0; i < NUM_COMMANDS; ++i)
            {
                Command* cmd = COMMANDS[i];
                if (strcmp(token, cmd->getName()) == 0)
                {
                    cmd->execute();
                    found = true;
                    break;
                }
            }

        }

        // look for program
        if (!found)
        {
            uint32_t progAddr = 0;
            found = findProgram(token, progAddr);
            if (found)
            {
                runProgram(progAddr);
            }
        }

        if (!found)
        {
            screen << "Unknown command\n";
        }
    }

    resetCmd();
    prompt();
}

bool Shell::findProgram(const char* name, uint32_t& progAddr)
{
    bool found = false;
    uint32_t addr = mbootInfo->mods_addr + KERNEL_VIRTUAL_BASE;
    uint32_t count = mbootInfo->mods_count;

    for (uint32_t i = 0; i < count; ++i)
    {
        // get module info struct
        const multiboot_mod_list* module = reinterpret_cast<const multiboot_mod_list*>(addr);

        // check if name matches
        const char* modName = reinterpret_cast<const char*>(module->cmdline + KERNEL_VIRTUAL_BASE);
        if (strcmp(name, modName) == 0)
        {
            progAddr = module->mod_start + KERNEL_VIRTUAL_BASE;
            found = true;
            break;
        }

        addr += sizeof(multiboot_mod_list);
    }

    return found;
}

void Shell::runProgram(uint32_t addr)
{
    programPtr program = reinterpret_cast<programPtr>(addr);
    int rc = program();
    screen << "Return code: " << rc << '\n';
}

void Shell::displayHelp()
{
    char* arg = strtok(nullptr, " ");

    // if no argument was given, list the commands
    if (arg == nullptr)
    {
        screen << "Commands:\n";
        for (unsigned int i = 0; i < NUM_COMMANDS; ++i)
        {
            screen << COMMANDS[i]->getName() << '\n';
        }
    }
    else if (strtok(nullptr, " ") != nullptr)
    {
        screen << "Only expected one argument\n";
    }
    else if (strcmp(arg, "help") == 0)
    {
        screen << "Displays help for commands\n";
    }
    else
    {
        bool found = false;
        for (unsigned int i = 0; i < NUM_COMMANDS; ++i)
        {
            Command* cmd = COMMANDS[i];
            if (strcmp(arg, cmd->getName()) == 0)
            {
                screen << cmd->getHelp();
                found = true;
                break;
            }
        }

        if (!found)
        {
            screen << '"' << arg << "\" is not a command\n";
        }
    }
}

void Shell::resetCmd()
{
    cmdIdx = 0;
}
<|endoftext|>


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

#pragma hdrstop

#include "sdresid.hxx"
#include "printdlg.hxx"
#include "printdlg.hrc"

/*************************************************************************
|*
|*    SdPrintDlg::SdPrintDlg()
|*
|*    Beschreibung  Dialog zum Einstellen von Printoptionen
|*
*************************************************************************/

SdPrintDlg::SdPrintDlg( Window* pWindow ) :
    ModalDialog     ( pWindow, SdResId( DLG_PRINT_WARNINGS ) ),
    aFtInfo         ( this, SdResId( FI_INFO ) ),
    aRbtScale       ( this, SdResId( RBT_SCALE ) ),
    aRbtPoster      ( this, SdResId( RBT_POSTER ) ),
    aRbtCut         ( this, SdResId( RBT_CUT ) ),
    aGrpOptions     ( this, SdResId( GRP_OPTIONS ) ),
    aBtnOK          ( this, SdResId( BTN_OK ) ),
    aBtnCancel      ( this, SdResId( BTN_CANCEL ) ),
    aBtnHelp        ( this, SdResId( BTN_HELP ) )
{
    FreeResource();

    aRbtScale.Check();
}

/*************************************************************************
|*
|*    SdPrintDlg::GetAttr()
|*
|*    Beschreibung  Liefert eingestellte Option zurueck
|*
*************************************************************************/

USHORT SdPrintDlg::GetAttr()
{
    USHORT nOption = 0;

    if( aRbtScale.IsChecked() )
        nOption = 1;
    else if( aRbtPoster.IsChecked() )
        nOption = 2;
    else if( aRbtCut.IsChecked() )
        nOption = 3;

    return( nOption );
}

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

#ifdef SD_DLLIMPLEMENTATION
#undef SD_DLLIMPLEMENTATION
#endif

#pragma hdrstop

#include "sdresid.hxx"
#include "printdlg.hxx"
#include "printdlg.hrc"

/*************************************************************************
|*
|*    SdPrintDlg::SdPrintDlg()
|*
|*    Beschreibung  Dialog zum Einstellen von Printoptionen
|*
*************************************************************************/

SdPrintDlg::SdPrintDlg( Window* pWindow ) :
    ModalDialog     ( pWindow, SdResId( DLG_PRINT_WARNINGS ) ),
    aFtInfo         ( this, SdResId( FI_INFO ) ),
    aRbtScale       ( this, SdResId( RBT_SCALE ) ),
    aRbtPoster      ( this, SdResId( RBT_POSTER ) ),
    aRbtCut         ( this, SdResId( RBT_CUT ) ),
    aGrpOptions     ( this, SdResId( GRP_OPTIONS ) ),
    aBtnOK          ( this, SdResId( BTN_OK ) ),
    aBtnCancel      ( this, SdResId( BTN_CANCEL ) ),
    aBtnHelp        ( this, SdResId( BTN_HELP ) )
{
    FreeResource();

    aRbtScale.Check();
}

/*************************************************************************
|*
|*    SdPrintDlg::GetAttr()
|*
|*    Beschreibung  Liefert eingestellte Option zurueck
|*
*************************************************************************/

USHORT SdPrintDlg::GetAttr()
{
    USHORT nOption = 0;

    if( aRbtScale.IsChecked() )
        nOption = 1;
    else if( aRbtPoster.IsChecked() )
        nOption = 2;
    else if( aRbtCut.IsChecked() )
        nOption = 3;

    return( nOption );
}

<|endoftext|>


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

#ifndef SD_FU_SLIDE_HIDE_HXX
#define SD_FU_SLIDE_HIDE_HXX

#ifndef SD_FU_SLIDE_HXX
#include "fuslid.hxx"
#endif

namespace sd {

/*************************************************************************
|*
|* selektierte Dias in der Show zeigen / nicht zeigen
|*
\************************************************************************/

class FuSlideHide
    : public FuSlide
{
public:
    TYPEINFO();

    FuSlideHide (
        ViewShell* pViewSh,
        ::sd::Window* pWin,
        ::sd::View* pView,
        SdDrawDocument* pDoc,
        SfxRequest& rReq);
    virtual ~FuSlideHide (void);
};

} // end of namespace sd

#endif

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

#ifndef SD_FU_SLIDE_HIDE_HXX
#define SD_FU_SLIDE_HIDE_HXX

#ifndef SD_FU_SLIDE_HXX
#include "fuslid.hxx"
#endif

namespace sd {

/*************************************************************************
|*
|* selektierte Dias in der Show zeigen / nicht zeigen
|*
\************************************************************************/

class FuSlideHide
    : public FuSlide
{
public:
    TYPEINFO();

    FuSlideHide (
        ViewShell* pViewSh,
        ::sd::Window* pWin,
        ::sd::View* pView,
        SdDrawDocument* pDoc,
        SfxRequest& rReq);
    virtual ~FuSlideHide (void);
};

} // end of namespace sd

#endif

<|endoftext|>


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

#ifndef _SD_UNDOPAGE_HXX
#define _SD_UNDOPAGE_HXX

#ifndef _GEN_HXX //autogen
#include <tools/gen.hxx>
#endif
#ifndef _SV_PRNTYPES_HXX //autogen
#include <vcl/prntypes.hxx>
#endif

#include "sdundo.hxx"

class SdDrawDocument;
class SdPage;

/************************************************************************/

class SdPageFormatUndoAction : public SdUndoAction
{
    SdPage*     mpPage;

    Size        maOldSize;
    INT32       mnOldLeft;
    INT32       mnOldRight;
    INT32       mnOldUpper;
    INT32       mnOldLower;
    BOOL        mbOldScale;
    Orientation meOldOrientation;
    USHORT      mnOldPaperBin;
    BOOL        mbOldFullSize;

    Size        maNewSize;
    INT32       mnNewLeft;
    INT32       mnNewRight;
    INT32       mnNewUpper;
    INT32       mnNewLower;
    BOOL        mbNewScale;
    Orientation meNewOrientation;
    USHORT      mnNewPaperBin;
    BOOL        mbNewFullSize;

public:
    TYPEINFO();
    SdPageFormatUndoAction( SdDrawDocument* pDoc,
                            SdPage*         pThePage,
                            const Size&     rOldSz,
                            INT32           nOldLft,
                            INT32           nOldRgt,
                            INT32           nOldUpr,
                            INT32           nOldLwr,
                            BOOL            bOldScl,
                            Orientation     eOldOrient,
                            USHORT          nOPaperBin,
                            BOOL            bOFullSize,

                            const Size&     rNewSz,
                            INT32           nNewLft,
                            INT32           nNewRgt,
                            INT32           nNewUpr,
                            INT32           nNewLwr,
                            BOOL            bNewScl,
                            Orientation     eNewOrient,
                            USHORT          nNPaperBin,
                            BOOL            bNFullSize
                            ) :
        SdUndoAction(pDoc),
        mpPage      (pThePage),
        maOldSize   (rOldSz),
        mnOldLeft   (nOldLft),
        mnOldRight  (nOldRgt),
        mnOldUpper  (nOldUpr),
        mnOldLower  (nOldLwr),
        mbOldScale   (bOldScl),
        meOldOrientation(eOldOrient),
        mnOldPaperBin (nOPaperBin),
        mbOldFullSize (bOFullSize),

        maNewSize   (rNewSz),
        mnNewLeft   (nNewLft),
        mnNewRight  (nNewRgt),
        mnNewUpper  (nNewUpr),
        mnNewLower   (nNewLwr),
        mbNewScale   (bNewScl),
        meNewOrientation(eNewOrient),
        mnNewPaperBin (nNPaperBin),
        mbNewFullSize (bNFullSize)

        {}
    virtual ~SdPageFormatUndoAction();

    virtual void Undo();
    virtual void Redo();
};

/************************************************************************/

class SdPageLRUndoAction : public SdUndoAction
{
    SdPage* mpPage;

    INT32   mnOldLeft;
    INT32   mnOldRight;
    INT32   mnNewLeft;
    INT32   mnNewRight;

public:
    TYPEINFO();
    SdPageLRUndoAction( SdDrawDocument* pDoc, SdPage* pThePage,
                        INT32 nOldLft, INT32 nOldRgt,
                        INT32 nNewLft, INT32 nNewRgt ) :
        SdUndoAction(pDoc),
        mpPage      (pThePage),
        mnOldLeft   (nOldLft),
        mnOldRight  (nOldRgt),
        mnNewLeft   (nNewLft),
        mnNewRight  (nNewRgt)
        {}
    virtual ~SdPageLRUndoAction();

    virtual void Undo();
    virtual void Redo();
};

/************************************************************************/

class SdPageULUndoAction : public SdUndoAction
{
    SdPage* mpPage;

    INT32   mnOldUpper;
    INT32   mnOldLower;
    INT32   mnNewUpper;
    INT32   mnNewLower;

public:
    TYPEINFO();
    SdPageULUndoAction( SdDrawDocument* pDoc, SdPage* pThePage,
                        INT32 nOldUpr, INT32 nOldLwr,
                        INT32 nNewUpr, INT32 nNewLwr ) :
        SdUndoAction(pDoc),
        mpPage      (pThePage),
        mnOldUpper  (nOldUpr),
        mnOldLower  (nOldLwr),
        mnNewUpper  (nNewUpr),
        mnNewLower  (nNewLwr)
        {}
    virtual ~SdPageULUndoAction();

    virtual void Undo();
    virtual void Redo();
};

#endif      // _SD_UNDOPAGE_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.4.298); FILE MERGED 2008/04/01 15:35:35 thb 1.4.298.2: #i85898# Stripping all external header guards 2008/03/31 13:58:18 rt 1.4.298.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: undopage.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SD_UNDOPAGE_HXX
#define _SD_UNDOPAGE_HXX

#include <tools/gen.hxx>
#include <vcl/prntypes.hxx>

#include "sdundo.hxx"

class SdDrawDocument;
class SdPage;

/************************************************************************/

class SdPageFormatUndoAction : public SdUndoAction
{
    SdPage*     mpPage;

    Size        maOldSize;
    INT32       mnOldLeft;
    INT32       mnOldRight;
    INT32       mnOldUpper;
    INT32       mnOldLower;
    BOOL        mbOldScale;
    Orientation meOldOrientation;
    USHORT      mnOldPaperBin;
    BOOL        mbOldFullSize;

    Size        maNewSize;
    INT32       mnNewLeft;
    INT32       mnNewRight;
    INT32       mnNewUpper;
    INT32       mnNewLower;
    BOOL        mbNewScale;
    Orientation meNewOrientation;
    USHORT      mnNewPaperBin;
    BOOL        mbNewFullSize;

public:
    TYPEINFO();
    SdPageFormatUndoAction( SdDrawDocument* pDoc,
                            SdPage*         pThePage,
                            const Size&     rOldSz,
                            INT32           nOldLft,
                            INT32           nOldRgt,
                            INT32           nOldUpr,
                            INT32           nOldLwr,
                            BOOL            bOldScl,
                            Orientation     eOldOrient,
                            USHORT          nOPaperBin,
                            BOOL            bOFullSize,

                            const Size&     rNewSz,
                            INT32           nNewLft,
                            INT32           nNewRgt,
                            INT32           nNewUpr,
                            INT32           nNewLwr,
                            BOOL            bNewScl,
                            Orientation     eNewOrient,
                            USHORT          nNPaperBin,
                            BOOL            bNFullSize
                            ) :
        SdUndoAction(pDoc),
        mpPage      (pThePage),
        maOldSize   (rOldSz),
        mnOldLeft   (nOldLft),
        mnOldRight  (nOldRgt),
        mnOldUpper  (nOldUpr),
        mnOldLower  (nOldLwr),
        mbOldScale   (bOldScl),
        meOldOrientation(eOldOrient),
        mnOldPaperBin (nOPaperBin),
        mbOldFullSize (bOFullSize),

        maNewSize   (rNewSz),
        mnNewLeft   (nNewLft),
        mnNewRight  (nNewRgt),
        mnNewUpper  (nNewUpr),
        mnNewLower   (nNewLwr),
        mbNewScale   (bNewScl),
        meNewOrientation(eNewOrient),
        mnNewPaperBin (nNPaperBin),
        mbNewFullSize (bNFullSize)

        {}
    virtual ~SdPageFormatUndoAction();

    virtual void Undo();
    virtual void Redo();
};

/************************************************************************/

class SdPageLRUndoAction : public SdUndoAction
{
    SdPage* mpPage;

    INT32   mnOldLeft;
    INT32   mnOldRight;
    INT32   mnNewLeft;
    INT32   mnNewRight;

public:
    TYPEINFO();
    SdPageLRUndoAction( SdDrawDocument* pDoc, SdPage* pThePage,
                        INT32 nOldLft, INT32 nOldRgt,
                        INT32 nNewLft, INT32 nNewRgt ) :
        SdUndoAction(pDoc),
        mpPage      (pThePage),
        mnOldLeft   (nOldLft),
        mnOldRight  (nOldRgt),
        mnNewLeft   (nNewLft),
        mnNewRight  (nNewRgt)
        {}
    virtual ~SdPageLRUndoAction();

    virtual void Undo();
    virtual void Redo();
};

/************************************************************************/

class SdPageULUndoAction : public SdUndoAction
{
    SdPage* mpPage;

    INT32   mnOldUpper;
    INT32   mnOldLower;
    INT32   mnNewUpper;
    INT32   mnNewLower;

public:
    TYPEINFO();
    SdPageULUndoAction( SdDrawDocument* pDoc, SdPage* pThePage,
                        INT32 nOldUpr, INT32 nOldLwr,
                        INT32 nNewUpr, INT32 nNewLwr ) :
        SdUndoAction(pDoc),
        mpPage      (pThePage),
        mnOldUpper  (nOldUpr),
        mnOldLower  (nOldLwr),
        mnNewUpper  (nNewUpr),
        mnNewLower  (nNewLwr)
        {}
    virtual ~SdPageULUndoAction();

    virtual void Undo();
    virtual void Redo();
};

#endif      // _SD_UNDOPAGE_HXX

<|endoftext|>


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

#define UNO_NAME_MODEL_LANGUAGE         "CharLocale"
#define UNO_NAME_MODEL_TABSTOP          "TabStop"

#define UNO_NAME_PAGE_BACKGROUND        "Background"
#define UNO_NAME_PAGE_LEFT              "BorderLeft"
#define UNO_NAME_PAGE_RIGHT             "BorderRight"
#define UNO_NAME_PAGE_TOP               "BorderTop"
#define UNO_NAME_PAGE_BOTTOM            "BorderBottom"
#define UNO_NAME_PAGE_CHANGE            "Change"
#define UNO_NAME_PAGE_DURATION          "Duration"
#define UNO_NAME_PAGE_EFFECT            "Effect"
#define UNO_NAME_PAGE_HEIGHT            "Height"
#define UNO_NAME_PAGE_LAYOUT            "Layout"
#define UNO_NAME_PAGE_NUMBER            "Number"
#define UNO_NAME_PAGE_OBJECTS           "Objects"
#define UNO_NAME_PAGE_ORIENTATION       "Orientation"
#define UNO_NAME_PAGE_SPEED             "Speed"
#define UNO_NAME_PAGE_WIDTH             "Width"
#define UNO_NAME_PAGE_PREVIEW           "Preview"
#define UNO_NAME_PAGE_VISIBLE           "Visible"

#define UNO_NAME_OBJ_BOOKMARK           "Bookmark"
#define UNO_NAME_OBJ_DIMCOLOR           "DimColor"
#define UNO_NAME_OBJ_DIMHIDE            "DimHide"
#define UNO_NAME_OBJ_DIMPREV            "DimPrevious"
#define UNO_NAME_OBJ_EFFECT             "Effect"
#define UNO_NAME_OBJ_ISEMPTYPRESOBJ     "IsEmptyPresentationObject"
#define UNO_NAME_OBJ_ISPRESOBJ          "IsPresentationObject"
#define UNO_NAME_OBJ_CLICKACTION        "OnClick"
#define UNO_NAME_OBJ_PLAYFULL           "PlayFull"
#define UNO_NAME_OBJ_PRESORDER          "PresentationOrder"
#define UNO_NAME_OBJ_SOUNDFILE          "Sound"
#define UNO_NAME_OBJ_SOUNDON            "SoundOn"
#define UNO_NAME_OBJ_SPEED              "Speed"
#define UNO_NAME_OBJ_TEXTEFFECT         "TextEffect"
#define UNO_NAME_OBJ_BLUESCREEN         "TransparentColor"
#define UNO_NAME_OBJ_VERB               "Verb"
#define UNO_NAME_OBJ_STYLE              "Style"
#define UNO_NAME_OBJ_MASTERDEPENDENT    "IsPlaceholderDependent"
#define UNO_NAME_OBJ_ANIMATIONPATH      "AnimationPath"

#define UNO_NAME_LAYER_LOCKED           "IsLocked"
#define UNO_NAME_LAYER_PRINTABLE        "IsPrintable"
#define UNO_NAME_LAYER_VISIBLE          "IsVisible"
#define UNO_NAME_LAYER_NAME             "Name"

#define UNO_NAME_SHOW_ALLOWANIM         "AllowAnimations"
#define UNO_NAME_SHOW_CUSTOMSHOW        "CustomShow"
#define UNO_NAME_SHOW_FIRSTPAGE         "FirstPage"
#define UNO_NAME_SHOW_ONTOP             "IsAlwaysOnTop"
#define UNO_NAME_SHOW_AUTOMATIC         "IsAutomatic"
#define UNO_NAME_SHOW_ENDLESS           "IsEndless"
#define UNO_NAME_SHOW_FULLSCREEN        "IsFullScreen"
#define UNO_NAME_SHOW_LIVEMODUS         "IsLivePresentation"
#define UNO_NAME_SHOW_MOUSEVISIBLE      "IsMouseVisible"
#define UNO_NAME_SHOW_PAGERANGE         "PageRange"
#define UNO_NAME_SHOW_PAUSE             "Pause"
#define UNO_NAME_SHOW_STARTWITHNAV      "StartWithNavigator"
#define UNO_NAME_SHOW_USEPEN            "UsePen"

#define UNO_NAME_SEARCH_BACKWARDS   "SearchBackwards"
#define UNO_NAME_SEARCH_CASE        "SearchCaseSensitive"
#define UNO_NAME_SEARCH_WORDS       "SearchWords"

#define UNO_NAME_LINKDISPLAYNAME                "LinkDisplayName"
#define UNO_NAME_LINKDISPLAYBITMAP              "LinkDisplayBitmap"

#define UNO_NAME_STYLE_FAMILY   "Family"
#endif

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

#define UNO_NAME_MODEL_LANGUAGE         "CharLocale"
#define UNO_NAME_MODEL_TABSTOP          "TabStop"

#define UNO_NAME_PAGE_BACKGROUND        "Background"
#define UNO_NAME_PAGE_LEFT              "BorderLeft"
#define UNO_NAME_PAGE_RIGHT             "BorderRight"
#define UNO_NAME_PAGE_TOP               "BorderTop"
#define UNO_NAME_PAGE_BOTTOM            "BorderBottom"
#define UNO_NAME_PAGE_CHANGE            "Change"
#define UNO_NAME_PAGE_DURATION          "Duration"
#define UNO_NAME_PAGE_EFFECT            "Effect"
#define UNO_NAME_PAGE_HEIGHT            "Height"
#define UNO_NAME_PAGE_LAYOUT            "Layout"
#define UNO_NAME_PAGE_NUMBER            "Number"
#define UNO_NAME_PAGE_OBJECTS           "Objects"
#define UNO_NAME_PAGE_ORIENTATION       "Orientation"
#define UNO_NAME_PAGE_SPEED             "Speed"
#define UNO_NAME_PAGE_WIDTH             "Width"
#define UNO_NAME_PAGE_PREVIEW           "Preview"
#define UNO_NAME_PAGE_VISIBLE           "Visible"

#define UNO_NAME_OBJ_BOOKMARK           "Bookmark"
#define UNO_NAME_OBJ_DIMCOLOR           "DimColor"
#define UNO_NAME_OBJ_DIMHIDE            "DimHide"
#define UNO_NAME_OBJ_DIMPREV            "DimPrevious"
#define UNO_NAME_OBJ_EFFECT             "Effect"
#define UNO_NAME_OBJ_ISEMPTYPRESOBJ     "IsEmptyPresentationObject"
#define UNO_NAME_OBJ_ISPRESOBJ          "IsPresentationObject"
#define UNO_NAME_OBJ_CLICKACTION        "OnClick"
#define UNO_NAME_OBJ_PLAYFULL           "PlayFull"
#define UNO_NAME_OBJ_PRESORDER          "PresentationOrder"
#define UNO_NAME_OBJ_SOUNDFILE          "Sound"
#define UNO_NAME_OBJ_SOUNDON            "SoundOn"
#define UNO_NAME_OBJ_SPEED              "Speed"
#define UNO_NAME_OBJ_TEXTEFFECT         "TextEffect"
#define UNO_NAME_OBJ_BLUESCREEN         "TransparentColor"
#define UNO_NAME_OBJ_VERB               "Verb"
#define UNO_NAME_OBJ_STYLE              "Style"
#define UNO_NAME_OBJ_MASTERDEPENDENT    "IsPlaceholderDependent"
#define UNO_NAME_OBJ_ANIMATIONPATH      "AnimationPath"

#define UNO_NAME_LAYER_LOCKED           "IsLocked"
#define UNO_NAME_LAYER_PRINTABLE        "IsPrintable"
#define UNO_NAME_LAYER_VISIBLE          "IsVisible"
#define UNO_NAME_LAYER_NAME             "Name"

#define UNO_NAME_SHOW_ALLOWANIM         "AllowAnimations"
#define UNO_NAME_SHOW_CUSTOMSHOW        "CustomShow"
#define UNO_NAME_SHOW_FIRSTPAGE         "FirstPage"
#define UNO_NAME_SHOW_ONTOP             "IsAlwaysOnTop"
#define UNO_NAME_SHOW_AUTOMATIC         "IsAutomatic"
#define UNO_NAME_SHOW_ENDLESS           "IsEndless"
#define UNO_NAME_SHOW_FULLSCREEN        "IsFullScreen"
#define UNO_NAME_SHOW_MOUSEVISIBLE      "IsMouseVisible"
#define UNO_NAME_SHOW_PAGERANGE         "PageRange"
#define UNO_NAME_SHOW_PAUSE             "Pause"
#define UNO_NAME_SHOW_STARTWITHNAV      "StartWithNavigator"
#define UNO_NAME_SHOW_USEPEN            "UsePen"

#define UNO_NAME_SEARCH_BACKWARDS   "SearchBackwards"
#define UNO_NAME_SEARCH_CASE        "SearchCaseSensitive"
#define UNO_NAME_SEARCH_WORDS       "SearchWords"

#define UNO_NAME_LINKDISPLAYNAME                "LinkDisplayName"
#define UNO_NAME_LINKDISPLAYBITMAP              "LinkDisplayBitmap"

#define UNO_NAME_STYLE_FAMILY   "Family"
#endif

<|endoftext|>


<commit_before><commit_msg>Let `A` own even if it should not...<commit_after><|endoftext|>


<commit_before>#include "Graphics.h"

namespace CppChart
{
	sf::RectangleShape MakeRect(sf::Vector2f first, sf::Vector2f second, float thickness)
	{
		sf::RectangleShape plot;
		float dist = sqrt((first.x - second.x) * (first.x - second.x) + (first.y - second.y) * (first.y - second.y));

		plot.setSize(sf::Vector2f(dist, thickness));

		if (first.y > second.y)
		{
			std::swap(first, second);
		}

		plot.setPosition(first);
		plot.setOrigin(0.0f, plot.getSize().y / 2.0f);

		float m = (second.y - first.y) / (second.x - first.x);
		float angle = (180.0f / 3.1415f) * atan(m >= 0.0f ? m : -m);

		if ((first.x - second.x) > 0.01f)
		{
			angle = 180.0f - angle;
		}

		plot.rotate(angle);

		return plot;
	}

	void DrawDottedLine(sf::RenderTarget* window, const sf::Vector2f& start, const sf::Vector2f& end, const sf::Color& color, float gap, float thickness)
	{
		LogFnStart();

		float dist = sqrt((start.x - end.x) * (start.x - end.x) + (start.y - end.y) * (start.y - end.y));
		float covered, ratio;
		float x, y;
		int totalSegments = dist / gap;
		bool draw = true;
		sf::Vector2f first = start, second;

		covered = gap;

		for (int i = 0; i < totalSegments; ++i)
		{
			if (draw)
			{
				ratio = covered / dist;
				x = start.x * (1.0f - ratio) + end.x * ratio;
				y = start.y * (1.0f - ratio) + end.y * ratio;
				second = sf::Vector2f(x, y);

				sf::RectangleShape rect = MakeRect(first, second, thickness);
				rect.setFillColor(color);
				window->draw(rect);
			}
			else
			{
				ratio = covered / dist;
				x = start.x * (1.0f - ratio) + end.x * ratio;
				y = start.y * (1.0f - ratio) + end.y * ratio;
				first = sf::Vector2f(x, y);
			}

			draw = !draw;
			covered += gap;
		}

		if ((totalSegments % 2 == 0) && ((dist / gap) > static_cast<float>(totalSegments)))
		{
			sf::RectangleShape rect = MakeRect(first, end, thickness);
			rect.setFillColor(color);
			window->draw(rect);
		}

		LogFnEnd();
	}

	void SetTextAtCenter(sf::Text& text, float x, float y, float w, float h)
	{
		LogFnStart();

		float offsetX = (w - text.getLocalBounds().width) / 2.0f;
		float offsetY = (h - text.getLocalBounds().height) / 2.0f;

		text.setPosition(sf::Vector2f(x + offsetX, y + offsetY));

		LogFnEnd();
	}

	sf::CircleShape PlotPoint(float x, float y, float r, const sf::Color& color)
	{
		LogFnStart();

		sf::CircleShape cs(r);
		cs.setPosition(sf::Vector2f(x, y));
		cs.setFillColor(color);

		LogFnEnd();

		return cs;
	}

	SectorShape::SectorShape(float r, float a, const sf::Vector2f& c) :
		m_radius(r), m_angle(a), m_center(c)
	{
		LogFnStart();

		m_points = 2u + static_cast<unsigned int>(0.05f * m_radius * m_angle);
		m_pie = sf::VertexArray(sf::TrianglesFan, m_points);

		Update();

		LogFnEnd();
	}
}<commit_msg>Implement SectorShape::Draw()<commit_after>#include "Graphics.h"

namespace CppChart
{
	sf::RectangleShape MakeRect(sf::Vector2f first, sf::Vector2f second, float thickness)
	{
		sf::RectangleShape plot;
		float dist = sqrt((first.x - second.x) * (first.x - second.x) + (first.y - second.y) * (first.y - second.y));

		plot.setSize(sf::Vector2f(dist, thickness));

		if (first.y > second.y)
		{
			std::swap(first, second);
		}

		plot.setPosition(first);
		plot.setOrigin(0.0f, plot.getSize().y / 2.0f);

		float m = (second.y - first.y) / (second.x - first.x);
		float angle = (180.0f / 3.1415f) * atan(m >= 0.0f ? m : -m);

		if ((first.x - second.x) > 0.01f)
		{
			angle = 180.0f - angle;
		}

		plot.rotate(angle);

		return plot;
	}

	void DrawDottedLine(sf::RenderTarget* window, const sf::Vector2f& start, const sf::Vector2f& end, const sf::Color& color, float gap, float thickness)
	{
		LogFnStart();

		float dist = sqrt((start.x - end.x) * (start.x - end.x) + (start.y - end.y) * (start.y - end.y));
		float covered, ratio;
		float x, y;
		int totalSegments = dist / gap;
		bool draw = true;
		sf::Vector2f first = start, second;

		covered = gap;

		for (int i = 0; i < totalSegments; ++i)
		{
			if (draw)
			{
				ratio = covered / dist;
				x = start.x * (1.0f - ratio) + end.x * ratio;
				y = start.y * (1.0f - ratio) + end.y * ratio;
				second = sf::Vector2f(x, y);

				sf::RectangleShape rect = MakeRect(first, second, thickness);
				rect.setFillColor(color);
				window->draw(rect);
			}
			else
			{
				ratio = covered / dist;
				x = start.x * (1.0f - ratio) + end.x * ratio;
				y = start.y * (1.0f - ratio) + end.y * ratio;
				first = sf::Vector2f(x, y);
			}

			draw = !draw;
			covered += gap;
		}

		if ((totalSegments % 2 == 0) && ((dist / gap) > static_cast<float>(totalSegments)))
		{
			sf::RectangleShape rect = MakeRect(first, end, thickness);
			rect.setFillColor(color);
			window->draw(rect);
		}

		LogFnEnd();
	}

	void SetTextAtCenter(sf::Text& text, float x, float y, float w, float h)
	{
		LogFnStart();

		float offsetX = (w - text.getLocalBounds().width) / 2.0f;
		float offsetY = (h - text.getLocalBounds().height) / 2.0f;

		text.setPosition(sf::Vector2f(x + offsetX, y + offsetY));

		LogFnEnd();
	}

	sf::CircleShape PlotPoint(float x, float y, float r, const sf::Color& color)
	{
		LogFnStart();

		sf::CircleShape cs(r);
		cs.setPosition(sf::Vector2f(x, y));
		cs.setFillColor(color);

		LogFnEnd();

		return cs;
	}

	SectorShape::SectorShape(float r, float a, const sf::Vector2f& c) :
		m_radius(r), m_angle(a), m_center(c)
	{
		LogFnStart();

		m_points = 2u + static_cast<unsigned int>(0.05f * m_radius * m_angle);
		m_pie = sf::VertexArray(sf::TrianglesFan, m_points);

		Update();

		LogFnEnd();
	}

	void SectorShape::Draw(sf::RenderTarget& target, sf::RenderStates states) const
	{
		LogFnStart();

		states.transform *= getTransform();
		target.draw(m_pie, states);

		LogFnEnd();
	}
}<|endoftext|>


<commit_before>// Copyright (c) 2020 Vasyl Teliman
//
// 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 "source/fuzz/fuzzer_pass_add_composite_extract.h"

#include "source/fuzz/fuzzer_context.h"
#include "source/fuzz/fuzzer_util.h"
#include "source/fuzz/instruction_descriptor.h"
#include "source/fuzz/transformation_composite_extract.h"

namespace spvtools {
namespace fuzz {

FuzzerPassAddCompositeExtract::FuzzerPassAddCompositeExtract(
    opt::IRContext* ir_context, TransformationContext* transformation_context,
    FuzzerContext* fuzzer_context,
    protobufs::TransformationSequence* transformations)
    : FuzzerPass(ir_context, transformation_context, fuzzer_context,
                 transformations) {}

FuzzerPassAddCompositeExtract::~FuzzerPassAddCompositeExtract() = default;

void FuzzerPassAddCompositeExtract::Apply() {
  std::vector<const protobufs::DataDescriptor*> composite_synonyms;
  for (const auto* dd :
       GetTransformationContext()->GetFactManager()->GetAllSynonyms()) {
    // |dd| must describe a component of a composite.
    if (!dd->index().empty()) {
      composite_synonyms.push_back(dd);
    }
  }

  // We don't want to invalidate the module every time we apply this
  // transformation since rebuilding DominatorAnalysis can be expensive, so we
  // collect up the transformations we wish to apply and apply them all later.
  std::vector<TransformationCompositeExtract> transformations;

  ForEachInstructionWithInstructionDescriptor(
      [this, &composite_synonyms, &transformations](
          opt::Function* function, opt::BasicBlock* block,
          opt::BasicBlock::iterator inst_it,
          const protobufs::InstructionDescriptor& instruction_descriptor) {
        if (!fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpCompositeExtract,
                                                          inst_it)) {
          return;
        }

        if (!GetFuzzerContext()->ChoosePercentage(
                GetFuzzerContext()->GetChanceOfAddingCompositeExtract())) {
          return;
        }

        auto available_composites = FindAvailableInstructions(
            function, block, inst_it,
            [](opt::IRContext* ir_context, opt::Instruction* inst) {
              return inst->type_id() && inst->result_id() &&
                     fuzzerutil::IsCompositeType(
                         ir_context->get_type_mgr()->GetType(inst->type_id()));
            });

        std::vector<const protobufs::DataDescriptor*> available_synonyms;
        for (const auto* dd : composite_synonyms) {
          if (fuzzerutil::IdIsAvailableBeforeInstruction(
                  GetIRContext(), &*inst_it, dd->object())) {
            available_synonyms.push_back(dd);
          }
        }

        if (available_synonyms.empty() && available_composites.empty()) {
          return;
        }

        uint32_t composite_id = 0;
        std::vector<uint32_t> indices;

        if (available_synonyms.empty() || (!available_composites.empty() &&
                                           GetFuzzerContext()->ChooseEven())) {
          const auto* inst =
              available_composites[GetFuzzerContext()->RandomIndex(
                  available_composites)];
          composite_id = inst->result_id();

          const auto* type =
              GetIRContext()->get_type_mgr()->GetType(inst->type_id());
          assert(type && "Composite instruction has invalid type id");

          do {
            uint32_t number_of_members = 0;

            if (const auto* array_type = type->AsArray()) {
              const auto* type_inst =
                  GetIRContext()->get_def_use_mgr()->GetDef(inst->type_id());
              assert(type_inst && "Type instruction must exist");

              number_of_members =
                  fuzzerutil::GetArraySize(*type_inst, GetIRContext());
              type = array_type->element_type();
            } else if (const auto* vector_type = type->AsVector()) {
              number_of_members = vector_type->element_count();
              type = vector_type->element_type();
            } else if (const auto* matrix_type = type->AsMatrix()) {
              number_of_members = matrix_type->element_count();
              type = matrix_type->element_type();
            } else if (const auto* struct_type = type->AsStruct()) {
              number_of_members =
                  static_cast<uint32_t>(struct_type->element_types().size());
              // The next value of |type| will be assigned when we know the
              // index of the OpTypeStruct's operand.
            } else {
              assert(false && "|inst| is not a composite");
              return;
            }

            if (number_of_members == 0) {
              return;
            }

            indices.push_back(
                GetFuzzerContext()->GetRandomCompositeExtractIndex(
                    number_of_members));

            if (const auto* struct_type = type->AsStruct()) {
              type = struct_type->element_types()[indices.back()];
            }
          } while (fuzzerutil::IsCompositeType(type) &&
                   GetFuzzerContext()->ChoosePercentage(
                       GetFuzzerContext()
                           ->GetChanceOfGoingDeeperToExtractComposite()));
        } else {
          const auto* dd = available_synonyms[GetFuzzerContext()->RandomIndex(
              available_synonyms)];

          composite_id = dd->object();
          indices.assign(dd->index().begin(), dd->index().end());
        }

        assert(composite_id != 0 && !indices.empty() &&
               "Composite object should have been chosen correctly");

        transformations.emplace_back(instruction_descriptor,
                                     GetFuzzerContext()->GetFreshId(),
                                     composite_id, indices);
      });

  for (const auto& transformation : transformations) {
    ApplyTransformation(transformation);
  }
}

}  // namespace fuzz
}  // namespace spvtools
<commit_msg>spirv-fuzz: Fix assertion failure in FuzzerPassAddCompositeExtract (#3995)<commit_after>// Copyright (c) 2020 Vasyl Teliman
//
// 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 "source/fuzz/fuzzer_pass_add_composite_extract.h"

#include "source/fuzz/fuzzer_context.h"
#include "source/fuzz/fuzzer_util.h"
#include "source/fuzz/instruction_descriptor.h"
#include "source/fuzz/transformation_composite_extract.h"

namespace spvtools {
namespace fuzz {

FuzzerPassAddCompositeExtract::FuzzerPassAddCompositeExtract(
    opt::IRContext* ir_context, TransformationContext* transformation_context,
    FuzzerContext* fuzzer_context,
    protobufs::TransformationSequence* transformations)
    : FuzzerPass(ir_context, transformation_context, fuzzer_context,
                 transformations) {}

FuzzerPassAddCompositeExtract::~FuzzerPassAddCompositeExtract() = default;

void FuzzerPassAddCompositeExtract::Apply() {
  std::vector<const protobufs::DataDescriptor*> composite_synonyms;
  for (const auto* dd :
       GetTransformationContext()->GetFactManager()->GetAllSynonyms()) {
    // |dd| must describe a component of a composite.
    if (!dd->index().empty()) {
      composite_synonyms.push_back(dd);
    }
  }

  // We don't want to invalidate the module every time we apply this
  // transformation since rebuilding DominatorAnalysis can be expensive, so we
  // collect up the transformations we wish to apply and apply them all later.
  std::vector<TransformationCompositeExtract> transformations;

  ForEachInstructionWithInstructionDescriptor(
      [this, &composite_synonyms, &transformations](
          opt::Function* function, opt::BasicBlock* block,
          opt::BasicBlock::iterator inst_it,
          const protobufs::InstructionDescriptor& instruction_descriptor) {
        if (!fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpCompositeExtract,
                                                          inst_it)) {
          return;
        }

        if (!GetFuzzerContext()->ChoosePercentage(
                GetFuzzerContext()->GetChanceOfAddingCompositeExtract())) {
          return;
        }

        auto available_composites = FindAvailableInstructions(
            function, block, inst_it,
            [](opt::IRContext* ir_context, opt::Instruction* inst) {
              return inst->type_id() && inst->result_id() &&
                     fuzzerutil::IsCompositeType(
                         ir_context->get_type_mgr()->GetType(inst->type_id()));
            });

        std::vector<const protobufs::DataDescriptor*> available_synonyms;
        for (const auto* dd : composite_synonyms) {
          if (fuzzerutil::IdIsAvailableBeforeInstruction(
                  GetIRContext(), &*inst_it, dd->object())) {
            available_synonyms.push_back(dd);
          }
        }

        if (available_synonyms.empty() && available_composites.empty()) {
          return;
        }

        uint32_t composite_id = 0;
        std::vector<uint32_t> indices;

        if (available_synonyms.empty() || (!available_composites.empty() &&
                                           GetFuzzerContext()->ChooseEven())) {
          const auto* inst =
              available_composites[GetFuzzerContext()->RandomIndex(
                  available_composites)];
          composite_id = inst->result_id();

          auto type_id = inst->type_id();
          do {
            uint32_t number_of_members = 0;

            const auto* type_inst =
                GetIRContext()->get_def_use_mgr()->GetDef(type_id);
            assert(type_inst && "Composite instruction has invalid type id");

            switch (type_inst->opcode()) {
              case SpvOpTypeArray:
                number_of_members =
                    fuzzerutil::GetArraySize(*type_inst, GetIRContext());
                break;
              case SpvOpTypeVector:
              case SpvOpTypeMatrix:
                number_of_members = type_inst->GetSingleWordInOperand(1);
                break;
              case SpvOpTypeStruct:
                number_of_members = type_inst->NumInOperands();
                break;
              default:
                assert(false && "|type_inst| is not a composite");
                return;
            }

            if (number_of_members == 0) {
              return;
            }

            indices.push_back(
                GetFuzzerContext()->GetRandomCompositeExtractIndex(
                    number_of_members));

            switch (type_inst->opcode()) {
              case SpvOpTypeArray:
              case SpvOpTypeVector:
              case SpvOpTypeMatrix:
                type_id = type_inst->GetSingleWordInOperand(0);
                break;
              case SpvOpTypeStruct:
                type_id = type_inst->GetSingleWordInOperand(indices.back());
                break;
              default:
                assert(false && "|type_inst| is not a composite");
                return;
            }
          } while (fuzzerutil::IsCompositeType(
                       GetIRContext()->get_type_mgr()->GetType(type_id)) &&
                   GetFuzzerContext()->ChoosePercentage(
                       GetFuzzerContext()
                           ->GetChanceOfGoingDeeperToExtractComposite()));
        } else {
          const auto* dd = available_synonyms[GetFuzzerContext()->RandomIndex(
              available_synonyms)];

          composite_id = dd->object();
          indices.assign(dd->index().begin(), dd->index().end());
        }

        assert(composite_id != 0 && !indices.empty() &&
               "Composite object should have been chosen correctly");

        transformations.emplace_back(instruction_descriptor,
                                     GetFuzzerContext()->GetFreshId(),
                                     composite_id, indices);
      });

  for (const auto& transformation : transformations) {
    ApplyTransformation(transformation);
  }
}

}  // namespace fuzz
}  // namespace spvtools
<|endoftext|>


<commit_before>#pragma once

#include "c.hpp"
#include "global.hpp"

namespace WonderRabbitProject
{
  namespace SQLite3
  {
    struct runtime_error
      : public std::runtime_error
    {
      const RESULT_CODE result_code;
      runtime_error( const std::string& message, const RESULT_CODE r )
        : std::runtime_error( message )
        , result_code( r )
      { }
    };

    inline void validate(RESULT_CODE r)
    {
      switch(r)
      {
        case RESULT_CODE::OK:
        case RESULT_CODE::ROW:
        case RESULT_CODE::DONE:
          return;
        default:
          // ToDo: to_string(RESULT_CODE)
          auto m = u8"FAIL; RESULT_CODE is " + std::to_string( static_cast< int >( r ) );
          throw runtime_error( m );
      }
    }

    struct zeroblob_size_t final
    {
      explicit zeroblob_size_t(size_t size__) noexcept
        : size_(size__)
      { }
      size_t size() const
      { return size_; }
    private:
      const size_t size_;
    };
  }
}
<commit_msg>fix-up<commit_after>#pragma once

#include "c.hpp"
#include "global.hpp"

namespace WonderRabbitProject
{
  namespace SQLite3
  {
    struct runtime_error
      : public std::runtime_error
    {
      const RESULT_CODE result_code;
      runtime_error( const std::string& message, const RESULT_CODE r )
        : std::runtime_error( message )
        , result_code( r )
      { }
    };

    inline void validate(RESULT_CODE r)
    {
      switch(r)
      {
        case RESULT_CODE::OK:
        case RESULT_CODE::ROW:
        case RESULT_CODE::DONE:
          return;
        default:
          // ToDo: to_string(RESULT_CODE)
          auto m = u8"FAIL; RESULT_CODE is " + std::to_string( static_cast< int >( r ) );
          throw runtime_error( m, r );
      }
    }

    struct zeroblob_size_t final
    {
      explicit zeroblob_size_t(size_t size__) noexcept
        : size_(size__)
      { }
      size_t size() const
      { return size_; }
    private:
      const size_t size_;
    };
  }
}
<|endoftext|>


<commit_before><commit_msg>[IMP] Increased default custom fields number.<commit_after><|endoftext|>


<commit_before>// 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

#ifndef __PROCESS_WINDOWS_JOBOBJECT_HPP__
#define __PROCESS_WINDOWS_JOBOBJECT_HPP__

#include <map>
#include <string>

#include <stout/lambda.hpp>
#include <stout/nothing.hpp>
#include <stout/windows.hpp> // For `SharedHandle`.
#include <stout/windows/os.hpp> // For `os` namespace.

#include <process/defer.hpp>
#include <process/future.hpp>
#include <process/reap.hpp>
#include <process/subprocess.hpp>
#include <process/process.hpp>

#include <glog/logging.h> // For `CHECK` macro.

namespace process {
namespace internal {

class JobObjectManager : public Process<JobObjectManager>
{
public:
  JobObjectManager() : ProcessBase("__job_object_manager") {}
  virtual ~JobObjectManager() {}

  void manage(
      const pid_t pid,
      const std::string& name,
      const SharedHandle& handle)
  {
    jobs.emplace(pid, JobData{name, handle});

    process::reap(pid)
      .onAny(defer(self(), &Self::cleanup, lambda::_1, pid));
  }

protected:
  void cleanup(Future<Option<int>> exit_code, const pid_t pid)
  {
    CHECK(!exit_code.isPending());
    CHECK(!exit_code.isDiscarded());

    Try<Nothing> killJobResult = os::kill_job(jobs.at(pid).handle);
    CHECK(!killJobResult.isError())
      << "Failed to kill job object: " << killJobResult.error();

    // Finally, erase the `JobData`, closing the last handle to the job object.
    // All functionality requiring a live job object handle (but possibly a
    // dead process) must happen prior to this, e.g. in a another parent hook.
    jobs.erase(pid);
  }

private:
  struct JobData {
    std::string name;
    SharedHandle handle;
  };

  std::map<pid_t, JobData> jobs;
};

// Global job object manager process. Defined in `process.cpp`.
extern PID<JobObjectManager> job_object_manager;

} // namespace internal {

inline Subprocess::ParentHook Subprocess::ParentHook::CREATE_JOB() {
  return Subprocess::ParentHook([](pid_t pid) -> Try<Nothing> {
    // NOTE: There are two very important parts to this hook. First, Windows
    // does not have a process hierarchy in the same sense that Unix does, so
    // in order to be able to kill a task, we have to put it in a job object.
    // Then, when we terminate the job object, it will terminate all the
    // processes in the task (including any processes that were subsequently
    // created by any process in this task). Second, the lifetime of the job
    // object is greater than the lifetime of the processes it contains. Thus
    // the job object handle is explicitly owned by the global job object
    // manager process.
    Try<std::string> name = os::name_job(pid);
    if (name.isError()) {
      return Error(name.error());
    }

    // This creates a named job object in the Windows kernel.
    // This handle must remain in scope (and open) until
    // a running process is assigned to it.
    Try<SharedHandle> handle = os::create_job(name.get());
    if (handle.isError()) {
      return Error(handle.error());
    }

    // This actually assigns the process `pid` to the job object.
    Try<Nothing> result = os::assign_job(handle.get(), pid);
    if (result.isError()) {
      return Error(result.error());
    }

    // Save the handle to the job object to ensure the object remains
    // open for the entire lifetime of the agent process, and is closed
    // when the process is reaped.
    dispatch(
      process::internal::job_object_manager,
      &process::internal::JobObjectManager::manage,
      pid,
      name.get(),
      handle.get());

    return Nothing();
  });
}

} // namespace process {

#endif // __PROCESS_WINDOWS_JOBOBJECT_HPP__
<commit_msg>Windows: Updated job object name types to `wstring`.<commit_after>// 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

#ifndef __PROCESS_WINDOWS_JOBOBJECT_HPP__
#define __PROCESS_WINDOWS_JOBOBJECT_HPP__

#include <map>
#include <string>

#include <stout/lambda.hpp>
#include <stout/nothing.hpp>
#include <stout/windows.hpp> // For `SharedHandle`.
#include <stout/windows/os.hpp> // For `os` namespace.

#include <process/defer.hpp>
#include <process/future.hpp>
#include <process/reap.hpp>
#include <process/subprocess.hpp>
#include <process/process.hpp>

#include <glog/logging.h> // For `CHECK` macro.

namespace process {
namespace internal {

class JobObjectManager : public Process<JobObjectManager>
{
public:
  JobObjectManager() : ProcessBase("__job_object_manager") {}
  virtual ~JobObjectManager() {}

  void manage(
      const pid_t pid,
      const std::wstring& name,
      const SharedHandle& handle)
  {
    jobs.emplace(pid, JobData{name, handle});

    process::reap(pid)
      .onAny(defer(self(), &Self::cleanup, lambda::_1, pid));
  }

protected:
  void cleanup(Future<Option<int>> exit_code, const pid_t pid)
  {
    CHECK(!exit_code.isPending());
    CHECK(!exit_code.isDiscarded());

    Try<Nothing> killJobResult = os::kill_job(jobs.at(pid).handle);
    CHECK(!killJobResult.isError())
      << "Failed to kill job object: " << killJobResult.error();

    // Finally, erase the `JobData`, closing the last handle to the job object.
    // All functionality requiring a live job object handle (but possibly a
    // dead process) must happen prior to this, e.g. in a another parent hook.
    jobs.erase(pid);
  }

private:
  struct JobData {
    std::wstring name;
    SharedHandle handle;
  };

  std::map<pid_t, JobData> jobs;
};

// Global job object manager process. Defined in `process.cpp`.
extern PID<JobObjectManager> job_object_manager;

} // namespace internal {

inline Subprocess::ParentHook Subprocess::ParentHook::CREATE_JOB() {
  return Subprocess::ParentHook([](pid_t pid) -> Try<Nothing> {
    // NOTE: There are two very important parts to this hook. First, Windows
    // does not have a process hierarchy in the same sense that Unix does, so
    // in order to be able to kill a task, we have to put it in a job object.
    // Then, when we terminate the job object, it will terminate all the
    // processes in the task (including any processes that were subsequently
    // created by any process in this task). Second, the lifetime of the job
    // object is greater than the lifetime of the processes it contains. Thus
    // the job object handle is explicitly owned by the global job object
    // manager process.
    Try<std::wstring> name = os::name_job(pid);
    if (name.isError()) {
      return Error(name.error());
    }

    // This creates a named job object in the Windows kernel.
    // This handle must remain in scope (and open) until
    // a running process is assigned to it.
    Try<SharedHandle> handle = os::create_job(name.get());
    if (handle.isError()) {
      return Error(handle.error());
    }

    // This actually assigns the process `pid` to the job object.
    Try<Nothing> result = os::assign_job(handle.get(), pid);
    if (result.isError()) {
      return Error(result.error());
    }

    // Save the handle to the job object to ensure the object remains
    // open for the entire lifetime of the agent process, and is closed
    // when the process is reaped.
    dispatch(
      process::internal::job_object_manager,
      &process::internal::JobObjectManager::manage,
      pid,
      name.get(),
      handle.get());

    return Nothing();
  });
}

} // namespace process {

#endif // __PROCESS_WINDOWS_JOBOBJECT_HPP__
<|endoftext|>