<commit_before>/*
 * Main Menu-bar
 */

#include <stdint.h>
#include <stdio.h>

#include <vector>

#include <SDL2/SDL.h>

#include "imgui.h"

extern "C" {

#include "util.h"
#include "snepulator.h"
#include "config.h"
#include "database/sms_db.h"

#include "gamepad.h"
#include "video/tms9928a.h"
#include "video/sms_vdp.h"
#include "cpu/z80.h"

#include "sg-1000.h"
#include "sms.h"
#include "colecovision.h"

extern Z80_Regs z80_regs;
extern TMS9928A_Mode sms_vdp_mode_get (void);

/* TODO: Access through a function instead of accessing the array */
extern Gamepad_Instance gamepad_list[128];
extern uint32_t gamepad_list_count;
extern Snepulator_Gamepad gamepad_1;
extern Snepulator_Gamepad gamepad_2;
}

#include "gui/input.h"
#include "gui/menubar.h"
#include "gui/open.h"
extern Snepulator_State state;
extern File_Open_State open_state;
extern bool config_capture_events; /* TODO: Move into state */

void snepulator_load_rom (char *path);
void snepulator_load_sms_bios (char *path);
void snepulator_load_colecovision_bios (char *path);

/*
 * Render the menubar.
 */
void snepulator_render_menubar (void)
{
    bool open_modal = false;
    bool input_modal = false;

    if (ImGui::BeginMainMenuBar ())
    {
        if (ImGui::BeginMenu ("File"))
        {
            if (ImGui::MenuItem ("Open ROM...", NULL))
            {
                state.running = false;
                open_state.title = "Open ROM...";
                snepulator_set_open_regex (".*\\.(bin|col|gg|sg|sms)$");
                open_state.callback = snepulator_load_rom;
                open_modal = true;
            }

            if (ImGui::BeginMenu ("Open BIOS"))
            {
                if (ImGui::MenuItem ("Master System...", NULL))
                {
                    state.running = false;
                    open_state.title = "Open Master System BIOS...";
                    snepulator_set_open_regex (".*\\.(bin|sms)$");
                    open_state.callback = snepulator_load_sms_bios;
                    open_modal = true;
                }
                if (ImGui::MenuItem ("ColecoVision...", NULL))
                {
                    state.running = false;
                    open_state.title = "Open ColecoVision BIOS...";
                    snepulator_set_open_regex (".*\\.(col)$");
                    open_state.callback = snepulator_load_colecovision_bios;
                    open_modal = true;
                }
                if (ImGui::BeginMenu ("Clear"))
                {
                    if (ImGui::MenuItem ("Master System", NULL))
                    {
                        config_entry_remove ("sms", "bios");
                        config_write ();
                        if (state.sms_bios_filename != NULL)
                        {
                            free (state.sms_bios_filename);
                            state.sms_bios_filename = NULL;
                        }
                    }
                    if (ImGui::MenuItem ("ColecoVision", NULL))
                    {
                        config_entry_remove ("colecovision", "bios");
                        config_write ();
                        if (state.colecovision_bios_filename != NULL)
                        {
                            free (state.colecovision_bios_filename);
                            state.colecovision_bios_filename = NULL;
                        }
                    }
                    ImGui::EndMenu ();
                }
                ImGui::EndMenu ();
            }

            if (ImGui::MenuItem ("Close ROM", NULL))
            {
                snepulator_reset ();
                snepulator_draw_logo ();
            }

            if (ImGui::MenuItem ("Pause", NULL, !state.running)) {
                if (state.ready) {
                    if (state.running)
                    {
                        snepulator_pause ();
                    }
                    else
                    {
                        state.running = true;
                    }
                }
            }
            ImGui::Separator ();
            if (ImGui::MenuItem ("Quit", NULL)) { state.abort = true; }
            ImGui::EndMenu ();
        }

        if (ImGui::BeginMenu ("Audio"))
        {
            if (ImGui::BeginMenu ("Device"))
            {
                int count = SDL_GetNumAudioDevices (0);
                for (int i = 0; i < count; i++)
                {
                    const char *audio_device_name = SDL_GetAudioDeviceName (i, 0);
                    if (audio_device_name == NULL)
                        audio_device_name = "Unknown Audio Device";

                    if (ImGui::MenuItem (audio_device_name, NULL)) { }
                }
                ImGui::EndMenu ();
            }
            ImGui::EndMenu ();
        }

        if (ImGui::BeginMenu ("Video"))
        {
            if (ImGui::BeginMenu ("Filter"))
            {
                if (ImGui::MenuItem ("Dot Matrix",  NULL, state.video_filter == VIDEO_FILTER_DOT_MATRIX))
                {
                    state.video_filter = VIDEO_FILTER_DOT_MATRIX;
                    config_string_set ("video", "filter", "Dot Matrix");
                    config_write ();
                }
                if (ImGui::MenuItem ("Linear Interpolation",  NULL, state.video_filter == VIDEO_FILTER_LINEAR))
                {
                    state.video_filter = VIDEO_FILTER_LINEAR;
                    config_string_set ("video", "filter", "Linear");
                    config_write ();
                }
                if (ImGui::MenuItem ("Nearest Neighbour", NULL, state.video_filter == VIDEO_FILTER_NEAREST))
                {
                    state.video_filter = VIDEO_FILTER_NEAREST;
                    config_string_set ("video", "filter", "Nearest");
                    config_write ();
                }
                if (ImGui::MenuItem ("Scanlines",  NULL, state.video_filter == VIDEO_FILTER_SCANLINES))
                {
                    state.video_filter = VIDEO_FILTER_SCANLINES;
                    config_string_set ("video", "filter", "Scanlines");
                    config_write ();
                }
                ImGui::EndMenu ();
            }

            if (ImGui::BeginMenu ("3D Mode"))
            {
                if (ImGui::MenuItem ("Left image only", NULL, state.video_3d_mode == VIDEO_3D_LEFT_ONLY))
                {
                    state.video_3d_mode = VIDEO_3D_LEFT_ONLY;
                }
                if (ImGui::MenuItem ("Right image only", NULL, state.video_3d_mode == VIDEO_3D_RIGHT_ONLY))
                {
                    state.video_3d_mode = VIDEO_3D_RIGHT_ONLY;
                }
                if (ImGui::MenuItem ("Red-Cyan", NULL, state.video_3d_mode == VIDEO_3D_RED_CYAN))
                {
                    state.video_3d_mode = VIDEO_3D_RED_CYAN;
                }
                if (ImGui::MenuItem ("Red-Green", NULL, state.video_3d_mode == VIDEO_3D_RED_GREEN))
                {
                    state.video_3d_mode = VIDEO_3D_RED_GREEN;
                }
                if (ImGui::MenuItem ("Magenta-Green", NULL, state.video_3d_mode == VIDEO_3D_MAGENTA_GREEN))
                {
                    state.video_3d_mode = VIDEO_3D_MAGENTA_GREEN;
                }

                ImGui::Separator ();

                if (ImGui::BeginMenu ("Colour"))
                {
                    if (ImGui::MenuItem ("Saturation 0%", NULL, state.video_3d_saturation == 0.0))
                    {
                        state.video_3d_saturation = 0.0;
                    }
                    if (ImGui::MenuItem ("Saturation 25%", NULL, state.video_3d_saturation == 0.25))
                    {
                        state.video_3d_saturation = 0.25;
                    }
                    if (ImGui::MenuItem ("Saturation 50%", NULL, state.video_3d_saturation == 0.50))
                    {
                        state.video_3d_saturation = 0.50;
                    }
                    if (ImGui::MenuItem ("Saturation 75%", NULL, state.video_3d_saturation == 0.75))
                    {
                        state.video_3d_saturation = 0.75;
                    }
                    if (ImGui::MenuItem ("Saturation 100%", NULL, state.video_3d_saturation == 1.0))
                    {
                        state.video_3d_saturation = 1.0;
                    }
                    ImGui::EndMenu ();
                }

                ImGui::EndMenu ();
            }

            if (ImGui::MenuItem ("Take Screenshot"))
            {
                snepulator_take_screenshot ();
            }

            ImGui::EndMenu ();
        }

        if (ImGui::BeginMenu ("Console"))
        {
            if (ImGui::MenuItem ("Hard Reset"))
            {
                snepulator_system_init ();
            }
            ImGui::Separator ();

            if (ImGui::MenuItem ("World", NULL, state.region == REGION_WORLD)) {
                state.region = REGION_WORLD;
                config_string_set ("sms", "region", "World");
                config_write ();
            }
            if (ImGui::MenuItem ("Japan", NULL, state.region == REGION_JAPAN)) {
                state.region = REGION_JAPAN;
                config_string_set ("sms", "region", "Japan");
                config_write ();
            }
            ImGui::Separator ();

            if (ImGui::MenuItem ("Auto", NULL, state.format_auto)) {
                state.format_auto = true;
                config_string_set ("sms", "format", "Auto");
                config_write ();

                if (state.ready == true)
                {
                    if (state.rom_hints & SMS_HINT_PAL_ONLY)
                    {
                        state.format = VIDEO_FORMAT_PAL;
                    }
                    else
                    {
                        state.format = VIDEO_FORMAT_NTSC;
                    }
                }
            }
            if (ImGui::MenuItem ("NTSC", NULL, state.format == VIDEO_FORMAT_NTSC)) {
                state.format = VIDEO_FORMAT_NTSC;
                state.format_auto = false;
                config_string_set ("sms", "format", "NTSC");
                config_write ();
            }
            if (ImGui::MenuItem ("PAL",  NULL, state.format == VIDEO_FORMAT_PAL))  {
                state.format = VIDEO_FORMAT_PAL;
                state.format_auto = false;
                config_string_set ("sms", "format", "PAL");
                config_write ();
            }
            ImGui::Separator ();

            if (ImGui::BeginMenu ("Info"))
            {
                ImGui::Text ("%s", state.console == CONSOLE_MASTER_SYSTEM ? "Master System" :
                                   state.console == CONSOLE_GAME_GEAR     ? "Game Gear" :
                                   state.console == CONSOLE_SG_1000       ? "SG-1000" :
                                   state.console == CONSOLE_COLECOVISION  ? "ColecoVision" :
                                   "N/A");

                ImGui::Separator ();

                ImGui::Text ("CPU");
                ImGui::Text ("PC : %04x    SP : %04x", z80_regs.pc, z80_regs.sp);
                ImGui::Text ("AF : %04x    BC : %04x", z80_regs.af, z80_regs.bc);
                ImGui::Text ("DE : %04x    HL : %04x", z80_regs.de, z80_regs.hl);
                ImGui::Text ("IX : %04x    IY : %04x", z80_regs.ix, z80_regs.iy);
                ImGui::Text ("IM : %d       IFF: %d/%d", z80_regs.im, z80_regs.iff1, z80_regs.iff2);

                ImGui::Separator ();

                ImGui::Text ("Video");
                ImGui::Text ("Mode : %s", tms9928a_mode_name_get (sms_vdp_mode_get ()));

                ImGui::EndMenu ();
            }
            if (ImGui::BeginMenu ("Statistics"))
            {
                ImGui::Text ("Video");
                ImGui::Text ("Host: %.2f fps", state.host_framerate);
                ImGui::Text ("VDP:  %.2f fps", state.vdp_framerate);
                ImGui::Separator ();
                ImGui::Text ("Audio");
                ImGui::Text ("Ring buffer: %.2f%% full", state.audio_ring_utilisation * 100.0);

                ImGui::EndMenu ();
            }
            if (ImGui::MenuItem ("Time Five Minutes", NULL))
            {
                uint32_t start_time;
                uint32_t end_time;
                state.running = false;
                start_time = SDL_GetTicks ();
                state.run (5 * 60000); /* Simulate five minutes */
                end_time = SDL_GetTicks ();
                state.running = true;

                fprintf (stdout, "[DEBUG] Took %d ms to emulate five minutes. (%fx speed-up)\n",
                         end_time - start_time, (5.0 * 60000.0) / (end_time - start_time));
            }

            ImGui::EndMenu ();
        }

        if (ImGui::BeginMenu ("Input"))
        {

            if (ImGui::BeginMenu ("Player 1"))
            {
                if (ImGui::BeginMenu ("Type"))
                {
                    if (ImGui::MenuItem ("Auto", NULL, gamepad_1.type_auto))
                    {
                        gamepad_1.type_auto = true;
                    }
                    if (ImGui::MenuItem ("SMS Gamepad", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS))
                    {
                        gamepad_1.type = GAMEPAD_TYPE_SMS;
                        gamepad_1.type_auto = false;
                    }
                    if (ImGui::MenuItem ("SMS Light Phaser", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS_PHASER))
                    {
                        gamepad_1.type = GAMEPAD_TYPE_SMS_PHASER;
                        gamepad_1.type_auto = false;
                    }
                    if (ImGui::MenuItem ("SMS Paddle", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS_PADDLE))
                    {
                        gamepad_1.type = GAMEPAD_TYPE_SMS_PADDLE;
                        gamepad_1.type_auto = false;
                    }
                    ImGui::EndMenu ();
                }

                ImGui::Separator ();

                for (int i = 0; i < gamepad_list_count; i++)
                {
                    if (ImGui::MenuItem (gamepad_get_name (i), NULL, gamepad_list [i].instance_id == gamepad_1.instance_id))
                    {
                        gamepad_change_device (1, i);
                    }
                }
                ImGui::EndMenu ();
            }
            if (ImGui::BeginMenu ("Player 2"))
            {
                for (int i = 0; i < gamepad_list_count; i++)
                {
                    if (ImGui::MenuItem (gamepad_get_name (i), NULL, gamepad_list [i].instance_id == gamepad_2.instance_id))
                    {
                        gamepad_change_device (2, i);
                    }
                }
                ImGui::EndMenu ();
            }

            if (ImGui::MenuItem ("Configure...", NULL))
            {
                input_start ();
                input_modal = true;
            }
            ImGui::EndMenu ();
        }

        ImGui::EndMainMenuBar ();
    }

    /* Open any popups requested */
    if (open_modal)
    {
        ImGui::OpenPopup (open_state.title);
    }
    if (input_modal)
    {
        config_capture_events = true;
        ImGui::OpenPopup ("Configure device...");
    }

}
<commit_msg>gui: Re-order menubar<commit_after>/*
 * Main Menu-bar
 */

#include <stdint.h>
#include <stdio.h>

#include <vector>

#include <SDL2/SDL.h>

#include "imgui.h"

extern "C" {

#include "util.h"
#include "snepulator.h"
#include "config.h"
#include "database/sms_db.h"

#include "gamepad.h"
#include "video/tms9928a.h"
#include "video/sms_vdp.h"
#include "cpu/z80.h"

#include "sg-1000.h"
#include "sms.h"
#include "colecovision.h"

extern Z80_Regs z80_regs;
extern TMS9928A_Mode sms_vdp_mode_get (void);

/* TODO: Access through a function instead of accessing the array */
extern Gamepad_Instance gamepad_list[128];
extern uint32_t gamepad_list_count;
extern Snepulator_Gamepad gamepad_1;
extern Snepulator_Gamepad gamepad_2;
}

#include "gui/input.h"
#include "gui/menubar.h"
#include "gui/open.h"
extern Snepulator_State state;
extern File_Open_State open_state;
extern bool config_capture_events; /* TODO: Move into state */

void snepulator_load_rom (char *path);
void snepulator_load_sms_bios (char *path);
void snepulator_load_colecovision_bios (char *path);

/*
 * Render the menubar.
 */
void snepulator_render_menubar (void)
{
    bool open_modal = false;
    bool input_modal = false;

    if (ImGui::BeginMainMenuBar ())
    {
        if (ImGui::BeginMenu ("File"))
        {
            if (ImGui::MenuItem ("Open ROM...", NULL))
            {
                state.running = false;
                open_state.title = "Open ROM...";
                snepulator_set_open_regex (".*\\.(bin|col|gg|sg|sms)$");
                open_state.callback = snepulator_load_rom;
                open_modal = true;
            }

            if (ImGui::BeginMenu ("Open BIOS"))
            {
                if (ImGui::MenuItem ("Master System...", NULL))
                {
                    state.running = false;
                    open_state.title = "Open Master System BIOS...";
                    snepulator_set_open_regex (".*\\.(bin|sms)$");
                    open_state.callback = snepulator_load_sms_bios;
                    open_modal = true;
                }
                if (ImGui::MenuItem ("ColecoVision...", NULL))
                {
                    state.running = false;
                    open_state.title = "Open ColecoVision BIOS...";
                    snepulator_set_open_regex (".*\\.(col)$");
                    open_state.callback = snepulator_load_colecovision_bios;
                    open_modal = true;
                }
                if (ImGui::BeginMenu ("Clear"))
                {
                    if (ImGui::MenuItem ("Master System", NULL))
                    {
                        config_entry_remove ("sms", "bios");
                        config_write ();
                        if (state.sms_bios_filename != NULL)
                        {
                            free (state.sms_bios_filename);
                            state.sms_bios_filename = NULL;
                        }
                    }
                    if (ImGui::MenuItem ("ColecoVision", NULL))
                    {
                        config_entry_remove ("colecovision", "bios");
                        config_write ();
                        if (state.colecovision_bios_filename != NULL)
                        {
                            free (state.colecovision_bios_filename);
                            state.colecovision_bios_filename = NULL;
                        }
                    }
                    ImGui::EndMenu ();
                }
                ImGui::EndMenu ();
            }

            if (ImGui::MenuItem ("Close ROM", NULL))
            {
                snepulator_reset ();
                snepulator_draw_logo ();
            }

            if (ImGui::MenuItem ("Pause", NULL, !state.running)) {
                if (state.ready) {
                    if (state.running)
                    {
                        snepulator_pause ();
                    }
                    else
                    {
                        state.running = true;
                    }
                }
            }
            ImGui::Separator ();
            if (ImGui::MenuItem ("Quit", NULL)) { state.abort = true; }
            ImGui::EndMenu ();
        }

        if (ImGui::BeginMenu ("Console"))
        {
            if (ImGui::MenuItem ("Hard Reset"))
            {
                snepulator_system_init ();
            }
            ImGui::Separator ();

            if (ImGui::MenuItem ("World", NULL, state.region == REGION_WORLD)) {
                state.region = REGION_WORLD;
                config_string_set ("sms", "region", "World");
                config_write ();
            }
            if (ImGui::MenuItem ("Japan", NULL, state.region == REGION_JAPAN)) {
                state.region = REGION_JAPAN;
                config_string_set ("sms", "region", "Japan");
                config_write ();
            }
            ImGui::Separator ();

            if (ImGui::MenuItem ("Auto", NULL, state.format_auto)) {
                state.format_auto = true;
                config_string_set ("sms", "format", "Auto");
                config_write ();

                if (state.ready == true)
                {
                    if (state.rom_hints & SMS_HINT_PAL_ONLY)
                    {
                        state.format = VIDEO_FORMAT_PAL;
                    }
                    else
                    {
                        state.format = VIDEO_FORMAT_NTSC;
                    }
                }
            }
            if (ImGui::MenuItem ("NTSC", NULL, state.format == VIDEO_FORMAT_NTSC)) {
                state.format = VIDEO_FORMAT_NTSC;
                state.format_auto = false;
                config_string_set ("sms", "format", "NTSC");
                config_write ();
            }
            if (ImGui::MenuItem ("PAL",  NULL, state.format == VIDEO_FORMAT_PAL))  {
                state.format = VIDEO_FORMAT_PAL;
                state.format_auto = false;
                config_string_set ("sms", "format", "PAL");
                config_write ();
            }
            ImGui::Separator ();

            if (ImGui::BeginMenu ("Info"))
            {
                ImGui::Text ("%s", state.console == CONSOLE_MASTER_SYSTEM ? "Master System" :
                                   state.console == CONSOLE_GAME_GEAR     ? "Game Gear" :
                                   state.console == CONSOLE_SG_1000       ? "SG-1000" :
                                   state.console == CONSOLE_COLECOVISION  ? "ColecoVision" :
                                   "N/A");

                ImGui::Separator ();

                ImGui::Text ("CPU");
                ImGui::Text ("PC : %04x    SP : %04x", z80_regs.pc, z80_regs.sp);
                ImGui::Text ("AF : %04x    BC : %04x", z80_regs.af, z80_regs.bc);
                ImGui::Text ("DE : %04x    HL : %04x", z80_regs.de, z80_regs.hl);
                ImGui::Text ("IX : %04x    IY : %04x", z80_regs.ix, z80_regs.iy);
                ImGui::Text ("IM : %d       IFF: %d/%d", z80_regs.im, z80_regs.iff1, z80_regs.iff2);

                ImGui::Separator ();

                ImGui::Text ("Video");
                ImGui::Text ("Mode : %s", tms9928a_mode_name_get (sms_vdp_mode_get ()));

                ImGui::EndMenu ();
            }
            if (ImGui::BeginMenu ("Statistics"))
            {
                ImGui::Text ("Video");
                ImGui::Text ("Host: %.2f fps", state.host_framerate);
                ImGui::Text ("VDP:  %.2f fps", state.vdp_framerate);
                ImGui::Separator ();
                ImGui::Text ("Audio");
                ImGui::Text ("Ring buffer: %.2f%% full", state.audio_ring_utilisation * 100.0);

                ImGui::EndMenu ();
            }
            if (ImGui::MenuItem ("Time Five Minutes", NULL))
            {
                uint32_t start_time;
                uint32_t end_time;
                state.running = false;
                start_time = SDL_GetTicks ();
                state.run (5 * 60000); /* Simulate five minutes */
                end_time = SDL_GetTicks ();
                state.running = true;

                fprintf (stdout, "[DEBUG] Took %d ms to emulate five minutes. (%fx speed-up)\n",
                         end_time - start_time, (5.0 * 60000.0) / (end_time - start_time));
            }

            ImGui::EndMenu ();
        }

        if (ImGui::BeginMenu ("Input"))
        {

            if (ImGui::BeginMenu ("Player 1"))
            {
                if (ImGui::BeginMenu ("Type"))
                {
                    if (ImGui::MenuItem ("Auto", NULL, gamepad_1.type_auto))
                    {
                        gamepad_1.type_auto = true;
                    }
                    if (ImGui::MenuItem ("SMS Gamepad", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS))
                    {
                        gamepad_1.type = GAMEPAD_TYPE_SMS;
                        gamepad_1.type_auto = false;
                    }
                    if (ImGui::MenuItem ("SMS Light Phaser", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS_PHASER))
                    {
                        gamepad_1.type = GAMEPAD_TYPE_SMS_PHASER;
                        gamepad_1.type_auto = false;
                    }
                    if (ImGui::MenuItem ("SMS Paddle", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS_PADDLE))
                    {
                        gamepad_1.type = GAMEPAD_TYPE_SMS_PADDLE;
                        gamepad_1.type_auto = false;
                    }
                    ImGui::EndMenu ();
                }

                ImGui::Separator ();

                for (int i = 0; i < gamepad_list_count; i++)
                {
                    if (ImGui::MenuItem (gamepad_get_name (i), NULL, gamepad_list [i].instance_id == gamepad_1.instance_id))
                    {
                        gamepad_change_device (1, i);
                    }
                }
                ImGui::EndMenu ();
            }
            if (ImGui::BeginMenu ("Player 2"))
            {
                for (int i = 0; i < gamepad_list_count; i++)
                {
                    if (ImGui::MenuItem (gamepad_get_name (i), NULL, gamepad_list [i].instance_id == gamepad_2.instance_id))
                    {
                        gamepad_change_device (2, i);
                    }
                }
                ImGui::EndMenu ();
            }

            if (ImGui::MenuItem ("Configure...", NULL))
            {
                input_start ();
                input_modal = true;
            }
            ImGui::EndMenu ();
        }

        if (ImGui::BeginMenu ("Audio"))
        {
            if (ImGui::BeginMenu ("Device"))
            {
                int count = SDL_GetNumAudioDevices (0);
                for (int i = 0; i < count; i++)
                {
                    const char *audio_device_name = SDL_GetAudioDeviceName (i, 0);
                    if (audio_device_name == NULL)
                        audio_device_name = "Unknown Audio Device";

                    if (ImGui::MenuItem (audio_device_name, NULL)) { }
                }
                ImGui::EndMenu ();
            }
            ImGui::EndMenu ();
        }

        if (ImGui::BeginMenu ("Video"))
        {
            if (ImGui::BeginMenu ("Filter"))
            {
                if (ImGui::MenuItem ("Dot Matrix",  NULL, state.video_filter == VIDEO_FILTER_DOT_MATRIX))
                {
                    state.video_filter = VIDEO_FILTER_DOT_MATRIX;
                    config_string_set ("video", "filter", "Dot Matrix");
                    config_write ();
                }
                if (ImGui::MenuItem ("Linear Interpolation",  NULL, state.video_filter == VIDEO_FILTER_LINEAR))
                {
                    state.video_filter = VIDEO_FILTER_LINEAR;
                    config_string_set ("video", "filter", "Linear");
                    config_write ();
                }
                if (ImGui::MenuItem ("Nearest Neighbour", NULL, state.video_filter == VIDEO_FILTER_NEAREST))
                {
                    state.video_filter = VIDEO_FILTER_NEAREST;
                    config_string_set ("video", "filter", "Nearest");
                    config_write ();
                }
                if (ImGui::MenuItem ("Scanlines",  NULL, state.video_filter == VIDEO_FILTER_SCANLINES))
                {
                    state.video_filter = VIDEO_FILTER_SCANLINES;
                    config_string_set ("video", "filter", "Scanlines");
                    config_write ();
                }
                ImGui::EndMenu ();
            }

            if (ImGui::BeginMenu ("3D Mode"))
            {
                if (ImGui::MenuItem ("Left image only", NULL, state.video_3d_mode == VIDEO_3D_LEFT_ONLY))
                {
                    state.video_3d_mode = VIDEO_3D_LEFT_ONLY;
                }
                if (ImGui::MenuItem ("Right image only", NULL, state.video_3d_mode == VIDEO_3D_RIGHT_ONLY))
                {
                    state.video_3d_mode = VIDEO_3D_RIGHT_ONLY;
                }
                if (ImGui::MenuItem ("Red-Cyan", NULL, state.video_3d_mode == VIDEO_3D_RED_CYAN))
                {
                    state.video_3d_mode = VIDEO_3D_RED_CYAN;
                }
                if (ImGui::MenuItem ("Red-Green", NULL, state.video_3d_mode == VIDEO_3D_RED_GREEN))
                {
                    state.video_3d_mode = VIDEO_3D_RED_GREEN;
                }
                if (ImGui::MenuItem ("Magenta-Green", NULL, state.video_3d_mode == VIDEO_3D_MAGENTA_GREEN))
                {
                    state.video_3d_mode = VIDEO_3D_MAGENTA_GREEN;
                }

                ImGui::Separator ();

                if (ImGui::BeginMenu ("Colour"))
                {
                    if (ImGui::MenuItem ("Saturation 0%", NULL, state.video_3d_saturation == 0.0))
                    {
                        state.video_3d_saturation = 0.0;
                    }
                    if (ImGui::MenuItem ("Saturation 25%", NULL, state.video_3d_saturation == 0.25))
                    {
                        state.video_3d_saturation = 0.25;
                    }
                    if (ImGui::MenuItem ("Saturation 50%", NULL, state.video_3d_saturation == 0.50))
                    {
                        state.video_3d_saturation = 0.50;
                    }
                    if (ImGui::MenuItem ("Saturation 75%", NULL, state.video_3d_saturation == 0.75))
                    {
                        state.video_3d_saturation = 0.75;
                    }
                    if (ImGui::MenuItem ("Saturation 100%", NULL, state.video_3d_saturation == 1.0))
                    {
                        state.video_3d_saturation = 1.0;
                    }
                    ImGui::EndMenu ();
                }

                ImGui::EndMenu ();
            }

            if (ImGui::MenuItem ("Take Screenshot"))
            {
                snepulator_take_screenshot ();
            }

            ImGui::EndMenu ();
        }

        ImGui::EndMainMenuBar ();
    }

    /* Open any popups requested */
    if (open_modal)
    {
        ImGui::OpenPopup (open_state.title);
    }
    if (input_modal)
    {
        config_capture_events = true;
        ImGui::OpenPopup ("Configure device...");
    }

}
<|endoftext|>


<commit_before>#include <cstdio>
#include <iostream>

using namespace std;

//program which uses a reference to set/change the values in an array
//notice that if you use double setval it wont work, only double& setval will work

double arr[] = { 0.01, 0.02, 0.03, 0.04, 0.05 }; //array

double& setval(int i) { //function to set values in array

	return arr[i];

}

int main() {

	cout << "values before change"<<endl;
	for (int i = 0;i < 5;i++) {
		cout << "arr["<<i<<"]=";
		cout << arr[i]<<endl;

	}

	cout << "values after change" << endl;
	for (int i = 0;i < 5;i++) {
		setval(0) = 1.0;
		setval(1) = 2.0;
		cout << "arr[" << i << "]=";
		cout << arr[i] << endl;

	}

	return 0;
}<commit_msg>changed position of & in function name<commit_after>#include <cstdio>
#include <iostream>

using namespace std;

//program which uses a reference to set/change the values in an array
//notice that if you use double setval it wont work, only double& setval will work

double arr[] = { 0.01, 0.02, 0.03, 0.04, 0.05 }; //array

double &setval(int i) { //function to set values in array

	return arr[i];

}

int main() {

	cout << "values before change"<<endl;
	for (int i = 0;i < 5;i++) {
		cout << "arr["<<i<<"]=";
		cout << arr[i]<<endl;

	}

	cout << "values after change" << endl;
	for (int i = 0;i < 5;i++) {
		setval(0) = 1.0;
		setval(1) = 2.0;
		cout << "arr[" << i << "]=";
		cout << arr[i] << endl;

	}

	return 0;
}<|endoftext|>


<commit_before><commit_msg>Remove DCHECK_NOTNULL(x) in favour of DCHECK(x != NULL)<commit_after><|endoftext|>


<commit_before>#include <random>
#include <gtest/gtest.h>
#include <boost/filesystem.hpp>
#include <boost/predef/os.h>
#include <qi/application.hpp>
#include <qi/log.hpp>
#include <qi/os.hpp>
#include <qi/path.hpp>

#include <errno.h>

#ifdef _WIN32
# include <windows.h>
# include <process.h>
# include <signal.h>
#else
# include <sys/wait.h>
#endif

/*
 * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */
// TODO2: Some tests to check the consume stack

static std::string binDir;
static std::string loopBinDir;

TEST(spawnvp, CmdWithNoArgs)
{
  char* args[] = {(char*)binDir.c_str(), NULL};

  int status = 0;

  int childPid = qi::os::spawnvp(args);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(42, status) << "status: " << status;
}

TEST(spawnvp, CmdWithArgs)
{
  char* args[] = {(char*)binDir.c_str(), (char*)"23", NULL};

  int status = 0;

  int childPid = qi::os::spawnvp(args);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(23, status) << "status: " << status;
}

TEST(spawnvp, CmdWithMultiArgs)
{
  char* args[] = {(char*)binDir.c_str(), (char*)"23", (char*)"-1", NULL};

  int status = 0;

  int childPid = qi::os::spawnvp(args);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(22, status) << "status: " << status;
}

TEST(spawnvp, InvalidBin)
{
  char* args[] = {(char*)"test42", NULL};

  int status = 0;

  int childPid = qi::os::spawnvp(args);
  EXPECT_EQ(-1, childPid);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(127, status) << "status: " << status;
}

TEST(spawnlp, CmdWithNoArgs)
{
  std::string bin = binDir.c_str();

  int status = 0;

  int childPid = qi::os::spawnlp(bin.c_str(), NULL);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(42, status) << "status: " << status;
}

TEST(spawnlp, CmdWithArgs)
{
  std::string bin = binDir.c_str();
  std::string arg1 = "23";
  int status = 0;

  int childPid = qi::os::spawnlp(bin.c_str(), arg1.c_str(), NULL);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(23, status) << "status: " << status;
}

TEST(spawnlp, CmdWithMultiArgs)
{
  std::string bin = binDir.c_str();
  std::string arg1 = "23";
  std::string arg2 = "-1";

  int status = 0;

  int childPid = qi::os::spawnlp(bin.c_str(), arg2.c_str(), arg1.c_str(), NULL);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(22, status) << "status: " << status;
}

TEST(spawnlp, Environment)
{
  // The check_env executable exits with rectode 1 if
  // the FOO environment var is not equal to BAR.
  std::string checkEnv = qi::path::findBin("check_env");
  int status = 0;
  qi::os::setenv("FOO", "BAR");
  int childPid = qi::os::spawnlp(checkEnv.c_str(), NULL);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, status) << "waitpid failed with retcode:   " << error;
  EXPECT_EQ(0, status) << "check_env failed with rectode: " << status;
}

TEST(spawnlp, InvalidBin)
{
  std::string bin = "test42";
  int status = 0;

  int childPid = qi::os::spawnlp(bin.c_str(), NULL);
  EXPECT_EQ(-1, childPid);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(127, status) << "status: " << status;
}

TEST(kill, Terminate)
{
  int status = 0;
  int alive = -1;
  int killed = -1;
  int dead = 0;

  int childPid = qi::os::spawnlp(loopBinDir.c_str(), NULL);
  ASSERT_NE(-1, childPid);

  if (childPid != -1)
  {
    qi::os::sleep(1);

    // is it alive?
    alive = qi::os::kill(childPid, 0);

    // let's kill it
    killed = qi::os::kill(childPid, SIGTERM);
    qi::os::waitpid(childPid, &status);

    // is it dead?
    dead = qi::os::kill(childPid, 0);
  }

  EXPECT_EQ(0, alive) << "alive: " << alive;
  EXPECT_EQ(0, killed) << "killed: " << killed;
  EXPECT_EQ(-1, dead) << "dead: " << dead;
}

#ifdef _MSC_VER
# define SIGKILL 9 // not defined on windows and ignored by kill
#endif

TEST(kill, Kill)
{
  int status = 0;
  int alive = -1;
  int killed = -1;
  int dead = 0;

  int childPid = qi::os::spawnlp(loopBinDir.c_str(), NULL);
  ASSERT_NE(-1, childPid);

  if (childPid != -1)
  {
    qi::os::sleep(1);

    // is it alive?
    alive = qi::os::kill(childPid, 0);

    // let's kill it
    killed = qi::os::kill(childPid, SIGKILL);
    qi::os::waitpid(childPid, &status);

    // is it dead?
    dead = qi::os::kill(childPid, 0);
  }

  EXPECT_EQ(0, alive) << "alive: " << alive;
  EXPECT_EQ(0, killed) << "killed: " << killed;
  EXPECT_EQ(-1, dead) << "dead: " << dead;
}

TEST(system, CmdWithNoArgs)
{
  std::string bin = binDir;

  int status = qi::os::system(bin.c_str());

  EXPECT_EQ(42, status) << "status: " << status;
}

TEST(system, CmdWithArgs)
{
  std::string bin = binDir + " 23";

  int status = qi::os::system(bin.c_str());

  EXPECT_EQ(23, status) << "status: " << status;
}

TEST(system, CmdWithMultiArgs)
{
  std::string bin = binDir + " 23 -1";

  int status = qi::os::system(bin.c_str());

  EXPECT_EQ(22, status) << "status: " << status;
}

TEST(system, InvalidBin)
{
  std::string bin = "test42";

  int status = qi::os::system(bin.c_str());

 #ifdef _WIN32
  EXPECT_EQ(1, status) << "status: " << status;
 #else
  EXPECT_EQ(127, status) << "status: " << status;
 #endif
}

//============================================================================
// Tests for checking isProcessRunning
//============================================================================
namespace
{
int randInt(int min, int max)
{
  static std::random_device rd;
  static std::mt19937 gen(rd());
  std::uniform_int_distribution<int> dis(min, max);
  return dis(gen);
}

char randomProcessChar()
{
  static const char* characters =
  "0123456789"
  "-_ "
  "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  "abcdefghijklmnopqrstuvwxyz";
  static int nofChars = strlen(characters) - 1;
  return characters[randInt(1, nofChars)];
}

std::string randomProcessName()
{
  std::string str;
  int length = 2 + rand() % 10;
  for(int i = 0; i < length; ++i)
  {
    str.push_back(randomProcessChar());
  }
  return str;
}

int randomWrongPid()
{
  return randInt(65565, std::numeric_limits<int>::max());
}

class ScopedProcess
{
public:
  ScopedProcess(
      const std::string& executable,
      const std::vector<std::string>& arguments = std::vector<std::string>())
    : _executable(executable)
  {
    char** cArgs = new char*[arguments.size()+2];
    cArgs[0] = (char*)_executable.c_str();
    for(size_t i = 0; i < arguments.size(); ++i)
      cArgs[i+1] = (char*)arguments[i].c_str();
    cArgs[arguments.size()+1] = NULL;
    _pid = qi::os::spawnvp(cArgs);
    if (_pid <= 0)
      throw std::runtime_error(
          std::string("Could not start: ") + _executable);
  }

  ~ScopedProcess()
  {
    qi::os::kill(_pid, SIGKILL);
    int status = 0;
    int ret = qi::os::waitpid(_pid, &status);
    std::cout << "Waiting for " << _executable << " has yielded the status "
                << status << " and returned " << ret << std::endl;
  }

  int pid() const
  {
    return _pid;
  }

private:
  std::string _executable;
  int _pid;
};

} // ends anonymous namespace

TEST(QiOs, isProcessRunningCrazyPid)
{
  ASSERT_FALSE(qi::os::isProcessRunning(randomWrongPid(), randomProcessName()));
}

TEST(QiOs, isProcessRunningCrazyPidNoName)
{
  ASSERT_FALSE(qi::os::isProcessRunning(randomWrongPid()));
}

TEST(QiOs, isProcessRunningWrongName)
{
  const std::string processName = randomProcessName();
  ASSERT_FALSE(qi::os::isProcessRunning(1, processName))
      << "random process with name " << processName << " is said to be running";
}

TEST(QiOs, isProcessRunningRealProcess)
{
  const std::string executable("testlaunchloop");
  const std::string executablePath = qi::path::findBin(executable);
  const ScopedProcess p{executablePath};
  ASSERT_TRUE(qi::os::isProcessRunning(p.pid(), executable))
      << executablePath << " was not found running";
}

TEST(QiOs, isProcessRunningRealProcessNoName)
{
  const std::string executable("testlaunchloop");
  const std::string executablePath = qi::path::findBin(executable);
  const ScopedProcess p{executablePath};
  ASSERT_TRUE(qi::os::isProcessRunning(p.pid()));
}

TEST(QiOs, isProcessRunningRealProcessWithArgs)
{
  const std::string executable("testlaunchloop");
  const std::string executablePath = qi::path::findBin(executable);
  const std::vector<std::string> args { "nan", "mais", "allo", "quoi" };
  const ScopedProcess p{executablePath, args};
  ASSERT_TRUE(qi::os::isProcessRunning(p.pid(), executable));
}

TEST(QiOs, isProcessRunningRealProcessWithArgsUnicode)
{
  const std::string originalExecutable { "testlaunchloop" };
  const std::string originalExecutablePath = qi::path::findBin(originalExecutable);
  // we'll copy the originalExecutable to a unique file inside a unique direcory.
  // we re-use the unique directory name to build a unique file name.
  const qi::Path tmp = qi::Path(qi::os::mktmpdir());
  // japanese ideograms (specified by their unicode code point)
  // as an utf-8-encoded string (does not work on VS).
  //char utf8[] = u8"-\u30e6\u30cb\u30b3\u30fc\u30c9";
  // The same ideograms, specified by their utf-8 encoding
  char utf8[] = "-\xe3\x83\xa6\xe3\x83\x8b\xe3\x82\xb3\xe3\x83\xbc\xe3\x83\x89";
  const std::string executable = tmp.filename() + utf8;
  std::string executableWithExtension = executable;
#if BOOST_OS_WINDOWS && defined(NDEBUG)
    executableWithExtension += ".exe";
#elif BOOST_OS_WINDOWS && !defined(NDEBUG)
    executableWithExtension += "_d.exe";
#endif

  const qi::Path executablePathWithExtension =
          tmp / executableWithExtension;
  const qi::path::ScopedFile executableFile(executablePathWithExtension);
  boost::filesystem::copy(
        qi::Path(originalExecutablePath).bfsPath(),
        executablePathWithExtension.bfsPath());

  const std::vector<std::string> args { "nan", "mais", "allo", "quoi" };
  const ScopedProcess p{executablePathWithExtension.str(), args};
  ASSERT_TRUE(qi::os::isProcessRunning(p.pid(), executable));
}
// Tests for isProcessRunning end ============================================

int main(int argc, char* argv[])
{
  qi::Application app(argc, argv);
  binDir = qi::path::findBin("testlaunch");
  loopBinDir = qi::path::findBin("testlaunchloop");
  qi::log::addFilter("qi.os", qi::LogLevel_Debug);
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>Fix max PID value<commit_after>#include <random>
#include <gtest/gtest.h>
#include <boost/filesystem.hpp>
#include <boost/predef/os.h>
#include <qi/application.hpp>
#include <qi/log.hpp>
#include <qi/os.hpp>
#include <qi/path.hpp>

#include <errno.h>

#ifdef _WIN32
# include <windows.h>
# include <process.h>
# include <signal.h>
#else
# include <sys/wait.h>
#endif

/*
 * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */
// TODO2: Some tests to check the consume stack

static std::string binDir;
static std::string loopBinDir;

TEST(spawnvp, CmdWithNoArgs)
{
  char* args[] = {(char*)binDir.c_str(), NULL};

  int status = 0;

  int childPid = qi::os::spawnvp(args);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(42, status) << "status: " << status;
}

TEST(spawnvp, CmdWithArgs)
{
  char* args[] = {(char*)binDir.c_str(), (char*)"23", NULL};

  int status = 0;

  int childPid = qi::os::spawnvp(args);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(23, status) << "status: " << status;
}

TEST(spawnvp, CmdWithMultiArgs)
{
  char* args[] = {(char*)binDir.c_str(), (char*)"23", (char*)"-1", NULL};

  int status = 0;

  int childPid = qi::os::spawnvp(args);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(22, status) << "status: " << status;
}

TEST(spawnvp, InvalidBin)
{
  char* args[] = {(char*)"test42", NULL};

  int status = 0;

  int childPid = qi::os::spawnvp(args);
  EXPECT_EQ(-1, childPid);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(127, status) << "status: " << status;
}

TEST(spawnlp, CmdWithNoArgs)
{
  std::string bin = binDir.c_str();

  int status = 0;

  int childPid = qi::os::spawnlp(bin.c_str(), NULL);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(42, status) << "status: " << status;
}

TEST(spawnlp, CmdWithArgs)
{
  std::string bin = binDir.c_str();
  std::string arg1 = "23";
  int status = 0;

  int childPid = qi::os::spawnlp(bin.c_str(), arg1.c_str(), NULL);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(23, status) << "status: " << status;
}

TEST(spawnlp, CmdWithMultiArgs)
{
  std::string bin = binDir.c_str();
  std::string arg1 = "23";
  std::string arg2 = "-1";

  int status = 0;

  int childPid = qi::os::spawnlp(bin.c_str(), arg2.c_str(), arg1.c_str(), NULL);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(22, status) << "status: " << status;
}

TEST(spawnlp, Environment)
{
  // The check_env executable exits with rectode 1 if
  // the FOO environment var is not equal to BAR.
  std::string checkEnv = qi::path::findBin("check_env");
  int status = 0;
  qi::os::setenv("FOO", "BAR");
  int childPid = qi::os::spawnlp(checkEnv.c_str(), NULL);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, status) << "waitpid failed with retcode:   " << error;
  EXPECT_EQ(0, status) << "check_env failed with rectode: " << status;
}

TEST(spawnlp, InvalidBin)
{
  std::string bin = "test42";
  int status = 0;

  int childPid = qi::os::spawnlp(bin.c_str(), NULL);
  EXPECT_EQ(-1, childPid);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(127, status) << "status: " << status;
}

TEST(kill, Terminate)
{
  int status = 0;
  int alive = -1;
  int killed = -1;
  int dead = 0;

  int childPid = qi::os::spawnlp(loopBinDir.c_str(), NULL);
  ASSERT_NE(-1, childPid);

  if (childPid != -1)
  {
    qi::os::sleep(1);

    // is it alive?
    alive = qi::os::kill(childPid, 0);

    // let's kill it
    killed = qi::os::kill(childPid, SIGTERM);
    qi::os::waitpid(childPid, &status);

    // is it dead?
    dead = qi::os::kill(childPid, 0);
  }

  EXPECT_EQ(0, alive) << "alive: " << alive;
  EXPECT_EQ(0, killed) << "killed: " << killed;
  EXPECT_EQ(-1, dead) << "dead: " << dead;
}

#ifdef _MSC_VER
# define SIGKILL 9 // not defined on windows and ignored by kill
#endif

TEST(kill, Kill)
{
  int status = 0;
  int alive = -1;
  int killed = -1;
  int dead = 0;

  int childPid = qi::os::spawnlp(loopBinDir.c_str(), NULL);
  ASSERT_NE(-1, childPid);

  if (childPid != -1)
  {
    qi::os::sleep(1);

    // is it alive?
    alive = qi::os::kill(childPid, 0);

    // let's kill it
    killed = qi::os::kill(childPid, SIGKILL);
    qi::os::waitpid(childPid, &status);

    // is it dead?
    dead = qi::os::kill(childPid, 0);
  }

  EXPECT_EQ(0, alive) << "alive: " << alive;
  EXPECT_EQ(0, killed) << "killed: " << killed;
  EXPECT_EQ(-1, dead) << "dead: " << dead;
}

TEST(system, CmdWithNoArgs)
{
  std::string bin = binDir;

  int status = qi::os::system(bin.c_str());

  EXPECT_EQ(42, status) << "status: " << status;
}

TEST(system, CmdWithArgs)
{
  std::string bin = binDir + " 23";

  int status = qi::os::system(bin.c_str());

  EXPECT_EQ(23, status) << "status: " << status;
}

TEST(system, CmdWithMultiArgs)
{
  std::string bin = binDir + " 23 -1";

  int status = qi::os::system(bin.c_str());

  EXPECT_EQ(22, status) << "status: " << status;
}

TEST(system, InvalidBin)
{
  std::string bin = "test42";

  int status = qi::os::system(bin.c_str());

 #ifdef _WIN32
  EXPECT_EQ(1, status) << "status: " << status;
 #else
  EXPECT_EQ(127, status) << "status: " << status;
 #endif
}

//============================================================================
// Tests for checking isProcessRunning
//============================================================================
namespace
{
int randInt(int min, int max)
{
  static std::random_device rd;
  static std::mt19937 gen(rd());
  std::uniform_int_distribution<int> dis(min, max);
  return dis(gen);
}

char randomProcessChar()
{
  static const char* characters =
  "0123456789"
  "-_ "
  "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  "abcdefghijklmnopqrstuvwxyz";
  static int nofChars = strlen(characters) - 1;
  return characters[randInt(1, nofChars)];
}

std::string randomProcessName()
{
  std::string str;
  int length = 2 + rand() % 10;
  for(int i = 0; i < length; ++i)
  {
    str.push_back(randomProcessChar());
  }
  return str;
}

int randomWrongPid()
{
  return randInt(100000, std::numeric_limits<int>::max());
}

class ScopedProcess
{
public:
  ScopedProcess(
      const std::string& executable,
      const std::vector<std::string>& arguments = std::vector<std::string>())
    : _executable(executable)
  {
    char** cArgs = new char*[arguments.size()+2];
    cArgs[0] = (char*)_executable.c_str();
    for(size_t i = 0; i < arguments.size(); ++i)
      cArgs[i+1] = (char*)arguments[i].c_str();
    cArgs[arguments.size()+1] = NULL;
    _pid = qi::os::spawnvp(cArgs);
    if (_pid <= 0)
      throw std::runtime_error(
          std::string("Could not start: ") + _executable);
  }

  ~ScopedProcess()
  {
    qi::os::kill(_pid, SIGKILL);
    int status = 0;
    int ret = qi::os::waitpid(_pid, &status);
    std::cout << "Waiting for " << _executable << " has yielded the status "
                << status << " and returned " << ret << std::endl;
  }

  int pid() const
  {
    return _pid;
  }

private:
  std::string _executable;
  int _pid;
};

} // ends anonymous namespace

TEST(QiOs, isProcessRunningCrazyPid)
{
  ASSERT_FALSE(qi::os::isProcessRunning(randomWrongPid(), randomProcessName()));
}

TEST(QiOs, isProcessRunningCrazyPidNoName)
{
  ASSERT_FALSE(qi::os::isProcessRunning(randomWrongPid()));
}

TEST(QiOs, isProcessRunningWrongName)
{
  const std::string processName = randomProcessName();
  ASSERT_FALSE(qi::os::isProcessRunning(1, processName))
      << "random process with name " << processName << " is said to be running";
}

TEST(QiOs, isProcessRunningRealProcess)
{
  const std::string executable("testlaunchloop");
  const std::string executablePath = qi::path::findBin(executable);
  const ScopedProcess p{executablePath};
  ASSERT_TRUE(qi::os::isProcessRunning(p.pid(), executable))
      << executablePath << " was not found running";
}

TEST(QiOs, isProcessRunningRealProcessNoName)
{
  const std::string executable("testlaunchloop");
  const std::string executablePath = qi::path::findBin(executable);
  const ScopedProcess p{executablePath};
  ASSERT_TRUE(qi::os::isProcessRunning(p.pid()));
}

TEST(QiOs, isProcessRunningRealProcessWithArgs)
{
  const std::string executable("testlaunchloop");
  const std::string executablePath = qi::path::findBin(executable);
  const std::vector<std::string> args { "nan", "mais", "allo", "quoi" };
  const ScopedProcess p{executablePath, args};
  ASSERT_TRUE(qi::os::isProcessRunning(p.pid(), executable));
}

TEST(QiOs, isProcessRunningRealProcessWithArgsUnicode)
{
  const std::string originalExecutable { "testlaunchloop" };
  const std::string originalExecutablePath = qi::path::findBin(originalExecutable);
  // we'll copy the originalExecutable to a unique file inside a unique direcory.
  // we re-use the unique directory name to build a unique file name.
  const qi::Path tmp = qi::Path(qi::os::mktmpdir());
  // japanese ideograms (specified by their unicode code point)
  // as an utf-8-encoded string (does not work on VS).
  //char utf8[] = u8"-\u30e6\u30cb\u30b3\u30fc\u30c9";
  // The same ideograms, specified by their utf-8 encoding
  char utf8[] = "-\xe3\x83\xa6\xe3\x83\x8b\xe3\x82\xb3\xe3\x83\xbc\xe3\x83\x89";
  const std::string executable = tmp.filename() + utf8;
  std::string executableWithExtension = executable;
#if BOOST_OS_WINDOWS && defined(NDEBUG)
    executableWithExtension += ".exe";
#elif BOOST_OS_WINDOWS && !defined(NDEBUG)
    executableWithExtension += "_d.exe";
#endif

  const qi::Path executablePathWithExtension =
          tmp / executableWithExtension;
  const qi::path::ScopedFile executableFile(executablePathWithExtension);
  boost::filesystem::copy(
        qi::Path(originalExecutablePath).bfsPath(),
        executablePathWithExtension.bfsPath());

  const std::vector<std::string> args { "nan", "mais", "allo", "quoi" };
  const ScopedProcess p{executablePathWithExtension.str(), args};
  ASSERT_TRUE(qi::os::isProcessRunning(p.pid(), executable));
}
// Tests for isProcessRunning end ============================================

int main(int argc, char* argv[])
{
  qi::Application app(argc, argv);
  binDir = qi::path::findBin("testlaunch");
  loopBinDir = qi::path::findBin("testlaunchloop");
  qi::log::addFilter("qi.os", qi::LogLevel_Debug);
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#include "leanify.h"

#include <iostream>

#include "lib/miniz/miniz.h"
#include "lib/zopfli/zlib_container.h"

#include "formats/data_uri.h"
#include "formats/dwf.h"
#include "formats/format.h"
#include "formats/gft.h"
#include "formats/gz.h"
#include "formats/ico.h"
#include "formats/jpeg.h"
#include "formats/lua.h"
#include "formats/mime.h"
#include "formats/pe.h"
#include "formats/png.h"
#include "formats/swf.h"
#include "formats/tar.h"
#include "formats/rdb.h"
#include "formats/vcf.h"
#include "formats/xml.h"
#include "formats/zip.h"

using std::cerr;
using std::cout;
using std::endl;
using std::string;

Format *GetType(void *file_pointer, size_t file_size, const string& filename)
{
    if (depth > max_depth)
    {
        return new Format(file_pointer, file_size);
    }

    if (!filename.empty())
    {
        size_t dot = filename.find_last_of('.');
        if (dot != string::npos)
        {
            string ext = filename.substr(dot + 1);
            // toupper
            for (auto &c : ext)
                c &= ~0x20;

            if (ext == "HTML" ||
                ext == "HTM" ||
                ext == "JS" ||
                ext == "CSS")
            {
                if (is_verbose)
                {
                    cout << ext << " detected." << endl;
                }
                return new DataURI(file_pointer, file_size);
            }
            if (ext == "VCF")
            {
                if (is_verbose)
                {
                    cout << ext << " detected." << endl;
                }
                return new Vcf(file_pointer, file_size);
            }
            if (ext == "MHT" ||
                ext == "MHTML" ||
                ext == "MIM" ||
                ext == "MIME" ||
                ext == "EML" )
            {
                if (is_verbose)
                {
                    cout << ext << " detected." << endl;
                }
                return new Mime(file_pointer, file_size);
            }
        }

    }
    if (memcmp(file_pointer, Png::header_magic, sizeof(Png::header_magic)) == 0)
    {
        if (is_verbose)
        {
            cout << "PNG detected." << endl;
        }
        return new Png(file_pointer, file_size);
    }
    else if (memcmp(file_pointer, Jpeg::header_magic, sizeof(Jpeg::header_magic)) == 0)
    {
        if (is_verbose)
        {
            cout << "JPEG detected." << endl;
        }
        return new Jpeg(file_pointer, file_size);
    }
    else if (memcmp(file_pointer, Lua::header_magic, sizeof(Lua::header_magic)) == 0)
    {
        if (is_verbose)
        {
            cout << "Lua detected." << endl;
        }
        return new Lua(file_pointer, file_size);
    }
    else if (memcmp(file_pointer, Zip::header_magic, sizeof(Zip::header_magic)) == 0)
    {
        if (is_verbose)
        {
            cout << "ZIP detected." << endl;
        }
        return new Zip(file_pointer, file_size);
    }
    else if (memcmp(file_pointer, Pe::header_magic, sizeof(Pe::header_magic)) == 0)
    {
        if (is_verbose)
        {
            cout << "PE detected." << endl;
        }
        return new Pe(file_pointer, file_size);
    }
    else if (memcmp(file_pointer, Gz::header_magic, sizeof(Gz::header_magic)) == 0)
    {
        if (is_verbose)
        {
            cout << "GZ detected." << endl;
        }
        return new Gz(file_pointer, file_size);
    }
    else if (memcmp(file_pointer, Ico::header_magic, sizeof(Ico::header_magic)) == 0)
    {
        if (is_verbose)
        {
            cout << "ICO detected." << endl;
        }
        return new Ico(file_pointer, file_size);
    }
    else if (memcmp(file_pointer, Dwf::header_magic, sizeof(Dwf::header_magic)) == 0)
    {
        if (is_verbose)
        {
            cout << "DWF detected." << endl;
        }
        return new Dwf(file_pointer, file_size);
    }
    else if (memcmp(file_pointer, Gft::header_magic, sizeof(Gft::header_magic)) == 0)
    {
        if (is_verbose)
        {
            cout << "GFT detected." << endl;
        }
        return new Gft(file_pointer, file_size);
    }
    else if (memcmp(file_pointer, Rdb::header_magic, sizeof(Rdb::header_magic)) == 0)
    {
        if (is_verbose)
        {
            cout << "RDB detected." << endl;
        }
        return new Rdb(file_pointer, file_size);
    }
    else if (memcmp(file_pointer, Swf::header_magic, sizeof(Swf::header_magic)) == 0 ||
             memcmp(file_pointer, Swf::header_magic_deflate, sizeof(Swf::header_magic_deflate)) == 0 ||
             memcmp(file_pointer, Swf::header_magic_lzma, sizeof(Swf::header_magic_lzma)) == 0)
    {
        if (is_verbose)
        {
            cout << "SWF detected." << endl;
        }
        return new Swf(file_pointer, file_size);
    }
    else
    {
        // tar file does not have header magic
        // ustar is optional
        {
            Tar *t = new Tar(file_pointer, file_size);
            // checking first record checksum
            if (t->IsValid())
            {
                if (is_verbose)
                {
                    cout << "tar detected." << endl;
                }
                return t;
            }
            delete t;
        }

        // XML file does not have header magic
        // have to parse and see if there are any errors.
        {
            Xml *x = new Xml(file_pointer, file_size);
            if (x->IsValid())
            {
                if (is_verbose)
                {
                    cout << "XML detected." << endl;
                }
                return x;
            }
            delete x;
        }
    }

    if (is_verbose)
    {
        cout << "Format not supported!" << endl;
    }
    // for unsupported format, just memmove it.
    return new Format(file_pointer, file_size);
}

// Leanify the file
// and move the file ahead size_leanified bytes
// the new location of the file will be file_pointer - size_leanified
// it's designed this way to avoid extra memmove or memcpy
// return new size
size_t LeanifyFile(void *file_pointer, size_t file_size, size_t size_leanified /*= 0*/, const string& filename /*= ""*/)
{
    Format *f = GetType(file_pointer, file_size, filename);
    size_t r = f->Leanify(size_leanified);
    delete f;
    return r;
}

size_t ZlibRecompress(void *src, size_t src_len, size_t size_leanified /*= 0*/)
{
    if (!is_fast)
    {
        size_t s = 0;
        uint8_t *buffer = static_cast<uint8_t *>(tinfl_decompress_mem_to_heap(src, src_len, &s, TINFL_FLAG_PARSE_ZLIB_HEADER));
        if (!buffer)
        {
            cerr << "Decompress Zlib data failed." << endl;
        }
        else
        {
            ZopfliOptions zopfli_options;
            ZopfliInitOptions(&zopfli_options);
            zopfli_options.numiterations = iterations;

            size_t new_size = 0;
            uint8_t *out_buffer = nullptr;
            ZopfliZlibCompress(&zopfli_options, buffer, s, &out_buffer, &new_size);
            mz_free(buffer);
            if (new_size < src_len)
            {
                memcpy(static_cast<uint8_t *>(src) - size_leanified, out_buffer, new_size);
                free(out_buffer);
                return new_size;
            }
            free(out_buffer);
        }
    }

    memmove(static_cast<uint8_t *>(src) - size_leanified, src, src_len);
    return src_len;
}<commit_msg>VCF: improve detection<commit_after>#include "leanify.h"

#include <algorithm>
#include <iostream>

#include "lib/miniz/miniz.h"
#include "lib/zopfli/zlib_container.h"

#include "formats/data_uri.h"
#include "formats/dwf.h"
#include "formats/format.h"
#include "formats/gft.h"
#include "formats/gz.h"
#include "formats/ico.h"
#include "formats/jpeg.h"
#include "formats/lua.h"
#include "formats/mime.h"
#include "formats/pe.h"
#include "formats/png.h"
#include "formats/swf.h"
#include "formats/tar.h"
#include "formats/rdb.h"
#include "formats/vcf.h"
#include "formats/xml.h"
#include "formats/zip.h"

using std::cerr;
using std::cout;
using std::endl;
using std::string;

Format *GetType(void *file_pointer, size_t file_size, const string& filename)
{
    if (depth > max_depth)
    {
        return new Format(file_pointer, file_size);
    }

    if (!filename.empty())
    {
        size_t dot = filename.find_last_of('.');
        if (dot != string::npos)
        {
            string ext = filename.substr(dot + 1);
            // toupper
            for (auto &c : ext)
                c &= ~0x20;

            if (ext == "HTML" ||
                ext == "HTM" ||
                ext == "JS" ||
                ext == "CSS")
            {
                if (is_verbose)
                {
                    cout << ext << " detected." << endl;
                }
                return new DataURI(file_pointer, file_size);
            }
            if (ext == "VCF" ||
                ext == "VCARD")
            {
                if (is_verbose)
                {
                    cout << ext << " detected." << endl;
                }
                return new Vcf(file_pointer, file_size);
            }
            if (ext == "MHT" ||
                ext == "MHTML" ||
                ext == "MIM" ||
                ext == "MIME" ||
                ext == "EML" )
            {
                if (is_verbose)
                {
                    cout << ext << " detected." << endl;
                }
                return new Mime(file_pointer, file_size);
            }
        }

    }
    if (memcmp(file_pointer, Png::header_magic, sizeof(Png::header_magic)) == 0)
    {
        if (is_verbose)
        {
            cout << "PNG detected." << endl;
        }
        return new Png(file_pointer, file_size);
    }
    else if (memcmp(file_pointer, Jpeg::header_magic, sizeof(Jpeg::header_magic)) == 0)
    {
        if (is_verbose)
        {
            cout << "JPEG detected." << endl;
        }
        return new Jpeg(file_pointer, file_size);
    }
    else if (memcmp(file_pointer, Lua::header_magic, sizeof(Lua::header_magic)) == 0)
    {
        if (is_verbose)
        {
            cout << "Lua detected." << endl;
        }
        return new Lua(file_pointer, file_size);
    }
    else if (memcmp(file_pointer, Zip::header_magic, sizeof(Zip::header_magic)) == 0)
    {
        if (is_verbose)
        {
            cout << "ZIP detected." << endl;
        }
        return new Zip(file_pointer, file_size);
    }
    else if (memcmp(file_pointer, Pe::header_magic, sizeof(Pe::header_magic)) == 0)
    {
        if (is_verbose)
        {
            cout << "PE detected." << endl;
        }
        return new Pe(file_pointer, file_size);
    }
    else if (memcmp(file_pointer, Gz::header_magic, sizeof(Gz::header_magic)) == 0)
    {
        if (is_verbose)
        {
            cout << "GZ detected." << endl;
        }
        return new Gz(file_pointer, file_size);
    }
    else if (memcmp(file_pointer, Ico::header_magic, sizeof(Ico::header_magic)) == 0)
    {
        if (is_verbose)
        {
            cout << "ICO detected." << endl;
        }
        return new Ico(file_pointer, file_size);
    }
    else if (memcmp(file_pointer, Dwf::header_magic, sizeof(Dwf::header_magic)) == 0)
    {
        if (is_verbose)
        {
            cout << "DWF detected." << endl;
        }
        return new Dwf(file_pointer, file_size);
    }
    else if (memcmp(file_pointer, Gft::header_magic, sizeof(Gft::header_magic)) == 0)
    {
        if (is_verbose)
        {
            cout << "GFT detected." << endl;
        }
        return new Gft(file_pointer, file_size);
    }
    else if (memcmp(file_pointer, Rdb::header_magic, sizeof(Rdb::header_magic)) == 0)
    {
        if (is_verbose)
        {
            cout << "RDB detected." << endl;
        }
        return new Rdb(file_pointer, file_size);
    }
    else if (memcmp(file_pointer, Swf::header_magic, sizeof(Swf::header_magic)) == 0 ||
             memcmp(file_pointer, Swf::header_magic_deflate, sizeof(Swf::header_magic_deflate)) == 0 ||
             memcmp(file_pointer, Swf::header_magic_lzma, sizeof(Swf::header_magic_lzma)) == 0)
    {
        if (is_verbose)
        {
            cout << "SWF detected." << endl;
        }
        return new Swf(file_pointer, file_size);
    }
    else
    {
        // Search for vcard magic which might not be at the very beginning.
        const string vcard_magic = "BEGIN:VCARD";
        const char* fp = static_cast<char*>(file_pointer);
        const char* search_end = fp + std::min(static_cast<size_t>(1024), file_size);
        if (std::search(fp, search_end, vcard_magic.begin(), vcard_magic.end()) < search_end)
        {
            if (is_verbose)
            {
                cout << "VCF detected." << endl;
            }
            return new Vcf(file_pointer, file_size);
        }

        // tar file does not have header magic
        // ustar is optional
        {
            Tar *t = new Tar(file_pointer, file_size);
            // checking first record checksum
            if (t->IsValid())
            {
                if (is_verbose)
                {
                    cout << "tar detected." << endl;
                }
                return t;
            }
            delete t;
        }

        // XML file does not have header magic
        // have to parse and see if there are any errors.
        {
            Xml *x = new Xml(file_pointer, file_size);
            if (x->IsValid())
            {
                if (is_verbose)
                {
                    cout << "XML detected." << endl;
                }
                return x;
            }
            delete x;
        }
    }

    if (is_verbose)
    {
        cout << "Format not supported!" << endl;
    }
    // for unsupported format, just memmove it.
    return new Format(file_pointer, file_size);
}

// Leanify the file
// and move the file ahead size_leanified bytes
// the new location of the file will be file_pointer - size_leanified
// it's designed this way to avoid extra memmove or memcpy
// return new size
size_t LeanifyFile(void *file_pointer, size_t file_size, size_t size_leanified /*= 0*/, const string& filename /*= ""*/)
{
    Format *f = GetType(file_pointer, file_size, filename);
    size_t r = f->Leanify(size_leanified);
    delete f;
    return r;
}

size_t ZlibRecompress(void *src, size_t src_len, size_t size_leanified /*= 0*/)
{
    if (!is_fast)
    {
        size_t s = 0;
        uint8_t *buffer = static_cast<uint8_t *>(tinfl_decompress_mem_to_heap(src, src_len, &s, TINFL_FLAG_PARSE_ZLIB_HEADER));
        if (!buffer)
        {
            cerr << "Decompress Zlib data failed." << endl;
        }
        else
        {
            ZopfliOptions zopfli_options;
            ZopfliInitOptions(&zopfli_options);
            zopfli_options.numiterations = iterations;

            size_t new_size = 0;
            uint8_t *out_buffer = nullptr;
            ZopfliZlibCompress(&zopfli_options, buffer, s, &out_buffer, &new_size);
            mz_free(buffer);
            if (new_size < src_len)
            {
                memcpy(static_cast<uint8_t *>(src) - size_leanified, out_buffer, new_size);
                free(out_buffer);
                return new_size;
            }
            free(out_buffer);
        }
    }

    memmove(static_cast<uint8_t *>(src) - size_leanified, src, src_len);
    return src_len;
}<|endoftext|>


<commit_before><commit_msg>Revert: Remove redundant explicitly defined copy constructors<commit_after><|endoftext|>


<commit_before>#include <wiringPi.h>
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
using namespace boost::python;

#include "QTRSensors.h"

class WrapperFuncs{
public:
    static boost::shared_ptr<QTRSensorsRC> init(
	        list _pins, unsigned int timeout, unsigned char emitterPin){
        wiringPiSetup();
        unsigned char __pins[QTRSensorsRC::QTR_MAX_SENSORS];
        for(int i=0; i<len(_pins); i++)
            __pins[i]=extract<int>(_pins[i]);
        return boost::shared_ptr<QTRSensorsRC>(
            new QTRSensorsRC(__pins, (unsigned char)len(_pins), timeout, emitterPin)
        );
    }

    static unsigned int readLine(QTRSensorsRC &qtrrc, list sensorValues,
            unsigned char readMode=QTRSensorsRC::QTR_EMITTERS_ON, unsigned char white_line=0){
        unsigned int _sv[QTRSensorsRC::QTR_MAX_SENSORS];
        for(int i=0; i<len(sensorValues); i++)
            _sv[i]=extract<unsigned int>(sensorValues[i]);

        int result=qtrrc.readLine(_sv, readMode, white_line);

        for(int i=0; i<len(sensorValues); i++)
            sensorValues[i]=_sv[i];
        return result;
    }

    static void read(QTRSensorsRC &qtrrc, list sensorValues,
            unsigned char readMode=QTRSensorsRC::QTR_EMITTERS_ON){
        unsigned int _sv[QTRSensorsRC::QTR_MAX_SENSORS];
        for(int i=0; i<len(sensorValues); i++)
            _sv[i]=extract<unsigned int>(sensorValues[i]);

        qtrrc.read(_sv, readMode);

        for(int i=0; i<len(sensorValues); i++)
            sensorValues[i]=_sv[i];
    }

    static void readCalibrated(QTRSensorsRC &qtrrc, list sensorValues,
            unsigned char readMode=QTRSensorsRC::QTR_EMITTERS_ON){
        unsigned int _sv[QTRSensorsRC::QTR_MAX_SENSORS];
        for(int i=0; i<len(sensorValues); i++)
            _sv[i]=extract<unsigned int>(sensorValues[i]);

        qtrrc.readCalibrated(_sv, readMode);

        for(int i=0; i<len(sensorValues); i++)
            sensorValues[i]=_sv[i];
    }

    static list calibratedMinimumOn(QTRSensorsRC& qtrrc){
        list values;
        for(unsigned char i=0; i<qtrrc.numSensors(); i++)
            values.append(qtrrc.calibratedMinimumOn[i]);
        return values;
    }

    static list calibratedMaximumOn(QTRSensorsRC& qtrrc){
        list values;
        for(unsigned char i=0; i<qtrrc.numSensors(); i++)
            values.append(qtrrc.calibratedMaximumOn[i]);
        return values;
    }

    static list calibratedMinimumOff(QTRSensorsRC& qtrrc){
        list values;
        for(unsigned char i=0; i<qtrrc.numSensors(); i++)
            values.append(qtrrc.calibratedMinimumOff[i]);
        return values;
    }

    static list calibratedMaximumOff(QTRSensorsRC& qtrrc){
        list values;
        for(unsigned char i=0; i<qtrrc.numSensors(); i++)
            values.append(qtrrc.calibratedMaximumOff[i]);
        return values;
    }
};

BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(
    calibrate_overloads, QTRSensorsRC::calibrate, 0, 1
)

BOOST_PYTHON_FUNCTION_OVERLOADS(
    read_overloads, WrapperFuncs::read, 2, 3
)

BOOST_PYTHON_FUNCTION_OVERLOADS(
    readCalibrated_overloads, WrapperFuncs::readCalibrated, 2, 3
)

BOOST_PYTHON_FUNCTION_OVERLOADS(
    readLine_overloads, WrapperFuncs::readLine, 2, 4
)

const char* classDocStr=""
    "QTRSensors - Library for using Pololu QTR reflectance "
    "sensors and reflectance sensor arrays: QTR-1RC and "
    "QTR-8RC. Simply specify in the constructor which "
    "Raspberry Pi pins are connected to a QTR sensor, and the read() method "
    "will obtain reflectance measurements for those sensors.  Smaller sensor "
    "values correspond to higher reflectance (e.g. white) while larger "
    "sensor values correspond to lower reflectance (e.g. black or a void). "
    "* QTRSensorsRC should be used for QTR-1RC and QTR-8RC sensors.    "
;

BOOST_PYTHON_MODULE(QTRSensors){
    scope the_scope=class_<QTRSensorsRC, boost::shared_ptr<QTRSensorsRC> >
        ("QTRSensorsRC", classDocStr, no_init)
        .def("__init__", make_constructor(WrapperFuncs::init))

        // 'Normal' methods
        .def("calibrate", &QTRSensorsRC::calibrate, calibrate_overloads())
        .def("emittersOff", &QTRSensorsRC::emittersOff)
        .def("emittersOn", &QTRSensorsRC::emittersOn)
        .def("resetCalibration", &QTRSensorsRC::resetCalibration)

        // Wrapped methods
        .def("read", &WrapperFuncs::read, read_overloads())
        .def("readCalibrated", &WrapperFuncs::readCalibrated, readCalibrated_overloads())
        .def("readLine", &WrapperFuncs::readLine, readLine_overloads())

        // Getter Methods (wrap exposed array pointers)
        .def("calibratedMinimumOn", &WrapperFuncs::calibratedMinimumOn)
        .def("calibratedMaximumOn", &WrapperFuncs::calibratedMaximumOn)
        .def("calibratedMinimumOff", &WrapperFuncs::calibratedMinimumOff)
        .def("calibratedMaximumOff", &WrapperFuncs::calibratedMaximumOff)
    ;

    enum_<QTRSensorsRC::QTR>
        ("QTR")
        .value("QTR_EMITTERS_OFF", QTRSensorsRC::QTR_EMITTERS_OFF)
        .value("QTR_EMITTERS_ON", QTRSensorsRC::QTR_EMITTERS_ON)
        .value("QTR_EMITTERS_ON_AND_OFF", QTRSensorsRC::QTR_EMITTERS_ON_AND_OFF)
        .value("QTR_NO_EMITTER_PIN", QTRSensorsRC::QTR_NO_EMITTER_PIN)
        .value("QTR_MAX_SENSORS", QTRSensorsRC::QTR_MAX_SENSORS)
        .export_values()
    ;
}
<commit_msg>More docstrings<commit_after>#include <wiringPi.h>
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
using namespace boost::python;

#include "QTRSensors.h"

class WrapperFuncs{
public:
    static boost::shared_ptr<QTRSensorsRC> init(
	        list _pins, unsigned int timeout, unsigned char emitterPin){
        wiringPiSetup();
        unsigned char __pins[QTRSensorsRC::QTR_MAX_SENSORS];
        for(int i=0; i<len(_pins); i++)
            __pins[i]=extract<int>(_pins[i]);
        return boost::shared_ptr<QTRSensorsRC>(
            new QTRSensorsRC(__pins, (unsigned char)len(_pins), timeout, emitterPin)
        );
    }

    static unsigned int readLine(QTRSensorsRC &qtrrc, list sensorValues,
            unsigned char readMode=QTRSensorsRC::QTR_EMITTERS_ON, unsigned char white_line=0){
        unsigned int _sv[QTRSensorsRC::QTR_MAX_SENSORS];
        for(int i=0; i<len(sensorValues); i++)
            _sv[i]=extract<unsigned int>(sensorValues[i]);

        int result=qtrrc.readLine(_sv, readMode, white_line);

        for(int i=0; i<len(sensorValues); i++)
            sensorValues[i]=_sv[i];
        return result;
    }

    static void read(QTRSensorsRC &qtrrc, list sensorValues,
            unsigned char readMode=QTRSensorsRC::QTR_EMITTERS_ON){
        unsigned int _sv[QTRSensorsRC::QTR_MAX_SENSORS];
        for(int i=0; i<len(sensorValues); i++)
            _sv[i]=extract<unsigned int>(sensorValues[i]);

        qtrrc.read(_sv, readMode);

        for(int i=0; i<len(sensorValues); i++)
            sensorValues[i]=_sv[i];
    }

    static void readCalibrated(QTRSensorsRC &qtrrc, list sensorValues,
            unsigned char readMode=QTRSensorsRC::QTR_EMITTERS_ON){
        unsigned int _sv[QTRSensorsRC::QTR_MAX_SENSORS];
        for(int i=0; i<len(sensorValues); i++)
            _sv[i]=extract<unsigned int>(sensorValues[i]);

        qtrrc.readCalibrated(_sv, readMode);

        for(int i=0; i<len(sensorValues); i++)
            sensorValues[i]=_sv[i];
    }

    static list calibratedMinimumOn(QTRSensorsRC& qtrrc){
        list values;
        for(unsigned char i=0; i<qtrrc.numSensors(); i++)
            values.append(qtrrc.calibratedMinimumOn[i]);
        return values;
    }

    static list calibratedMaximumOn(QTRSensorsRC& qtrrc){
        list values;
        for(unsigned char i=0; i<qtrrc.numSensors(); i++)
            values.append(qtrrc.calibratedMaximumOn[i]);
        return values;
    }

    static list calibratedMinimumOff(QTRSensorsRC& qtrrc){
        list values;
        for(unsigned char i=0; i<qtrrc.numSensors(); i++)
            values.append(qtrrc.calibratedMinimumOff[i]);
        return values;
    }

    static list calibratedMaximumOff(QTRSensorsRC& qtrrc){
        list values;
        for(unsigned char i=0; i<qtrrc.numSensors(); i++)
            values.append(qtrrc.calibratedMaximumOff[i]);
        return values;
    }
};

BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(
    calibrate_overloads, QTRSensorsRC::calibrate, 0, 1
)

BOOST_PYTHON_FUNCTION_OVERLOADS(
    read_overloads, WrapperFuncs::read, 2, 3
)

BOOST_PYTHON_FUNCTION_OVERLOADS(
    readCalibrated_overloads, WrapperFuncs::readCalibrated, 2, 3
)

BOOST_PYTHON_FUNCTION_OVERLOADS(
    readLine_overloads, WrapperFuncs::readLine, 2, 4
)

const char* classDocStr=""
    "QTRSensors - Library for using Pololu QTR reflectance\n"
    "sensors and reflectance sensor arrays: QTR-1RC and\n"
    "QTR-8RC. Simply specify in the constructor which\n"
    "Raspberry Pi pins are connected to a QTR sensor, and the read() method\n"
    "will obtain reflectance measurements for those sensors.  Smaller sensor\n"
    "values correspond to higher reflectance (e.g. white) while larger\n"
    "sensor values correspond to lower reflectance (e.g. black or a void).\n\n"
    "* QTRSensorsRC should be used for QTR-1RC and QTR-8RC sensors.\n"
;

const char * initDocStr=""
    "The list 'pins' contains the Raspberry Pi pin number for each sensor.\n"
    "This library uses the pin number convention defined by WiringPi which \n"
    "can be found at http://wiringpi.com/pins/.\n\n"

    "'timeout' specifies the length of time in microseconds beyond\n"
    "which you consider the sensor reading completely black.  That is to say,\n"
    "if the pulse length for a pin exceeds 'timeout', pulse timing will stop\n"
    "and the reading for that pin will be considered full black.\n"
    "It is recommended that you set timeout to be between 1000 and\n"
    "3000 us, depending on things like the height of your sensors and\n"
    "ambient lighting.  Using timeout allows you to shorten the\n"
    "duration of a sensor-reading cycle while still maintaining\n"
    "useful analog measurements of reflectance.\n\n"

    "'emitterPin' is the Raspberry Pi pin that controls the IR LEDs on the 8RC\n"
    "modules.  If you are using a 1RC (i.e. if there is no emitter pin),\n"
    "or if you just want the emitters on all the time and don't want to\n"
    "use an I/O pin to control it, use a value of 255 (QTR_NO_EMITTER_PIN).\n"
;

BOOST_PYTHON_MODULE(QTRSensors){
    scope the_scope=class_<QTRSensorsRC, boost::shared_ptr<QTRSensorsRC> >
        ("QTRSensorsRC", classDocStr, no_init)
        .def("__init__", make_constructor(WrapperFuncs::init), initDocStr)

        // 'Normal' methods
        .def("calibrate", &QTRSensorsRC::calibrate, calibrate_overloads())
        .def("emittersOff", &QTRSensorsRC::emittersOff)
        .def("emittersOn", &QTRSensorsRC::emittersOn)
        .def("resetCalibration", &QTRSensorsRC::resetCalibration)

        // Wrapped methods
        .def("read", &WrapperFuncs::read, read_overloads())
        .def("readCalibrated", &WrapperFuncs::readCalibrated, readCalibrated_overloads())
        .def("readLine", &WrapperFuncs::readLine, readLine_overloads())

        // Getter Methods (wrap exposed array pointers)
        .def("calibratedMinimumOn", &WrapperFuncs::calibratedMinimumOn)
        .def("calibratedMaximumOn", &WrapperFuncs::calibratedMaximumOn)
        .def("calibratedMinimumOff", &WrapperFuncs::calibratedMinimumOff)
        .def("calibratedMaximumOff", &WrapperFuncs::calibratedMaximumOff)
    ;

    enum_<QTRSensorsRC::QTR>
        ("QTR")
        .value("QTR_EMITTERS_OFF", QTRSensorsRC::QTR_EMITTERS_OFF)
        .value("QTR_EMITTERS_ON", QTRSensorsRC::QTR_EMITTERS_ON)
        .value("QTR_EMITTERS_ON_AND_OFF", QTRSensorsRC::QTR_EMITTERS_ON_AND_OFF)
        .value("QTR_NO_EMITTER_PIN", QTRSensorsRC::QTR_NO_EMITTER_PIN)
        .value("QTR_MAX_SENSORS", QTRSensorsRC::QTR_MAX_SENSORS)
        .export_values()
    ;
}
<|endoftext|>


<commit_before>#include "Matrix4x4.h"

#include <memory>
#include <assert.h>

using namespace s1;

const Matrix4x4 Matrix4x4::Identity = Matrix4x4(
	1.0, 0.0, 0.0, 0.0,
	0.0, 1.0, 0.0, 0.0,
	0.0, 0.0, 1.0, 0.0,
	0.0, 0.0, 0.0, 1.0);

Matrix4x4::Matrix4x4()
{
	this->_copyFrom(Identity);
}

Matrix4x4::Matrix4x4(const Matrix4x4& m)
{
	this->_copyFrom(m);
}

Matrix4x4::~Matrix4x4()
{

}

Matrix4x4::Matrix4x4(
	double r1c1, double r1c2, double r1c3, double r1c4,
	double r2c1, double r2c2, double r2c3, double r2c4,
	double r3c1, double r3c2, double r3c3, double r3c4,
	double r4c1, double r4c2, double r4c3, double r4c4)
{
	_value[0][0] = r1c1; _value[0][1] = r1c2; _value[0][2] = r1c3; _value[0][3] = r1c4;
	_value[1][0] = r2c1; _value[1][1] = r2c2; _value[1][2] = r2c3; _value[1][3] = r2c4;
	_value[2][0] = r3c1; _value[2][1] = r3c2; _value[2][2] = r3c3; _value[2][3] = r3c4;
	_value[3][0] = r4c1; _value[3][1] = r4c2; _value[3][2] = r4c3; _value[3][3] = r4c4;
}

Matrix4x4 Matrix4x4::operator=(const Matrix4x4& rhs)
{
	this->_copyFrom(rhs);
	return *this;
}

void Matrix4x4::copyToColumnMajor(float matrix[16])
{
	int i = 0;
	for (int col = 0; col < 4; col++)
	{
		for (int row = 0; row < 4; row++)
		{
			matrix[i++] = static_cast<float>(this->_value[row][col]);
		}
	}
}

Matrix4x4 Matrix4x4::orthogonal(double xmin, double xmax, double ymin, double ymax, double zmin, double zmax)
{
	assert(xmin < xmax && ymin < ymax && zmin < zmax);

	return Matrix4x4(
		2.0 / (xmax - xmin), 0.0, 0.0, -(xmax + xmin) / (xmax - xmin),
		0.0, 2.0 / (ymax - ymin), 0.0, -(ymax + ymin) / (ymax - ymin),
		0.0, 0.0, -2.0 / (zmax - zmin), (zmax + zmin) / (zmax - zmin),
		0.0, 0.0, 0.0, 1.0);
}

Matrix4x4 Matrix4x4::perspective(double xmin, double xmax, double ymin, double ymax, double zmin, double zmax, double zpp)
{
	assert(xmin < xmax && ymin < ymax && zmin < zmax && zmax < 0 && zpp < 0);

	return Matrix4x4(
		-2.0*zpp/(xmax-xmin), 0.0,                 (xmax+xmin)/(xmax-xmin),  0.0,
		0.0,                 -2.0*zpp/(ymax-ymin), (ymax+ymin)/(ymax-ymin),  0.0,
		0.0,                 0.0,                 -(zmax+zmin)/(zmax-zmin), 2.0*zmin*zmax/(zmax-zmin),
		0.0,                 0.0,                 -1.0,                     0.0);
}

Matrix4x4 Matrix4x4::lookAt(AffinePoint& eye, AffinePoint& center, AffineVector& up)
{
	s1::AffineVector u, v, w;
	w = eye - center;
	w.normalize();
	u = w.cross(up);
	u.normalize();
	v = u.cross(w);
	double tx = u.dot(eye);
	double ty = v.dot(eye);
	double tz = w.dot(eye);
	return Matrix4x4(
		 u[0],  u[1],  u[2], -tx,
		 v[0],  v[1],  v[2], -ty,
		-w[0], -w[1], -w[2], -tz,
   		  0.0,   0.0,   0.0, 1.0);
}

void Matrix4x4::_copyFrom(const Matrix4x4& m)
{
	memcpy((void*)_value, (void*)m._value, 16 * sizeof(double));
}<commit_msg>Fix to inverted perspective divide.<commit_after>#include "Matrix4x4.h"

#include <memory>
#include <assert.h>

using namespace s1;

const Matrix4x4 Matrix4x4::Identity = Matrix4x4(
	1.0, 0.0, 0.0, 0.0,
	0.0, 1.0, 0.0, 0.0,
	0.0, 0.0, 1.0, 0.0,
	0.0, 0.0, 0.0, 1.0);

Matrix4x4::Matrix4x4()
{
	this->_copyFrom(Identity);
}

Matrix4x4::Matrix4x4(const Matrix4x4& m)
{
	this->_copyFrom(m);
}

Matrix4x4::~Matrix4x4()
{

}

Matrix4x4::Matrix4x4(
	double r1c1, double r1c2, double r1c3, double r1c4,
	double r2c1, double r2c2, double r2c3, double r2c4,
	double r3c1, double r3c2, double r3c3, double r3c4,
	double r4c1, double r4c2, double r4c3, double r4c4)
{
	_value[0][0] = r1c1; _value[0][1] = r1c2; _value[0][2] = r1c3; _value[0][3] = r1c4;
	_value[1][0] = r2c1; _value[1][1] = r2c2; _value[1][2] = r2c3; _value[1][3] = r2c4;
	_value[2][0] = r3c1; _value[2][1] = r3c2; _value[2][2] = r3c3; _value[2][3] = r3c4;
	_value[3][0] = r4c1; _value[3][1] = r4c2; _value[3][2] = r4c3; _value[3][3] = r4c4;
}

Matrix4x4 Matrix4x4::operator=(const Matrix4x4& rhs)
{
	this->_copyFrom(rhs);
	return *this;
}

void Matrix4x4::copyToColumnMajor(float matrix[16])
{
	int i = 0;
	for (int col = 0; col < 4; col++)
	{
		for (int row = 0; row < 4; row++)
		{
			matrix[i++] = static_cast<float>(this->_value[row][col]);
		}
	}
}

Matrix4x4 Matrix4x4::orthogonal(double xmin, double xmax, double ymin, double ymax, double zmin, double zmax)
{
	assert(xmin < xmax && ymin < ymax && zmin < zmax);

	return Matrix4x4(
		2.0 / (xmax - xmin), 0.0, 0.0, -(xmax + xmin) / (xmax - xmin),
		0.0, 2.0 / (ymax - ymin), 0.0, -(ymax + ymin) / (ymax - ymin),
		0.0, 0.0, -2.0 / (zmax - zmin), (zmax + zmin) / (zmax - zmin),
		0.0, 0.0, 0.0, 1.0);
}

Matrix4x4 Matrix4x4::perspective(double xmin, double xmax, double ymin, double ymax, double zmin, double zmax, double zpp)
{
	assert(xmin < xmax && ymin < ymax && zmin < zmax && zmax < 0 && zpp < 0);

	return Matrix4x4(
		-2.0*zpp/(xmax-xmin), 0.0,                 (xmax+xmin)/(xmax-xmin),  0.0,
		0.0,                 -2.0*zpp/(ymax-ymin), (ymax+ymin)/(ymax-ymin),  0.0,
		0.0,                  0.0,                 (zmax+zmin)/(zmax-zmin), -2.0*zmin*zmax/(zmax-zmin),
		0.0,                  0.0,                 -1.0,                     0.0);
}

Matrix4x4 Matrix4x4::lookAt(AffinePoint& eye, AffinePoint& center, AffineVector& up)
{
	s1::AffineVector u, v, w;
	w = center - eye;
	w.normalize();
	u = w.cross(up);
	u.normalize();
	v = u.cross(w);
	double tx = u.dot(eye);
	double ty = v.dot(eye);
	double tz = w.dot(eye);
	return Matrix4x4(
		 u[0],  u[1],  u[2], tx,
		 v[0],  v[1],  v[2], ty,
		-w[0], -w[1], -w[2], tz,
   		  0.0,   0.0,   0.0, 1.0);
}

void Matrix4x4::_copyFrom(const Matrix4x4& m)
{
	memcpy((void*)_value, (void*)m._value, 16 * sizeof(double));
}<|endoftext|>