<commit_before>#include "yaml-cpp/value.h"
#include <map>

int main()
{
	YAML::Value value(YAML::ValueType::Sequence);
	for(int i=0;i<5;i++)
		value.append(i);

	for(YAML::const_iterator it=value.begin();it!=value.end();++it) {
		std::cout << it->as<int>() << "\n";
	}

	return 0;
}
<commit_msg>Map iterator works\!<commit_after>#include "yaml-cpp/value.h"
#include <map>

int main()
{
	YAML::Value value;
	value["seq"] = YAML::Value(YAML::ValueType::Sequence);
	for(int i=0;i<5;i++)
		value["seq"].append(i);
	value["map"]["one"] = "I";
	value["map"]["two"] = "II";
	value["map"]["three"] = "III";
	value["map"]["four"] = "IV";

	for(YAML::const_iterator it=value["seq"].begin();it!=value["seq"].end();++it) {
		std::cout << it->as<int>() << "\n";
	}

	for(YAML::const_iterator it=value["map"].begin();it!=value["map"].end();++it) {
		std::cout << it->first.as<std::string>() << " -> " << it->second.as<std::string>() << "\n";
	}

	return 0;
}
<|endoftext|>


<commit_before>#include "parser.h"

int priority[128];
bool rightassoc[128];

const std::vector<std::pair<token_type, std::string> > splitExpression(const std::string &expr)
{
    priority[int('+')] = 0;
    priority[int('-')] = 0;
    priority[int('*')] = 1;
    priority[int('/')] = 1;
    priority[int('%')] = 1;
    priority[int('^')] = 2;
    priority[int('_')] = 3;
    priority[int('=')] = -1;
    rightassoc[int('^')] = true;
    rightassoc[int('_')] = true;
    std::string func, num, poly;
    std::vector<std::pair<token_type, std::string> > ans;
    token_type last = TOKEN_LEFTPAR;
    for(char i : expr + ' ')
    {
        if('A' <= i && i <= 'Z')
        {
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
            if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR)
                ans.push_back({TOKEN_OP, "*"});
            ans.push_back({TOKEN_MATRIX, std::string() + i});
            last = TOKEN_MATRIX;
        }
        else if(i == '+' || i == '*' || i == '^' || i == '(' || i == ')' || i == '=' || i == '/' || i == '%')
        {
            if(i == '/' && poly.size())
            {
                poly.push_back('/');
                continue;
            }
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
            if(i == '(')
            {
                if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR)
                    ans.push_back({TOKEN_OP, "*"});
                ans.push_back({TOKEN_LEFTPAR, ""});
            }
            else if(i == ')')
                ans.push_back({TOKEN_RIGHTPAR, ""});
            else
                ans.push_back({TOKEN_OP, std::string() + i});
            last = ans.back().first;
        }
        else if(i == '-')
        {
            if(poly.size())
            {
                poly.push_back('-');
                continue;
            }
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
            if(last == TOKEN_LEFTPAR || last == TOKEN_OP || last == TOKEN_COMMA)
            {
                ans.push_back({TOKEN_OP, "_"});  // unary
            }
            else
            {
                ans.push_back({TOKEN_OP, "-"});
            }
            last = TOKEN_OP;
        }
        else if(('0' <= i && i <= '9') || i == '.')
        {
            if(poly.size())
            {
                poly.push_back(i);
                continue;
            }
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            func = "";
            num.push_back(i);
            last = TOKEN_NUMBER;
        }
        else if('a' <= i && i <= 'z')
        {
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = "";
            func.push_back(i);
            last = TOKEN_FUNC;
        }
        else if(i == ',')
        {
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
            ans.push_back({TOKEN_COMMA, ""});
            last = TOKEN_COMMA;
        }
        else if(i == '$')
        {
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
            ans.push_back({TOKEN_DOLLAR, ""});
            last = TOKEN_DOLLAR;
        }
        else if(i == '"' || i == '\'')
        {
            if(poly.size())
            {
                if(poly[0] != i)
                {
                    ans.clear();
                    return ans;
                }
                ans.push_back({TOKEN_POLY, poly.substr(1)});
                poly = "";
                last = TOKEN_POLY;
            }
            else
            {
                poly = i;
                num = func = "";
            }
        }
        else
        {
            if(i == ' ' && poly.size())
            {
                poly.push_back(i);
                continue;
            }
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
        }
    }
    return ans;
}
<commit_msg>Число * функция<commit_after>#include "parser.h"

int priority[128];
bool rightassoc[128];

const std::vector<std::pair<token_type, std::string> > splitExpression(const std::string &expr)
{
    priority[int('+')] = 0;
    priority[int('-')] = 0;
    priority[int('*')] = 1;
    priority[int('/')] = 1;
    priority[int('%')] = 1;
    priority[int('^')] = 2;
    priority[int('_')] = 3;
    priority[int('=')] = -1;
    rightassoc[int('^')] = true;
    rightassoc[int('_')] = true;
    std::string func, num, poly;
    std::vector<std::pair<token_type, std::string> > ans;
    token_type last = TOKEN_LEFTPAR;
    for(char i : expr + ' ')
    {
        if('A' <= i && i <= 'Z')
        {
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
            if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR)
                ans.push_back({TOKEN_OP, "*"});
            ans.push_back({TOKEN_MATRIX, std::string() + i});
            last = TOKEN_MATRIX;
        }
        else if(i == '+' || i == '*' || i == '^' || i == '(' || i == ')' || i == '=' || i == '/' || i == '%')
        {
            if(i == '/' && poly.size())
            {
                poly.push_back('/');
                continue;
            }
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
            if(i == '(')
            {
                if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR)
                    ans.push_back({TOKEN_OP, "*"});
                ans.push_back({TOKEN_LEFTPAR, ""});
            }
            else if(i == ')')
                ans.push_back({TOKEN_RIGHTPAR, ""});
            else
                ans.push_back({TOKEN_OP, std::string() + i});
            last = ans.back().first;
        }
        else if(i == '-')
        {
            if(poly.size())
            {
                poly.push_back('-');
                continue;
            }
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
            if(last == TOKEN_LEFTPAR || last == TOKEN_OP || last == TOKEN_COMMA)
            {
                ans.push_back({TOKEN_OP, "_"});  // unary
            }
            else
            {
                ans.push_back({TOKEN_OP, "-"});
            }
            last = TOKEN_OP;
        }
        else if(('0' <= i && i <= '9') || i == '.')
        {
            if(poly.size())
            {
                poly.push_back(i);
                continue;
            }
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            func = "";
            num.push_back(i);
            last = TOKEN_NUMBER;
        }
        else if('a' <= i && i <= 'z')
        {
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = "";
            if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR)
                ans.push_back({TOKEN_OP, "*"});
            func.push_back(i);
            last = TOKEN_FUNC;
        }
        else if(i == ',')
        {
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
            ans.push_back({TOKEN_COMMA, ""});
            last = TOKEN_COMMA;
        }
        else if(i == '$')
        {
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
            ans.push_back({TOKEN_DOLLAR, ""});
            last = TOKEN_DOLLAR;
        }
        else if(i == '"' || i == '\'')
        {
            if(poly.size())
            {
                if(poly[0] != i)
                {
                    ans.clear();
                    return ans;
                }
                ans.push_back({TOKEN_POLY, poly.substr(1)});
                poly = "";
                last = TOKEN_POLY;
            }
            else
            {
                poly = i;
                num = func = "";
            }
        }
        else
        {
            if(i == ' ' && poly.size())
            {
                poly.push_back(i);
                continue;
            }
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
        }
    }
    return ans;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2020 Arduino SA
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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.
 */

/** @file
 *  Provides wiced fs porting to generic mbed APIs
 */

#include <stddef.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "sockets.h"
#include "resources.h"
#include "wiced_filesystem.h"
#include "wiced_bd.h"
#include "QSPIFBlockDevice.h"
#include "MBRBlockDevice.h"
#include "FATFileSystem.h"

#define WIFI_DEFAULT_FIRMWARE_PATH "/wlan/4343WA1.BIN"
#define WIFI_DEFAULT_MOUNT_NAME "wlan"
#define WIFI_DEFAULT_PARTITION 1
#define WIFI_DEFAULT_FS 0

QSPIFBlockDevice *qspi_bd = NULL;
MBRBlockDevice   *mbr_bd = NULL;
FATFileSystem    *wifi_fs = NULL;

MBED_WEAK void wiced_filesystem_mount_error(void)
{
    WPRINT_WHD_ERROR(("Failed to mount the filesystem containing the WiFi firmware.\n\r"));
    whd_print_logbuffer();
    while (1) {}
}

MBED_WEAK void wiced_filesystem_firmware_error(void)
{
    WPRINT_WHD_ERROR(("Please run the \"PortentaWiFiFirmwareUpdater\" sketch once to install the WiFi firmware.\n\r"));
    whd_print_logbuffer();
    while (1) {}
}

MBED_WEAK wiced_result_t whd_firmware_check_hook(const char *mounted_name, int mount_err)
{
    DIR *dir;
    struct dirent *ent;
    std::string dir_name(mounted_name);
    if (mount_err) {
        wiced_filesystem_mount_error();
    } else {
        if ((dir = opendir(mounted_name)) != NULL) {
            // print all the files and directories within directory
            while ((ent = readdir(dir)) != NULL) {
                std::string fullname =  "/" + dir_name + "/" + std::string(ent->d_name);
                if (fullname == WIFI_DEFAULT_FIRMWARE_PATH) {
                    closedir(dir);
                    return WICED_SUCCESS;
                }
            }
            closedir(dir);
        }
        wiced_filesystem_firmware_error();
    }
    return WICED_ERROR;
}

static wiced_result_t whd_default_firmware_restore(void)
{
#if MBED_CONF_APP_WIFI_FIRMWARE_RESTORE
    size_t ret;
    FILE *fp;

    //This should only happen the firs time or if the partition table has been overwritten i.e QSPI tests
    WPRINT_WHD_DEBUG(("MBRBlockDevice init failed, repatitioning\n\r"));
    if (mbr_bd->partition(qspi_bd, 1, 0x0B, 0, 1024 * 1024) != BD_ERROR_OK) {
        return WICED_ERROR;
    }
    WPRINT_WHD_DEBUG(("MBRBockDevice repatitioning OK, reinit\n\r"));

    if (mbr_bd->init() != BD_ERROR_OK) {
        return WICED_ERROR;
    }
    WPRINT_WHD_DEBUG(("MBRBockDevice init OK\n\r"));

    wifi_fs = new FATFileSystem(WIFI_DEFAULT_MOUNT_NAME);

    if (wifi_fs->reformat(mbr_bd) != 0) {
        return WICED_ERROR;
    }
    WPRINT_WHD_DEBUG(("FATFileSystem reformat and mount OK\n\r"));

    fp = fopen(WIFI_DEFAULT_FIRMWARE_PATH, "wb");
    if (fp == NULL) {
        return WICED_ERROR;
    }
    ret = fwrite(wifi_firmware_image_data, wifi_firmware_image.size, 1, fp);
    if (ret != wifi_firmware_image.size) {
        return WICED_ERROR;
    }
    fclose(fp);

    if (mbr_bd->sync() != 0) {
        return WICED_ERROR;
    }
    WPRINT_WHD_DEBUG(("Sync BlockDevice OK\n\r"));

    if (wifi_fs->unmount() != 0) {
        return WICED_ERROR;
    }
    WPRINT_WHD_DEBUG(("Unmount FS\n\r"));
    wifi_fs = NULL;
#endif

    return WICED_SUCCESS;
}

wiced_result_t wiced_filesystem_init(void)
{
    if (mbr_bd == NULL && wifi_fs == NULL) {
        WPRINT_WHD_DEBUG(("Initialize FileSystem with Mbed default settings\n\r"));
        qspi_bd = new QSPIFBlockDevice(PD_11, PD_12, PF_7, PD_13,  PF_10, PG_6, QSPIF_POLARITY_MODE_1, 40000000);

        if (qspi_bd->init() == BD_ERROR_OK) {
            mbr_bd = new MBRBlockDevice(qspi_bd, WIFI_DEFAULT_PARTITION);
            if (mbr_bd->init() == BD_ERROR_OK) {
                return WICED_SUCCESS;
            } else {
                return whd_default_firmware_restore();
            }
        }
        return WICED_ERROR;
    } else {
        WPRINT_WHD_DEBUG(("FileSystem initialized with user settings\n\r"));
        return WICED_SUCCESS;
    }
}

wiced_result_t wiced_filesystem_mount(BlockDevice *device, wiced_filesystem_handle_type_t fs_type, wiced_filesystem_t *fs_handle_out, const char *mounted_name)
{
    wifi_fs = new FATFileSystem(mounted_name);

    int err = wifi_fs->mount(device);
    whd_firmware_check_hook(mounted_name, err);
    if (!err) {
        //fs_handle_out = wifi_fs
        return WICED_SUCCESS;
    }
    return WICED_ERROR;
}

wiced_result_t wiced_filesystem_file_open(wiced_filesystem_t *fs_handle, wiced_file_t *file_handle_out, const char *filename, wiced_filesystem_open_mode_t mode)
{
    /* This is called by mbed test system */
    //if (mbr_bd == NULL && wifi_fs == NULL) {
    //    wiced_filesystem_init();
    //}
    //This can be called from user sketch to provide custom block device and mount point before WiFi.beginAP or WiFi.begin
    if (wifi_fs == NULL) {
        wiced_filesystem_mount(mbr_bd, WIFI_DEFAULT_FS, fs_handle, WIFI_DEFAULT_MOUNT_NAME);
    }

    if (wifi_fs == NULL) {
        return WICED_ERROR;
    }

    *file_handle_out = open(filename, mode);
    if (*file_handle_out == -1) {
        return WICED_ERROR;
    }
    return WICED_SUCCESS;
}

wiced_result_t wiced_filesystem_file_seek(wiced_file_t *file_handle, int64_t offset, wiced_filesystem_seek_type_t whence)
{
    if (*file_handle == -1) {
        return WICED_ERROR;
    }
    lseek(*file_handle, offset, whence);
    return WICED_SUCCESS;
}

wiced_result_t wiced_filesystem_file_read(wiced_file_t *file_handle, void *data, uint64_t bytes_to_read, uint64_t *returned_bytes_count)
{
    if (*file_handle == -1) {
        return WICED_ERROR;
    }
    *returned_bytes_count = read(*file_handle, data, bytes_to_read);
    return WICED_SUCCESS;
}

wiced_result_t wiced_filesystem_file_close(wiced_file_t *file_handle)
{
    if (*file_handle == -1) {
        return WICED_ERROR;
    }
    close(*file_handle);
    return WICED_SUCCESS;
}
<commit_msg>Portenta add resource_fs_handle declaration<commit_after>/*
 * Copyright 2020 Arduino SA
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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.
 */

/** @file
 *  Provides wiced fs porting to generic mbed APIs
 */

#include <stddef.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "sockets.h"
#include "resources.h"
#include "wiced_filesystem.h"
#include "wiced_bd.h"
#include "QSPIFBlockDevice.h"
#include "MBRBlockDevice.h"
#include "FATFileSystem.h"

#define WIFI_DEFAULT_FIRMWARE_PATH "/wlan/4343WA1.BIN"
#define WIFI_DEFAULT_MOUNT_NAME "wlan"
#define WIFI_DEFAULT_PARTITION 1
#define WIFI_DEFAULT_FS 0

QSPIFBlockDevice *qspi_bd = NULL;
MBRBlockDevice   *mbr_bd = NULL;
FATFileSystem    *wifi_fs = NULL;

wiced_filesystem_t resource_fs_handle;

MBED_WEAK void wiced_filesystem_mount_error(void)
{
    WPRINT_WHD_ERROR(("Failed to mount the filesystem containing the WiFi firmware.\n\r"));
    whd_print_logbuffer();
    while (1) {}
}

MBED_WEAK void wiced_filesystem_firmware_error(void)
{
    WPRINT_WHD_ERROR(("Please run the \"PortentaWiFiFirmwareUpdater\" sketch once to install the WiFi firmware.\n\r"));
    whd_print_logbuffer();
    while (1) {}
}

MBED_WEAK wiced_result_t whd_firmware_check_hook(const char *mounted_name, int mount_err)
{
    DIR *dir;
    struct dirent *ent;
    std::string dir_name(mounted_name);
    if (mount_err) {
        wiced_filesystem_mount_error();
    } else {
        if ((dir = opendir(mounted_name)) != NULL) {
            // print all the files and directories within directory
            while ((ent = readdir(dir)) != NULL) {
                std::string fullname =  "/" + dir_name + "/" + std::string(ent->d_name);
                if (fullname == WIFI_DEFAULT_FIRMWARE_PATH) {
                    closedir(dir);
                    return WICED_SUCCESS;
                }
            }
            closedir(dir);
        }
        wiced_filesystem_firmware_error();
    }
    return WICED_ERROR;
}

static wiced_result_t whd_default_firmware_restore(void)
{
#if MBED_CONF_APP_WIFI_FIRMWARE_RESTORE
    size_t ret;
    FILE *fp;

    //This should only happen the firs time or if the partition table has been overwritten i.e QSPI tests
    WPRINT_WHD_DEBUG(("MBRBlockDevice init failed, repatitioning\n\r"));
    if (mbr_bd->partition(qspi_bd, 1, 0x0B, 0, 1024 * 1024) != BD_ERROR_OK) {
        return WICED_ERROR;
    }
    WPRINT_WHD_DEBUG(("MBRBockDevice repatitioning OK, reinit\n\r"));

    if (mbr_bd->init() != BD_ERROR_OK) {
        return WICED_ERROR;
    }
    WPRINT_WHD_DEBUG(("MBRBockDevice init OK\n\r"));

    wifi_fs = new FATFileSystem(WIFI_DEFAULT_MOUNT_NAME);

    if (wifi_fs->reformat(mbr_bd) != 0) {
        return WICED_ERROR;
    }
    WPRINT_WHD_DEBUG(("FATFileSystem reformat and mount OK\n\r"));

    fp = fopen(WIFI_DEFAULT_FIRMWARE_PATH, "wb");
    if (fp == NULL) {
        return WICED_ERROR;
    }
    ret = fwrite(wifi_firmware_image_data, wifi_firmware_image.size, 1, fp);
    if (ret != wifi_firmware_image.size) {
        return WICED_ERROR;
    }
    fclose(fp);

    if (mbr_bd->sync() != 0) {
        return WICED_ERROR;
    }
    WPRINT_WHD_DEBUG(("Sync BlockDevice OK\n\r"));

    if (wifi_fs->unmount() != 0) {
        return WICED_ERROR;
    }
    WPRINT_WHD_DEBUG(("Unmount FS\n\r"));
    wifi_fs = NULL;
#endif

    return WICED_SUCCESS;
}

wiced_result_t wiced_filesystem_init(void)
{
    if (mbr_bd == NULL && wifi_fs == NULL) {
        WPRINT_WHD_DEBUG(("Initialize FileSystem with Mbed default settings\n\r"));
        qspi_bd = new QSPIFBlockDevice(PD_11, PD_12, PF_7, PD_13,  PF_10, PG_6, QSPIF_POLARITY_MODE_1, 40000000);

        if (qspi_bd->init() == BD_ERROR_OK) {
            mbr_bd = new MBRBlockDevice(qspi_bd, WIFI_DEFAULT_PARTITION);
            if (mbr_bd->init() == BD_ERROR_OK) {
                return WICED_SUCCESS;
            } else {
                return whd_default_firmware_restore();
            }
        }
        return WICED_ERROR;
    } else {
        WPRINT_WHD_DEBUG(("FileSystem initialized with user settings\n\r"));
        return WICED_SUCCESS;
    }
}

wiced_result_t wiced_filesystem_mount(BlockDevice *device, wiced_filesystem_handle_type_t fs_type, wiced_filesystem_t *fs_handle_out, const char *mounted_name)
{
    wifi_fs = new FATFileSystem(mounted_name);

    int err = wifi_fs->mount(device);
    whd_firmware_check_hook(mounted_name, err);
    if (!err) {
        //fs_handle_out = wifi_fs
        return WICED_SUCCESS;
    }
    return WICED_ERROR;
}

wiced_result_t wiced_filesystem_file_open(wiced_filesystem_t *fs_handle, wiced_file_t *file_handle_out, const char *filename, wiced_filesystem_open_mode_t mode)
{
    /* This is called by mbed test system */
    //if (mbr_bd == NULL && wifi_fs == NULL) {
    //    wiced_filesystem_init();
    //}
    //This can be called from user sketch to provide custom block device and mount point before WiFi.beginAP or WiFi.begin
    if (wifi_fs == NULL) {
        wiced_filesystem_mount(mbr_bd, WIFI_DEFAULT_FS, fs_handle, WIFI_DEFAULT_MOUNT_NAME);
    }

    if (wifi_fs == NULL) {
        return WICED_ERROR;
    }

    *file_handle_out = open(filename, mode);
    if (*file_handle_out == -1) {
        return WICED_ERROR;
    }
    return WICED_SUCCESS;
}

wiced_result_t wiced_filesystem_file_seek(wiced_file_t *file_handle, int64_t offset, wiced_filesystem_seek_type_t whence)
{
    if (*file_handle == -1) {
        return WICED_ERROR;
    }
    lseek(*file_handle, offset, whence);
    return WICED_SUCCESS;
}

wiced_result_t wiced_filesystem_file_read(wiced_file_t *file_handle, void *data, uint64_t bytes_to_read, uint64_t *returned_bytes_count)
{
    if (*file_handle == -1) {
        return WICED_ERROR;
    }
    *returned_bytes_count = read(*file_handle, data, bytes_to_read);
    return WICED_SUCCESS;
}

wiced_result_t wiced_filesystem_file_close(wiced_file_t *file_handle)
{
    if (*file_handle == -1) {
        return WICED_ERROR;
    }
    close(*file_handle);
    return WICED_SUCCESS;
}
<|endoftext|>


<commit_before><commit_msg>Overlapping rectangles area.<commit_after><|endoftext|>


<commit_before>/* FasTC
 * Copyright (c) 2013 University of North Carolina at Chapel Hill.
 * All rights reserved.
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for educational, research, and non-profit purposes, without
 * fee, and without a written agreement is hereby granted, provided that the
 * above copyright notice, this paragraph, and the following four paragraphs
 * appear in all copies.
 *
 * Permission to incorporate this software into commercial products may be
 * obtained by contacting the authors or the Office of Technology Development
 * at the University of North Carolina at Chapel Hill <otd@unc.edu>.
 *
 * This software program and documentation are copyrighted by the University of
 * North Carolina at Chapel Hill. The software program and documentation are
 * supplied "as is," without any accompanying services from the University of
 * North Carolina at Chapel Hill or the authors. The University of North
 * Carolina at Chapel Hill and the authors do not warrant that the operation of
 * the program will be uninterrupted or error-free. The end-user understands
 * that the program was developed for research purposes and is advised not to
 * rely exclusively on the program for any reason.
 *
 * IN NO EVENT SHALL THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE
 * AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL,
 * OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF
 * THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF NORTH CAROLINA
 * AT CHAPEL HILL OR THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 *
 * THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS SPECIFICALLY
 * DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AND ANY
 * STATUTORY WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE PROVIDED HEREUNDER IS ON
 * AN "AS IS" BASIS, AND THE UNIVERSITY  OF NORTH CAROLINA AT CHAPEL HILL AND
 * THE AUTHORS HAVE NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
 * ENHANCEMENTS, OR MODIFICATIONS.
 *
 * Please send all BUG REPORTS to <pavel@cs.unc.edu>.
 *
 * The authors may be contacted via:
 *
 * Pavel Krajcevski
 * Dept of Computer Science
 * 201 S Columbia St
 * Frederick P. Brooks, Jr. Computer Science Bldg
 * Chapel Hill, NC 27599-3175
 * USA
 *
 * <http://gamma.cs.unc.edu/FasTC/>
 */

#include "Pixel.h"

#include <cstring>
#include <cassert>
#include <algorithm>

namespace FasTC {

  void Pixel::FromBits(const uint8 *bits,
                       const uint8 channelDepth[4],
                       uint8 bitOffset) {
    if(channelDepth) {
      memcpy(m_BitDepth, channelDepth, sizeof(m_BitDepth));
    } else {
      for(int i = 0; i < 4; i++) {
        m_BitDepth[i] = 8;
      }
    }

    uint32 nBits = bitOffset;
    for(uint32 i = 0; i < 4; i++) {
      nBits += m_BitDepth[i];
    }

    int32 byteIdx = 0;
    uint32 bitIdx = bitOffset;
    while(bitIdx >= 8) {
      bitIdx -= 8;
      byteIdx++;
    }

    for(int32 i = 0; i < 4; i++) {
      ChannelType &channel = Component(i);
      uint32 depth = m_BitDepth[i];

      assert(depth <= 8);

      channel = 0;
      if(0 == depth) {
        channel = 0xFF;
      } else if(depth + bitIdx < 8) {
        bitIdx += depth;
        channel = (bits[byteIdx] >> (8 - bitIdx)) & ((1 << depth) - 1);
      } else {
        const uint32 numLowBits = 8 - bitIdx;
        uint32 bitsLeft = depth - numLowBits;
        channel |= bits[byteIdx] & ((1 << numLowBits) - 1);
        byteIdx++;

        const uint8 highBitsMask = ((1 << bitsLeft) - 1);
        const uint8 highBits = (bits[byteIdx] >> (8 - bitsLeft)) & highBitsMask;
        channel <<= bitsLeft;
        channel |= highBits;
        bitIdx = bitsLeft;
      }
    }
  }

  void Pixel::ToBits(uint8 *bits, uint32 numBytes, uint32 bitOffset) const {
#ifndef NDEBUG
    uint32 bitDepthSum = bitOffset;
    for(int i = 0; i < 4; i++) {
      bitDepthSum += m_BitDepth[i];
    }
    assert((bitDepthSum / 8) < numBytes);
#endif

    uint8 byteIdx = 0;
    while(bitOffset > 8) {
      byteIdx++;
      bitOffset -= 8;
    }

    uint8 bitIdx = bitOffset;
    for(int i = 3; i >= 0; i--) {
      ChannelType val = Component(i);
      uint8 depth = m_BitDepth[i];

      if(depth + bitIdx > 8) {
        uint8 nextBitIdx = depth - (8 - bitIdx);
        uint16 v = static_cast<uint16>(val);
        bits[byteIdx++] |= (v << bitIdx) & 0xFF;
        bitIdx = nextBitIdx;
        bits[byteIdx] = (v >> (depth - bitIdx)) & 0xFF;
      } else {
        bits[byteIdx] |= (val << bitIdx) & 0xFF;
        bitIdx += depth;
      }

      if(bitIdx == 8) {
        bitIdx = 0;
        byteIdx++;
      }
    }
  }

  Pixel::ChannelType Pixel::ChangeBitDepth(Pixel::ChannelType val, uint8 oldDepth, uint8 newDepth) {
    assert(newDepth <= 8);
    assert(oldDepth <= 8);

    if(oldDepth == newDepth) {
      // Do nothing
      return val;
    } else if(oldDepth == 0 && newDepth != 0) {
      return (1 << newDepth) - 1;
    } else if(newDepth > oldDepth) {
      uint8 bitsLeft = newDepth;
      uint8 ret = 0;
      while(bitsLeft > oldDepth) {
        ret |= val;
        bitsLeft -= oldDepth;
        ret <<= std::min(bitsLeft, oldDepth);
      }

      return ret | (val >> (oldDepth - bitsLeft));

    } else {
      // oldDepth > newDepth
      if(newDepth == 0) {
        return 0xFF;
      } else {
        uint8 bitsWasted = oldDepth - newDepth;
        uint16 v = static_cast<uint16>(val);
        v = (v + (1 << (bitsWasted - 1))) >> bitsWasted;
        v = ::std::min<uint16>(::std::max<uint16>(0, v), (1 << newDepth) - 1);
        return static_cast<uint8>(v);
      }
    }

    assert(!"We shouldn't get here.");
    return 0;
  }

  void Pixel::ChangeBitDepth(const uint8 (&depth)[4]) {
    for(uint32 i = 0; i < 4; i++) {
      Component(i) = ChangeBitDepth(Component(i), m_BitDepth[i], depth[i]);
      m_BitDepth[i] = depth[i];
    }
  }

  float Pixel::ToIntensity() const {
    // First convert the pixel values to floats using premultiplied alpha...
    float a = ConvertChannelToFloat(A(), m_BitDepth[0]);
    float r = a * ConvertChannelToFloat(R(), m_BitDepth[1]);
    float g = a * ConvertChannelToFloat(G(), m_BitDepth[2]);
    float b = a * ConvertChannelToFloat(B(), m_BitDepth[3]);
    return r * 0.21f + g * 0.71f + b * 0.07f;
  }

  uint32 Pixel::Pack() const {
    Pixel eightBit(*this);
    const uint8 eightBitDepth[4] = { 8, 8, 8, 8 };
    eightBit.ChangeBitDepth(eightBitDepth);

    uint32 r = 0;
    r |= eightBit.A();
    r <<= 8;
    r |= eightBit.B();
    r <<= 8;
    r |= eightBit.G();
    r <<= 8;
    r |= eightBit.R();
    return r;
  }

  void Pixel::Unpack(uint32 rgba) {
    A() = ChangeBitDepth((rgba >> 24) & 0xFF, 8, m_BitDepth[0]);
    R() = ChangeBitDepth(rgba & 0xFF, 8, m_BitDepth[1]);
    G() = ChangeBitDepth((rgba >> 8) & 0xFF, 8, m_BitDepth[2]);
    B() = ChangeBitDepth((rgba >> 16) & 0xFF, 8, m_BitDepth[3]);
  }

  bool Pixel::operator==(const Pixel &other) const {
    uint8 depths[4];
    other.GetBitDepth(depths);

    bool ok = true;
    for(int i = 0; i < 4; i++) {
      ok = ok && m_BitDepth[i] == depths[i];

      uint8 mask = (1 << depths[i]) - 1;
      const ChannelType c = other.Component(i) & mask;
      ok = ok && (c == (Component(i) & mask));
    }
    return ok;
  }

}  // namespace FasTC
<commit_msg>Fix Intensity calculation for pixel.<commit_after>/* FasTC
 * Copyright (c) 2013 University of North Carolina at Chapel Hill.
 * All rights reserved.
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for educational, research, and non-profit purposes, without
 * fee, and without a written agreement is hereby granted, provided that the
 * above copyright notice, this paragraph, and the following four paragraphs
 * appear in all copies.
 *
 * Permission to incorporate this software into commercial products may be
 * obtained by contacting the authors or the Office of Technology Development
 * at the University of North Carolina at Chapel Hill <otd@unc.edu>.
 *
 * This software program and documentation are copyrighted by the University of
 * North Carolina at Chapel Hill. The software program and documentation are
 * supplied "as is," without any accompanying services from the University of
 * North Carolina at Chapel Hill or the authors. The University of North
 * Carolina at Chapel Hill and the authors do not warrant that the operation of
 * the program will be uninterrupted or error-free. The end-user understands
 * that the program was developed for research purposes and is advised not to
 * rely exclusively on the program for any reason.
 *
 * IN NO EVENT SHALL THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE
 * AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL,
 * OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF
 * THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF NORTH CAROLINA
 * AT CHAPEL HILL OR THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 *
 * THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS SPECIFICALLY
 * DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AND ANY
 * STATUTORY WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE PROVIDED HEREUNDER IS ON
 * AN "AS IS" BASIS, AND THE UNIVERSITY  OF NORTH CAROLINA AT CHAPEL HILL AND
 * THE AUTHORS HAVE NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
 * ENHANCEMENTS, OR MODIFICATIONS.
 *
 * Please send all BUG REPORTS to <pavel@cs.unc.edu>.
 *
 * The authors may be contacted via:
 *
 * Pavel Krajcevski
 * Dept of Computer Science
 * 201 S Columbia St
 * Frederick P. Brooks, Jr. Computer Science Bldg
 * Chapel Hill, NC 27599-3175
 * USA
 *
 * <http://gamma.cs.unc.edu/FasTC/>
 */

#include "Pixel.h"

#include <cstring>
#include <cassert>
#include <algorithm>

namespace FasTC {

  void Pixel::FromBits(const uint8 *bits,
                       const uint8 channelDepth[4],
                       uint8 bitOffset) {
    if(channelDepth) {
      memcpy(m_BitDepth, channelDepth, sizeof(m_BitDepth));
    } else {
      for(int i = 0; i < 4; i++) {
        m_BitDepth[i] = 8;
      }
    }

    uint32 nBits = bitOffset;
    for(uint32 i = 0; i < 4; i++) {
      nBits += m_BitDepth[i];
    }

    int32 byteIdx = 0;
    uint32 bitIdx = bitOffset;
    while(bitIdx >= 8) {
      bitIdx -= 8;
      byteIdx++;
    }

    for(int32 i = 0; i < 4; i++) {
      ChannelType &channel = Component(i);
      uint32 depth = m_BitDepth[i];

      assert(depth <= 8);

      channel = 0;
      if(0 == depth) {
        channel = 0xFF;
      } else if(depth + bitIdx < 8) {
        bitIdx += depth;
        channel = (bits[byteIdx] >> (8 - bitIdx)) & ((1 << depth) - 1);
      } else {
        const uint32 numLowBits = 8 - bitIdx;
        uint32 bitsLeft = depth - numLowBits;
        channel |= bits[byteIdx] & ((1 << numLowBits) - 1);
        byteIdx++;

        const uint8 highBitsMask = ((1 << bitsLeft) - 1);
        const uint8 highBits = (bits[byteIdx] >> (8 - bitsLeft)) & highBitsMask;
        channel <<= bitsLeft;
        channel |= highBits;
        bitIdx = bitsLeft;
      }
    }
  }

  void Pixel::ToBits(uint8 *bits, uint32 numBytes, uint32 bitOffset) const {
#ifndef NDEBUG
    uint32 bitDepthSum = bitOffset;
    for(int i = 0; i < 4; i++) {
      bitDepthSum += m_BitDepth[i];
    }
    assert((bitDepthSum / 8) < numBytes);
#endif

    uint8 byteIdx = 0;
    while(bitOffset > 8) {
      byteIdx++;
      bitOffset -= 8;
    }

    uint8 bitIdx = bitOffset;
    for(int i = 3; i >= 0; i--) {
      ChannelType val = Component(i);
      uint8 depth = m_BitDepth[i];

      if(depth + bitIdx > 8) {
        uint8 nextBitIdx = depth - (8 - bitIdx);
        uint16 v = static_cast<uint16>(val);
        bits[byteIdx++] |= (v << bitIdx) & 0xFF;
        bitIdx = nextBitIdx;
        bits[byteIdx] = (v >> (depth - bitIdx)) & 0xFF;
      } else {
        bits[byteIdx] |= (val << bitIdx) & 0xFF;
        bitIdx += depth;
      }

      if(bitIdx == 8) {
        bitIdx = 0;
        byteIdx++;
      }
    }
  }

  Pixel::ChannelType Pixel::ChangeBitDepth(Pixel::ChannelType val, uint8 oldDepth, uint8 newDepth) {
    assert(newDepth <= 8);
    assert(oldDepth <= 8);

    if(oldDepth == newDepth) {
      // Do nothing
      return val;
    } else if(oldDepth == 0 && newDepth != 0) {
      return (1 << newDepth) - 1;
    } else if(newDepth > oldDepth) {
      uint8 bitsLeft = newDepth;
      uint8 ret = 0;
      while(bitsLeft > oldDepth) {
        ret |= val;
        bitsLeft -= oldDepth;
        ret <<= std::min(bitsLeft, oldDepth);
      }

      return ret | (val >> (oldDepth - bitsLeft));

    } else {
      // oldDepth > newDepth
      if(newDepth == 0) {
        return 0xFF;
      } else {
        uint8 bitsWasted = oldDepth - newDepth;
        uint16 v = static_cast<uint16>(val);
        v = (v + (1 << (bitsWasted - 1))) >> bitsWasted;
        v = ::std::min<uint16>(::std::max<uint16>(0, v), (1 << newDepth) - 1);
        return static_cast<uint8>(v);
      }
    }

    assert(!"We shouldn't get here.");
    return 0;
  }

  void Pixel::ChangeBitDepth(const uint8 (&depth)[4]) {
    for(uint32 i = 0; i < 4; i++) {
      Component(i) = ChangeBitDepth(Component(i), m_BitDepth[i], depth[i]);
      m_BitDepth[i] = depth[i];
    }
  }

  float Pixel::ToIntensity() const {
    // First convert the pixel values to floats using premultiplied alpha...
    double a = ConvertChannelToFloat(A(), m_BitDepth[0]);
    double r = a * ConvertChannelToFloat(R(), m_BitDepth[1]);
    double g = a * ConvertChannelToFloat(G(), m_BitDepth[2]);
    double b = a * ConvertChannelToFloat(B(), m_BitDepth[3]);
    return static_cast<float>(r * 0.2126 + g * 0.7152 + b * 0.0722);
  }

  uint32 Pixel::Pack() const {
    Pixel eightBit(*this);
    const uint8 eightBitDepth[4] = { 8, 8, 8, 8 };
    eightBit.ChangeBitDepth(eightBitDepth);

    uint32 r = 0;
    r |= eightBit.A();
    r <<= 8;
    r |= eightBit.B();
    r <<= 8;
    r |= eightBit.G();
    r <<= 8;
    r |= eightBit.R();
    return r;
  }

  void Pixel::Unpack(uint32 rgba) {
    A() = ChangeBitDepth((rgba >> 24) & 0xFF, 8, m_BitDepth[0]);
    R() = ChangeBitDepth(rgba & 0xFF, 8, m_BitDepth[1]);
    G() = ChangeBitDepth((rgba >> 8) & 0xFF, 8, m_BitDepth[2]);
    B() = ChangeBitDepth((rgba >> 16) & 0xFF, 8, m_BitDepth[3]);
  }

  bool Pixel::operator==(const Pixel &other) const {
    uint8 depths[4];
    other.GetBitDepth(depths);

    bool ok = true;
    for(int i = 0; i < 4; i++) {
      ok = ok && m_BitDepth[i] == depths[i];

      uint8 mask = (1 << depths[i]) - 1;
      const ChannelType c = other.Component(i) & mask;
      ok = ok && (c == (Component(i) & mask));
    }
    return ok;
  }

}  // namespace FasTC
<|endoftext|>


<commit_before>#include "parser.hpp"

//////////////
// Includes //
#include <istream>
#include <string>
#include <vector>
#include <tuple>
#include <map>

#include "parsestream.hpp"
#include "streamutils.hpp"
#include "json.hpp"

//////////
// Code //

// Creating a parse exception.
ParseException::ParseException(std::string type) {
    this->type = type;
}

// Returning a string to refer to this exception.
const char* ParseException::what() const throw() {
    return ("Failed to parse a " + this->type + " piece of JSON.").c_str();
}

// Definitions for the functions.
JValue parseJSONObject( ParseStream&) throw (ParseException);
JValue parseJSONArray ( ParseStream&) throw (ParseException);
JValue parseJSONNumbe ( ParseStream&) throw (ParseException);
JValue parseJSONString( ParseStream&) throw (ParseException);
JValue parseJSONBool  ( ParseStream&) throw (ParseException);
JValue parseJSONNull  ( ParseStream&) throw (ParseException);

// Trying to specifically parse out a JSON object.
JValue parseJSONObject(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);

    if (ps.consume() == '{') {
        std::map<std::string, JValue> valueMap;
        bool first = true;

        while (true) {
            consumeWhitespace(ps);
            if (first && ps.peek() == '}')
                break;

            std::string key = parseJSONString(ps).jString();
            consumeWhitespace(ps);

            if (ps.consume() != ':')
                throw ParseException("JObject");

            consumeWhitespace(ps);
            JValue val = parseJSON(ps);
            valueMap.insert(std::pair<std::string, JValue>(key, val));
            consumeWhitespace(ps);

            char c = ps.consume();
            if (c == '}')
                break;
            else if (c != ',')
                throw ParseException("JObject");
        }

        return JValue(valueMap);
    }

    throw ParseException("JObject");
}

// Trying to specifically parse out a JSON array.
JValue parseJSONArray(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);

    if (ps.consume() == '[') {
        std::vector<JValue> values;
        bool first = true;

        while (true) {
            consumeWhitespace(ps);
            if (first && ps.peek() == ']')
                break;

            values.push_back(parseJSON(ps));
            consumeWhitespace(ps);

            char c = ps.consume();
            if (c == ']')
                break;
            else if (c != ',')
                throw ParseException("parseJSONArray");
            first = false;
        }

        return JValue(values);
    }

    throw ParseException("parseJSONArray");
}

// Trying to specifically parse out a JSON number.
JValue parseJSONNumber(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);

    std::string str;
    bool first = true;
    while (!ps.eof() && !isDelimiter(ps.peek())) {
        char c = ps.consume();

        if (first && c == '-') {
            str.push_back(c);
            first = false;
        } else if (('0' <= c && c <= '9') || c == '.')
            str.push_back(c);
        else
            throw ParseException("parseJSONNumber");
    }

    return JValue(stod(str));
}

// Trying to specifically parse out a JSON string.
JValue parseJSONString(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);
    if (ps.peek() == '"') {
        ps.consume();

        std::string str;
        while (ps.peek() != '"') {
            char c = ps.consume();
            if (c == '\n')
                throw ParseException("parseJSONString");

            if (c == '\\') {
                char c2 = ps.consume();

                switch (c2) {
                case '"':
                    str.push_back('"');
                    break;
                case '\\':
                    str.push_back('\\');
                    break;
                case '/':
                    str.push_back('/');
                case 'b':
                    str.push_back('\b');
                    break;
                case 'f':
                    str.push_back('\f');
                    break;
                case 't':
                    str.push_back('\t');
                    break;
                case 'r':
                    str.push_back('\r');
                    break;
                case 'n':
                    str.push_back('\n');
                    break;
                default:
                    throw ParseException("parseJSONString");
                    break;
                }
            } else
                str.push_back(c);
        }

        ps.consume();
        return JValue(str);
    }

    throw ParseException("parseJSONString");
}

// Trying to specifically parse out a JSON boolean.
JValue parseJSONBool(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);
    std::string str;

    while (!ps.eof() && !isDelimiter(ps.peek()))
        str.push_back(ps.consume());

    if (str.compare("true") == 0)
        return JValue(true);
    else if (str.compare("false") == 0)
        return JValue(false);

    throw ParseException("JSONBool");
}

// Trying to specifically parse out the null JSON value.
JValue parseJSONNull(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);
    std::string str;

    while (!ps.eof() && !isDelimiter(ps.peek()))
        str.push_back(ps.consume());

    if (str.compare("null") == 0)
        return JValue();
    throw ParseException("parseJSONNull");
}

// Attempting to perform a parse - and then backing up on an error.
JValue attemptParse(ParseStream& ps, JValue (*parseFn)(ParseStream&)) throw(ParseException) {
    int sl = ps.getLoc();
    try { return parseFn(ps); }
    catch (const ParseException& e) {
        ps.back(ps.getLoc() - sl);
        throw e;
    }
}

// Parsing out a block of JSON from a ParseStream.
JValue parseJSON(ParseStream& ps) throw(ParseException) {
    std::vector<JValue (*)(ParseStream&)> fns;
    fns.push_back(&parseJSONObject);
    fns.push_back(&parseJSONArray);
    fns.push_back(&parseJSONNumber);
    fns.push_back(&parseJSONString);
    fns.push_back(&parseJSONBool);
    fns.push_back(&parseJSONNull);

    for (auto it = fns.begin(); it != fns.end(); it++) {
        try { return attemptParse(ps, *it); }
        catch (const ParseException& e) { }
    }

    throw ParseException("parseJSON");
}

// Parsing out a block of JSON from a string.
JValue parseJSON(const std::string& str) throw(ParseException) {
    ParseStream ps(str);
    return parseJSON(ps);
}

// Parsing out a block of JSON from an istream.
JValue parseJSON(std::istream& stream) throw(ParseException) {
    std::string line, all;

    while (!stream.eof()) {
        std::getline(stream, line);
        all += line;
    }

    return parseJSON(all);
}
<commit_msg>Changed the exception names.<commit_after>#include "parser.hpp"

//////////////
// Includes //
#include <istream>
#include <string>
#include <vector>
#include <tuple>
#include <map>

#include "parsestream.hpp"
#include "streamutils.hpp"
#include "json.hpp"

//////////
// Code //

// Creating a parse exception.
ParseException::ParseException(std::string type) {
    this->type = type;
}

// Returning a string to refer to this exception.
const char* ParseException::what() const throw() {
    return ("Failed to parse a " + this->type + " piece of JSON.").c_str();
}

// Definitions for the functions.
JValue parseJSONObject( ParseStream&) throw (ParseException);
JValue parseJSONArray ( ParseStream&) throw (ParseException);
JValue parseJSONNumbe ( ParseStream&) throw (ParseException);
JValue parseJSONString( ParseStream&) throw (ParseException);
JValue parseJSONBool  ( ParseStream&) throw (ParseException);
JValue parseJSONNull  ( ParseStream&) throw (ParseException);

// Trying to specifically parse out a JSON object.
JValue parseJSONObject(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);

    if (ps.consume() == '{') {
        std::map<std::string, JValue> valueMap;
        bool first = true;

        while (true) {
            consumeWhitespace(ps);
            if (first && ps.peek() == '}')
                break;

            std::string key = parseJSONString(ps).jString();
            consumeWhitespace(ps);

            if (ps.consume() != ':')
                throw ParseException("parseJSONObject");

            consumeWhitespace(ps);
            JValue val = parseJSON(ps);
            valueMap.insert(std::pair<std::string, JValue>(key, val));
            consumeWhitespace(ps);

            char c = ps.consume();
            if (c == '}')
                break;
            else if (c != ',')
                throw ParseException("parseJSONObject");
        }

        return JValue(valueMap);
    }

    throw ParseException("parseJSONObject");
}

// Trying to specifically parse out a JSON array.
JValue parseJSONArray(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);

    if (ps.consume() == '[') {
        std::vector<JValue> values;
        bool first = true;

        while (true) {
            consumeWhitespace(ps);
            if (first && ps.peek() == ']')
                break;

            values.push_back(parseJSON(ps));
            consumeWhitespace(ps);

            char c = ps.consume();
            if (c == ']')
                break;
            else if (c != ',')
                throw ParseException("parseJSONArray");
            first = false;
        }

        return JValue(values);
    }

    throw ParseException("parseJSONArray");
}

// Trying to specifically parse out a JSON number.
JValue parseJSONNumber(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);

    std::string str;
    bool first = true;
    while (!ps.eof() && !isDelimiter(ps.peek())) {
        char c = ps.consume();

        if (first && c == '-') {
            str.push_back(c);
            first = false;
        } else if (('0' <= c && c <= '9') || c == '.')
            str.push_back(c);
        else
            throw ParseException("parseJSONNumber");
    }

    return JValue(stod(str));
}

// Trying to specifically parse out a JSON string.
JValue parseJSONString(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);
    if (ps.peek() == '"') {
        ps.consume();

        std::string str;
        while (ps.peek() != '"') {
            char c = ps.consume();
            if (c == '\n')
                throw ParseException("parseJSONString");

            if (c == '\\') {
                char c2 = ps.consume();

                switch (c2) {
                case '"':
                    str.push_back('"');
                    break;
                case '\\':
                    str.push_back('\\');
                    break;
                case '/':
                    str.push_back('/');
                case 'b':
                    str.push_back('\b');
                    break;
                case 'f':
                    str.push_back('\f');
                    break;
                case 't':
                    str.push_back('\t');
                    break;
                case 'r':
                    str.push_back('\r');
                    break;
                case 'n':
                    str.push_back('\n');
                    break;
                default:
                    throw ParseException("parseJSONString");
                    break;
                }
            } else
                str.push_back(c);
        }

        ps.consume();
        return JValue(str);
    }

    throw ParseException("parseJSONString");
}

// Trying to specifically parse out a JSON boolean.
JValue parseJSONBool(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);
    std::string str;

    while (!ps.eof() && !isDelimiter(ps.peek()))
        str.push_back(ps.consume());

    if (str.compare("true") == 0)
        return JValue(true);
    else if (str.compare("false") == 0)
        return JValue(false);

    throw ParseException("parseJSONBool");
}

// Trying to specifically parse out the null JSON value.
JValue parseJSONNull(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);
    std::string str;

    while (!ps.eof() && !isDelimiter(ps.peek()))
        str.push_back(ps.consume());

    if (str.compare("null") == 0)
        return JValue();
    throw ParseException("parseJSONNull");
}

// Attempting to perform a parse - and then backing up on an error.
JValue attemptParse(ParseStream& ps, JValue (*parseFn)(ParseStream&)) throw(ParseException) {
    int sl = ps.getLoc();
    try { return parseFn(ps); }
    catch (const ParseException& e) {
        ps.back(ps.getLoc() - sl);
        throw e;
    }
}

// Parsing out a block of JSON from a ParseStream.
JValue parseJSON(ParseStream& ps) throw(ParseException) {
    std::vector<JValue (*)(ParseStream&)> fns;
    fns.push_back(&parseJSONObject);
    fns.push_back(&parseJSONArray);
    fns.push_back(&parseJSONNumber);
    fns.push_back(&parseJSONString);
    fns.push_back(&parseJSONBool);
    fns.push_back(&parseJSONNull);

    for (auto it = fns.begin(); it != fns.end(); it++) {
        try { return attemptParse(ps, *it); }
        catch (const ParseException& e) { }
    }

    throw ParseException("parseJSON");
}

// Parsing out a block of JSON from a string.
JValue parseJSON(const std::string& str) throw(ParseException) {
    ParseStream ps(str);
    return parseJSON(ps);
}

// Parsing out a block of JSON from an istream.
JValue parseJSON(std::istream& stream) throw(ParseException) {
    std::string line, all;

    while (!stream.eof()) {
        std::getline(stream, line);
        all += line;
    }

    return parseJSON(all);
}
<|endoftext|>


<commit_before><commit_msg>lib: reset the DBus proxy when registration failed<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: excdefs.hxx,v $
 *
 *  $Revision: 1.41 $
 *
 *  last change: $Author: rt $ $Date: 2004-03-02 09:41:52 $
 *
 *  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 _EXCDEFS_HXX
#define _EXCDEFS_HXX

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

// (0x001C) NOTE ==============================================================

#define EXC_NOTE5_MAXTEXT           2048

// (0x0031) FONT ==============================================================

// color
#define EXC_FONTCOL_IGNORE          0x7FFF

// height
#define EXC_FONTHGHT_COEFF          20.0

// (0x0092) PALETTE ===========================================================

// special color indices
#define EXC_COLIND_AUTOTEXT         77
#define EXC_COLIND_AUTOLINE         77
#define EXC_COLIND_AUTOFILLBG       77
#define EXC_COLIND_AUTOFILLFG       78

// (0x009B, 0x009D, 0x009E) AUTOFILTER ========================================

// flags
#define EXC_AFFLAG_AND              0x0000
#define EXC_AFFLAG_OR               0x0001
#define EXC_AFFLAG_ANDORMASK        0x0003
#define EXC_AFFLAG_SIMPLE1          0x0004
#define EXC_AFFLAG_SIMPLE2          0x0008
#define EXC_AFFLAG_TOP10            0x0010
#define EXC_AFFLAG_TOP10TOP         0x0020
#define EXC_AFFLAG_TOP10PERC        0x0040

// data types
#define EXC_AFTYPE_NOTUSED          0x00
#define EXC_AFTYPE_RK               0x02
#define EXC_AFTYPE_DOUBLE           0x04
#define EXC_AFTYPE_STRING           0x06
#define EXC_AFTYPE_BOOLERR          0x08
#define EXC_AFTYPE_INVALID          0x0A
#define EXC_AFTYPE_EMPTY            0x0C
#define EXC_AFTYPE_NOTEMPTY         0x0E

// comparison operands
#define EXC_AFOPER_NONE             0x00
#define EXC_AFOPER_LESS             0x01
#define EXC_AFOPER_EQUAL            0x02
#define EXC_AFOPER_LESSEQUAL        0x03
#define EXC_AFOPER_GREATER          0x04
#define EXC_AFOPER_NOTEQUAL         0x05
#define EXC_AFOPER_GREATEREQUAL     0x06

// (0x00AE, 0x00AF) SCENARIO, SCENMAN =========================================

#define EXC_SCEN_MAXCELL            32

// (0x00E5) CELLMERGING =======================================================

#define EXC_MERGE_MAXCOUNT          1024

// (0x0208) ROW ===============================================================

// flags
#define EXC_ROW_COLLAPSED           0x0010
#define EXC_ROW_ZEROHEIGHT          0x0020
#define EXC_ROW_UNSYNCED            0x0040
#define EXC_ROW_GHOSTDIRTY          0x0080
#define EXC_ROW_XFMASK              0x0FFF

// outline
#define EXC_ROW_LEVELFLAGS(nOL)     (nOL & 0x0007)
#define EXC_ROW_GETLEVEL(nFlag)     (nFlag & 0x0007)

// unknown, always save
#define EXC_ROW_FLAGCOMMON          0x0100

// row height
#define EXC_ROW_VALZEROHEIGHT       0x00FF
#define EXC_ROW_FLAGDEFHEIGHT       0x8000

// (0x0236) TABLE =============================================================

#define EXC_TABOP_CALCULATE         0x0003
#define EXC_TABOP_ROW               0x0004
#define EXC_TABOP_BOTH              0x0008

// (0x023E) WINDOW2 ===========================================================

#define EXC_WIN2_SHOWFORMULAS       0x0001
#define EXC_WIN2_SHOWGRID           0x0002
#define EXC_WIN2_SHOWHEADINGS       0x0004
#define EXC_WIN2_FROZEN             0x0008
#define EXC_WIN2_SHOWZEROS          0x0010
#define EXC_WIN2_DEFAULTCOLOR       0x0020
const sal_uInt16 EXC_WIN2_MIRRORED          = 0x0040;
#define EXC_WIN2_OUTLINE            0x0080
#define EXC_WIN2_FROZENNOSPLIT      0x0100
#define EXC_WIN2_SELECTED           0x0200
#define EXC_WIN2_DISPLAYED          0x0400

// Specials for outlines ======================================================

#define EXC_OUTLINE_MAX             7
#define EXC_OUTLINE_COUNT           (EXC_OUTLINE_MAX + 1)

// data pilot / pivot tables ==================================================

// subtotal functions
#define EXC_PIVOT_SUBT_SUM          0x0000
#define EXC_PIVOT_SUBT_COUNT        0x0001
#define EXC_PIVOT_SUBT_AVERAGE      0x0002
#define EXC_PIVOT_SUBT_MAX          0x0003
#define EXC_PIVOT_SUBT_MIN          0x0004
#define EXC_PIVOT_SUBT_PROD         0x0005
#define EXC_PIVOT_SUBT_COUNTNUM     0x0006
#define EXC_PIVOT_SUBT_STDDEV       0x0007
#define EXC_PIVOT_SUBT_STDDEVP      0x0008
#define EXC_PIVOT_SUBT_VAR          0x0009
#define EXC_PIVOT_SUBT_VARP         0x000A

// field orientation
#define EXC_PIVOT_AXIS_NONE         0x0000
#define EXC_PIVOT_AXIS_ROW          0x0001
#define EXC_PIVOT_AXIS_COL          0x0002
#define EXC_PIVOT_AXIS_PAGE         0x0004
#define EXC_PIVOT_AXIS_DATA         0x0008
#define EXC_PIVOT_AXIS_RCP_MASK     (EXC_PIVOT_AXIS_ROW|EXC_PIVOT_AXIS_COL|EXC_PIVOT_AXIS_PAGE)

// misc xcl record flags
#define EXC_SXVIEW_COMMON           0x0208
#define EXC_SXVIEW_ROWGRAND         0x0001
#define EXC_SXVIEW_COLGRAND         0x0002

#define EXC_SXVDEX_COMMON           0x0A00141E
#define EXC_SXVDEX_SHOWALL          0x00000001

#define EXC_SXVI_HIDDEN             0x0001
#define EXC_SXVI_HIDEDETAIL         0x0002
#define EXC_SXVI_FORMULA            0x0004
#define EXC_SXVI_MISSING            0x0008

#define EXC_SXVS_EXCEL              0x0001
#define EXC_SXVS_EXTERN             0x0002
#define EXC_SXVS_MULTICONSR         0x0004
#define EXC_SXVS_PIVOTTAB           0x0008
#define EXC_SXVS_SCENMAN            0x0010

#define EXC_SXIVD_IDDATA            0xFFFE

// pivot cache record flags
#define EXC_SXFIELD_COMMON          0x0001
#define EXC_SXFIELD_READLATER       0x0002
#define EXC_SXFIELD_16BIT           0x0200

#define EXC_SXITEM_

// defines for change tracking ================================================

// opcodes
#define EXC_CHTR_OP_COLFLAG         0x0001
#define EXC_CHTR_OP_DELFLAG         0x0002
#define EXC_CHTR_OP_INSROW          0x0000
#define EXC_CHTR_OP_INSCOL          EXC_CHTR_OP_COLFLAG
#define EXC_CHTR_OP_DELROW          EXC_CHTR_OP_DELFLAG
#define EXC_CHTR_OP_DELCOL          (EXC_CHTR_OP_COLFLAG|EXC_CHTR_OP_DELFLAG)
#define EXC_CHTR_OP_MOVE            0x0004
#define EXC_CHTR_OP_INSTAB          0x0005
#define EXC_CHTR_OP_CELL            0x0008
#define EXC_CHTR_OP_RENAME          0x0009
#define EXC_CHTR_OP_NAME            0x000A
#define EXC_CHTR_OP_FORMAT          0x000B
#define EXC_CHTR_OP_UNKNOWN         0xFFFF

// data types
#define EXC_CHTR_TYPE_MASK          0x0007
#define EXC_CHTR_TYPE_FORMATMASK    0xFF00
#define EXC_CHTR_TYPE_EMPTY         0x0000
#define EXC_CHTR_TYPE_RK            0x0001
#define EXC_CHTR_TYPE_DOUBLE        0x0002
#define EXC_CHTR_TYPE_STRING        0x0003
#define EXC_CHTR_TYPE_BOOL          0x0004
#define EXC_CHTR_TYPE_FORMULA       0x0005

// accept flags
#define EXC_CHTR_NOTHING            0x0000
#define EXC_CHTR_ACCEPT             0x0001
#define EXC_CHTR_REJECT             0x0003

// ============================================================================

#endif // _EXCDEFS_HXX

<commit_msg>INTEGRATION: CWS pagefields (1.39.156); FILE MERGED 2004/03/30 14:53:41 sab 1.39.156.4: RESYNC: (1.40-1.41); FILE MERGED 2004/03/03 10:29:52 sab 1.39.156.3: RESYNC: (1.39-1.40); FILE MERGED 2004/02/27 17:30:14 dr 1.39.156.2: #i22164# export of DP page field selection 2004/02/27 12:26:16 dr 1.39.156.1: #i22164# import of DP page field selection<commit_after>/*************************************************************************
 *
 *  $RCSfile: excdefs.hxx,v $
 *
 *  $Revision: 1.42 $
 *
 *  last change: $Author: hr $ $Date: 2004-04-13 12:27:48 $
 *
 *  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 _EXCDEFS_HXX
#define _EXCDEFS_HXX

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

// (0x001C) NOTE ==============================================================

#define EXC_NOTE5_MAXTEXT           2048

// (0x0031) FONT ==============================================================

// color
#define EXC_FONTCOL_IGNORE          0x7FFF

// height
#define EXC_FONTHGHT_COEFF          20.0

// (0x0092) PALETTE ===========================================================

// special color indices
#define EXC_COLIND_AUTOTEXT         77
#define EXC_COLIND_AUTOLINE         77
#define EXC_COLIND_AUTOFILLBG       77
#define EXC_COLIND_AUTOFILLFG       78

// (0x009B, 0x009D, 0x009E) AUTOFILTER ========================================

// flags
#define EXC_AFFLAG_AND              0x0000
#define EXC_AFFLAG_OR               0x0001
#define EXC_AFFLAG_ANDORMASK        0x0003
#define EXC_AFFLAG_SIMPLE1          0x0004
#define EXC_AFFLAG_SIMPLE2          0x0008
#define EXC_AFFLAG_TOP10            0x0010
#define EXC_AFFLAG_TOP10TOP         0x0020
#define EXC_AFFLAG_TOP10PERC        0x0040

// data types
#define EXC_AFTYPE_NOTUSED          0x00
#define EXC_AFTYPE_RK               0x02
#define EXC_AFTYPE_DOUBLE           0x04
#define EXC_AFTYPE_STRING           0x06
#define EXC_AFTYPE_BOOLERR          0x08
#define EXC_AFTYPE_INVALID          0x0A
#define EXC_AFTYPE_EMPTY            0x0C
#define EXC_AFTYPE_NOTEMPTY         0x0E

// comparison operands
#define EXC_AFOPER_NONE             0x00
#define EXC_AFOPER_LESS             0x01
#define EXC_AFOPER_EQUAL            0x02
#define EXC_AFOPER_LESSEQUAL        0x03
#define EXC_AFOPER_GREATER          0x04
#define EXC_AFOPER_NOTEQUAL         0x05
#define EXC_AFOPER_GREATEREQUAL     0x06

// (0x00AE, 0x00AF) SCENARIO, SCENMAN =========================================

#define EXC_SCEN_MAXCELL            32

// (0x00E5) CELLMERGING =======================================================

#define EXC_MERGE_MAXCOUNT          1024

// (0x0208) ROW ===============================================================

// flags
#define EXC_ROW_COLLAPSED           0x0010
#define EXC_ROW_ZEROHEIGHT          0x0020
#define EXC_ROW_UNSYNCED            0x0040
#define EXC_ROW_GHOSTDIRTY          0x0080
#define EXC_ROW_XFMASK              0x0FFF

// outline
#define EXC_ROW_LEVELFLAGS(nOL)     (nOL & 0x0007)
#define EXC_ROW_GETLEVEL(nFlag)     (nFlag & 0x0007)

// unknown, always save
#define EXC_ROW_FLAGCOMMON          0x0100

// row height
#define EXC_ROW_VALZEROHEIGHT       0x00FF
#define EXC_ROW_FLAGDEFHEIGHT       0x8000

// (0x0236) TABLE =============================================================

#define EXC_TABOP_CALCULATE         0x0003
#define EXC_TABOP_ROW               0x0004
#define EXC_TABOP_BOTH              0x0008

// (0x023E) WINDOW2 ===========================================================

#define EXC_WIN2_SHOWFORMULAS       0x0001
#define EXC_WIN2_SHOWGRID           0x0002
#define EXC_WIN2_SHOWHEADINGS       0x0004
#define EXC_WIN2_FROZEN             0x0008
#define EXC_WIN2_SHOWZEROS          0x0010
#define EXC_WIN2_DEFAULTCOLOR       0x0020
const sal_uInt16 EXC_WIN2_MIRRORED          = 0x0040;
#define EXC_WIN2_OUTLINE            0x0080
#define EXC_WIN2_FROZENNOSPLIT      0x0100
#define EXC_WIN2_SELECTED           0x0200
#define EXC_WIN2_DISPLAYED          0x0400

// Specials for outlines ======================================================

#define EXC_OUTLINE_MAX             7
#define EXC_OUTLINE_COUNT           (EXC_OUTLINE_MAX + 1)

// data pilot / pivot tables ==================================================

// subtotal functions
#define EXC_PIVOT_SUBT_SUM          0x0000
#define EXC_PIVOT_SUBT_COUNT        0x0001
#define EXC_PIVOT_SUBT_AVERAGE      0x0002
#define EXC_PIVOT_SUBT_MAX          0x0003
#define EXC_PIVOT_SUBT_MIN          0x0004
#define EXC_PIVOT_SUBT_PROD         0x0005
#define EXC_PIVOT_SUBT_COUNTNUM     0x0006
#define EXC_PIVOT_SUBT_STDDEV       0x0007
#define EXC_PIVOT_SUBT_STDDEVP      0x0008
#define EXC_PIVOT_SUBT_VAR          0x0009
#define EXC_PIVOT_SUBT_VARP         0x000A

// field orientation
#define EXC_PIVOT_AXIS_NONE         0x0000
#define EXC_PIVOT_AXIS_ROW          0x0001
#define EXC_PIVOT_AXIS_COL          0x0002
#define EXC_PIVOT_AXIS_PAGE         0x0004
#define EXC_PIVOT_AXIS_DATA         0x0008
#define EXC_PIVOT_AXIS_RCP_MASK     (EXC_PIVOT_AXIS_ROW|EXC_PIVOT_AXIS_COL|EXC_PIVOT_AXIS_PAGE)

// misc xcl record flags
#define EXC_SXVIEW_COMMON           0x0208
#define EXC_SXVIEW_ROWGRAND         0x0001
#define EXC_SXVIEW_COLGRAND         0x0002

#define EXC_SXVDEX_COMMON           0x0A00141E
#define EXC_SXVDEX_SHOWALL          0x00000001

#define EXC_SXVI_HIDDEN             0x0001
#define EXC_SXVI_HIDEDETAIL         0x0002
#define EXC_SXVI_FORMULA            0x0004
#define EXC_SXVI_MISSING            0x0008

#define EXC_SXVS_EXCEL              0x0001
#define EXC_SXVS_EXTERN             0x0002
#define EXC_SXVS_MULTICONSR         0x0004
#define EXC_SXVS_PIVOTTAB           0x0008
#define EXC_SXVS_SCENMAN            0x0010

#define EXC_SXIVD_IDDATA            0xFFFE

const sal_uInt16 EXC_ID_SXPI            = 0x00B6;
const sal_uInt16 EXC_SXPI_ALLITEMS      = 0x7FFD;

// pivot cache record flags
#define EXC_SXFIELD_COMMON          0x0001
#define EXC_SXFIELD_READLATER       0x0002
#define EXC_SXFIELD_16BIT           0x0200

// defines for change tracking ================================================

// opcodes
#define EXC_CHTR_OP_COLFLAG         0x0001
#define EXC_CHTR_OP_DELFLAG         0x0002
#define EXC_CHTR_OP_INSROW          0x0000
#define EXC_CHTR_OP_INSCOL          EXC_CHTR_OP_COLFLAG
#define EXC_CHTR_OP_DELROW          EXC_CHTR_OP_DELFLAG
#define EXC_CHTR_OP_DELCOL          (EXC_CHTR_OP_COLFLAG|EXC_CHTR_OP_DELFLAG)
#define EXC_CHTR_OP_MOVE            0x0004
#define EXC_CHTR_OP_INSTAB          0x0005
#define EXC_CHTR_OP_CELL            0x0008
#define EXC_CHTR_OP_RENAME          0x0009
#define EXC_CHTR_OP_NAME            0x000A
#define EXC_CHTR_OP_FORMAT          0x000B
#define EXC_CHTR_OP_UNKNOWN         0xFFFF

// data types
#define EXC_CHTR_TYPE_MASK          0x0007
#define EXC_CHTR_TYPE_FORMATMASK    0xFF00
#define EXC_CHTR_TYPE_EMPTY         0x0000
#define EXC_CHTR_TYPE_RK            0x0001
#define EXC_CHTR_TYPE_DOUBLE        0x0002
#define EXC_CHTR_TYPE_STRING        0x0003
#define EXC_CHTR_TYPE_BOOL          0x0004
#define EXC_CHTR_TYPE_FORMULA       0x0005

// accept flags
#define EXC_CHTR_NOTHING            0x0000
#define EXC_CHTR_ACCEPT             0x0001
#define EXC_CHTR_REJECT             0x0003

// ============================================================================

#endif // _EXCDEFS_HXX

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: viewcontactofsdrmediaobj.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2004-10-12 10:04:42 $
 *
 *  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 _SDR_CONTACT_VIEWCONTACTOFSDRMEDIAOBJ_HXX
#define _SDR_CONTACT_VIEWCONTACTOFSDRMEDIAOBJ_HXX

#ifndef _SDR_CONTACT_VIEWCONTACTOFSDROBJ_HXX
#include <svx/sdr/contact/viewcontactofsdrobj.hxx>
#endif

//////////////////////////////////////////////////////////////////////////////
// predeclarations

class SdrMediaObj;
namespace avmedia { class MediaItem; }

//////////////////////////////////////////////////////////////////////////////

namespace sdr
{
    namespace contact
    {
        class ViewContactOfSdrMediaObj : public ViewContactOfSdrObj
        {
            friend class ViewObjectContactOfSdrMediaObj;

        public:

            // basic constructor, used from SdrObject.
            ViewContactOfSdrMediaObj( SdrMediaObj& rMediaObj );

            // The destructor. When PrepareDelete() was not called before (see there)
            // warnings will be generated in debug version if there are still contacts
            // existing.
            virtual ~ViewContactOfSdrMediaObj();

            // Paint this object. This is before evtl. SubObjects get painted. It needs to return
            // sal_True when something was pained and the paint output rectangle in rPaintRectangle.
            virtual sal_Bool PaintObject(DisplayInfo& rDisplayInfo, Rectangle& rPaintRectangle, const ViewObjectContact& rAssociatedVOC);

        public:

            bool    hasPreferredSize() const;
            Size    getPreferredSize() const;

            void    updateMediaItem( ::avmedia::MediaItem& rItem ) const;
            void    executeMediaItem( const ::avmedia::MediaItem& rItem );

        protected:

            // Create a Object-Specific ViewObjectContact, set ViewContact and
            // ObjectContact. Always needs to return something.
            virtual ViewObjectContact& CreateObjectSpecificViewObjectContact(ObjectContact& rObjectContact);

            // get notified if some properties have changed
            virtual void mediaPropertiesChanged( const ::avmedia::MediaItem& rNewState );
        };
    } // end of namespace contact
} // end of namespace sdr

//////////////////////////////////////////////////////////////////////////////

#endif //_SDR_CONTACT_VIEWCONTACTOFSDRMEDIAOBJ_HXX
<commit_msg>INTEGRATION: CWS visibility01 (1.3.8); FILE MERGED 2004/11/19 12:54:51 mmeeks 1.3.8.1: Issue number: #i35758# Submitted by: mnicel Reviewed by:  mmeeks<commit_after>/*************************************************************************
 *
 *  $RCSfile: viewcontactofsdrmediaobj.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2005-01-21 16:21:10 $
 *
 *  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 _SDR_CONTACT_VIEWCONTACTOFSDRMEDIAOBJ_HXX
#define _SDR_CONTACT_VIEWCONTACTOFSDRMEDIAOBJ_HXX

#ifndef _SDR_CONTACT_VIEWCONTACTOFSDROBJ_HXX
#include <svx/sdr/contact/viewcontactofsdrobj.hxx>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

//////////////////////////////////////////////////////////////////////////////
// predeclarations

class SdrMediaObj;
namespace avmedia { class MediaItem; }

//////////////////////////////////////////////////////////////////////////////

namespace sdr
{
    namespace contact
    {
        class SVX_DLLPUBLIC ViewContactOfSdrMediaObj : public ViewContactOfSdrObj
        {
            friend class ViewObjectContactOfSdrMediaObj;

        public:

            // basic constructor, used from SdrObject.
            ViewContactOfSdrMediaObj( SdrMediaObj& rMediaObj );

            // The destructor. When PrepareDelete() was not called before (see there)
            // warnings will be generated in debug version if there are still contacts
            // existing.
            virtual ~ViewContactOfSdrMediaObj();

            // Paint this object. This is before evtl. SubObjects get painted. It needs to return
            // sal_True when something was pained and the paint output rectangle in rPaintRectangle.
            virtual sal_Bool PaintObject(DisplayInfo& rDisplayInfo, Rectangle& rPaintRectangle, const ViewObjectContact& rAssociatedVOC);

        public:

            bool    hasPreferredSize() const;
            Size    getPreferredSize() const;

            void    updateMediaItem( ::avmedia::MediaItem& rItem ) const;
            void    executeMediaItem( const ::avmedia::MediaItem& rItem );

        protected:

            // Create a Object-Specific ViewObjectContact, set ViewContact and
            // ObjectContact. Always needs to return something.
            virtual ViewObjectContact& CreateObjectSpecificViewObjectContact(ObjectContact& rObjectContact);

            // get notified if some properties have changed
            virtual void mediaPropertiesChanged( const ::avmedia::MediaItem& rNewState );
        };
    } // end of namespace contact
} // end of namespace sdr

//////////////////////////////////////////////////////////////////////////////

#endif //_SDR_CONTACT_VIEWCONTACTOFSDRMEDIAOBJ_HXX
<|endoftext|>


<commit_before>/// \file player.cpp
/// Holds all code for the MistPlayer application used for VoD streams.

#include <iostream>//for std::cerr
#include <stdio.h> //for fileno
#include <stdlib.h> //for atoi
#include <sys/time.h>
#include <mist/dtsc.h>
#include <mist/json.h>
#include <mist/config.h>
#include <mist/socket.h>

/// Copy of stats from buffer_user.cpp
class Stats{
  public:
    unsigned int up;
    unsigned int down;
    std::string host;
    std::string connector;
    unsigned int conntime;
    Stats(){
      up = 0; down = 0; conntime = 0;
    };
    /// Reads a stats string and parses it to the internal representation.
    Stats(std::string s){
      size_t f = s.find(' ');
      if (f != std::string::npos){
        host = s.substr(0, f);
        s.erase(0, f+1);
      }
      f = s.find(' ');
      if (f != std::string::npos){
        connector = s.substr(0, f);
        s.erase(0, f+1);
      }
      f = s.find(' ');
      if (f != std::string::npos){
        conntime = atoi(s.substr(0, f).c_str());
        s.erase(0, f+1);
      }
      f = s.find(' ');
      if (f != std::string::npos){
        up = atoi(s.substr(0, f).c_str());
        s.erase(0, f+1);
        down = atoi(s.c_str());
      }
    };
};

/// Gets the current system time in milliseconds.
long long int getNowMS(){
  timeval t;
  gettimeofday(&t, 0);
  return t.tv_sec * 1000 + t.tv_usec/1000;
}//getNowMS

int main(int argc, char** argv){
  Util::Config conf(argv[0], PACKAGE_VERSION);
  conf.addOption("filename", JSON::fromString("{\"arg_num\":1, \"help\":\"Name of the file to write to stdout.\"}"));
  conf.parseArgs(argc, argv);
  conf.activate();
  int playing = 0;

  DTSC::File source = DTSC::File(conf.getString("filename"));
  Socket::Connection in_out = Socket::Connection(fileno(stdout), fileno(stdin));
  std::string meta_str = source.getHeader();
  JSON::Value pausemark;
  pausemark["datatype"] = "pause_marker";
  pausemark["time"] = (long long int)0;

  Socket::Connection StatsSocket = Socket::Connection("/tmp/mist/statistics", true);

  //send the header
  {
    in_out.Send("DTSC");
    unsigned int size = htonl(meta_str.size());
    in_out.Send((char*)&size, 4);
    in_out.Send(meta_str);
  }

  JSON::Value meta = JSON::fromDTMI(meta_str);
  JSON::Value last_pack;

  bool meta_sent = false;
  long long now, timeDiff = 0, lastTime = 0;
  Stats sts;

  while (in_out.connected() && std::cin.good() && std::cout.good()){
    if (in_out.spool()){
      while (in_out.Received().find('\n') != std::string::npos){
        std::string cmd = in_out.Received().substr(0, in_out.Received().find('\n'));
        in_out.Received().erase(0, in_out.Received().find('\n')+1);
        if (cmd != ""){
          switch (cmd[0]){
            case 'P':{ //Push
              #if DEBUG >= 4
              std::cerr << "Received push - ignoring (" << cmd << ")" << std::endl;
              #endif
              in_out.close();//pushing to VoD makes no sense
            } break;
            case 'S':{ //Stats
              if (!StatsSocket.connected()){
                StatsSocket = Socket::Connection("/tmp/mist/statistics", true);
              }
              if (StatsSocket.connected()){
                sts = Stats(cmd.substr(2));
                JSON::Value json_sts;
                json_sts["vod"]["down"] = (long long int)sts.down;
                json_sts["vod"]["up"] = (long long int)sts.up;
                json_sts["vod"]["time"] = (long long int)sts.conntime;
                json_sts["vod"]["host"] = sts.host;
                json_sts["vod"]["connector"] = sts.connector;
                json_sts["vod"]["filename"] = conf.getString("filename");
                json_sts["vod"]["now"] = (long long int)time(0);
                json_sts["vod"]["start"] = (long long int)(time(0) - sts.conntime);
                if (!meta_sent){
                  json_sts["vod"]["meta"] = meta;
                  meta_sent = true;
                }
                StatsSocket.Send(json_sts.toString().c_str());
                StatsSocket.Send("\n\n");
                StatsSocket.flush();
              }
            } break;
            case 's':{ //second-seek
              #if DEBUG >= 4
              std::cerr << "Received ms-seek (" << cmd << ")" << std::endl;
              #endif
              int ms = JSON::Value(cmd.substr(2)).asInt();
              bool ret = source.seek_time(ms);
              #if DEBUG >= 4
              std::cerr << "Second-seek completed (time " << ms << "ms) " << ret << std::endl;
              #endif
            } break;
            case 'f':{ //frame-seek
              #if DEBUG >= 4
              std::cerr << "Received frame-seek (" << cmd << ")" << std::endl;
              #endif
              bool ret = source.seek_frame(JSON::Value(cmd.substr(2)).asInt());
              #if DEBUG >= 4
              std::cerr << "Frame-seek completed " << ret << std::endl;
              #endif
            } break;
            case 'p':{ //play
              #if DEBUG >= 4
              std::cerr << "Received play" << std::endl;
              #endif
              playing = -1;
              in_out.setBlocking(false);
            } break;
            case 'o':{ //once-play
              #if DEBUG >= 4
              std::cerr << "Received once-play" << std::endl;
              #endif
              if (playing <= 0){playing = 1;}
              ++playing;
              in_out.setBlocking(false);
            } break;
            case 'q':{ //quit-playing
              #if DEBUG >= 4
              std::cerr << "Received quit-playing" << std::endl;
              #endif
              playing = 0;
              in_out.setBlocking(true);
            } break;
          }
        }
      }
    }
    if (playing != 0){
      now = getNowMS();
      if (playing > 0 || now - timeDiff >= lastTime || lastTime - (now - timeDiff) > 15000) {
        source.seekNext();
        lastTime = source.getJSON()["time"].asInt();
        if ((now - timeDiff - lastTime) > 5000 || (now - timeDiff - lastTime < -5000)){
          timeDiff = now - lastTime;
        }
        if (source.getJSON().isMember("keyframe")){
          if (playing > 0){--playing;}
          if (playing == 0){
            #if DEBUG >= 4
            std::cerr << "Sending pause_marker" << std::endl;
            #endif
            pausemark["time"] = (long long int)now;
            pausemark.toPacked();
            in_out.Send(pausemark.toNetPacked());
            in_out.flush();
            in_out.setBlocking(true);
          }
        }
        if (playing != 0){
          //insert proper header for this type of data
          in_out.Send("DTPD");
          //insert the packet length
          unsigned int size = htonl(source.getPacket().size());
          in_out.Send((char*)&size, 4);
          in_out.Send(source.getPacket());
        }
      } else {
        usleep(std::min(10000LL, lastTime - (now - timeDiff)) * 1000);
      }
    }
    usleep(10000);//sleep 10ms
  }

  StatsSocket.close();
  return 0;
}
<commit_msg>Fixed MistPlayer not shutting down.<commit_after>/// \file player.cpp
/// Holds all code for the MistPlayer application used for VoD streams.

#include <iostream>//for std::cerr
#include <stdio.h> //for fileno
#include <stdlib.h> //for atoi
#include <sys/time.h>
#include <mist/dtsc.h>
#include <mist/json.h>
#include <mist/config.h>
#include <mist/socket.h>

/// Copy of stats from buffer_user.cpp
class Stats{
  public:
    unsigned int up;
    unsigned int down;
    std::string host;
    std::string connector;
    unsigned int conntime;
    Stats(){
      up = 0; down = 0; conntime = 0;
    };
    /// Reads a stats string and parses it to the internal representation.
    Stats(std::string s){
      size_t f = s.find(' ');
      if (f != std::string::npos){
        host = s.substr(0, f);
        s.erase(0, f+1);
      }
      f = s.find(' ');
      if (f != std::string::npos){
        connector = s.substr(0, f);
        s.erase(0, f+1);
      }
      f = s.find(' ');
      if (f != std::string::npos){
        conntime = atoi(s.substr(0, f).c_str());
        s.erase(0, f+1);
      }
      f = s.find(' ');
      if (f != std::string::npos){
        up = atoi(s.substr(0, f).c_str());
        s.erase(0, f+1);
        down = atoi(s.c_str());
      }
    };
};

/// Gets the current system time in milliseconds.
long long int getNowMS(){
  timeval t;
  gettimeofday(&t, 0);
  return t.tv_sec * 1000 + t.tv_usec/1000;
}//getNowMS

int main(int argc, char** argv){
  Util::Config conf(argv[0], PACKAGE_VERSION);
  conf.addOption("filename", JSON::fromString("{\"arg_num\":1, \"help\":\"Name of the file to write to stdout.\"}"));
  conf.parseArgs(argc, argv);
  conf.activate();
  int playing = 0;

  DTSC::File source = DTSC::File(conf.getString("filename"));
  Socket::Connection in_out = Socket::Connection(fileno(stdout), fileno(stdin));
  std::string meta_str = source.getHeader();
  JSON::Value pausemark;
  pausemark["datatype"] = "pause_marker";
  pausemark["time"] = (long long int)0;

  Socket::Connection StatsSocket = Socket::Connection("/tmp/mist/statistics", true);
  int lasttime = time(0);

  //send the header
  {
    in_out.Send("DTSC");
    unsigned int size = htonl(meta_str.size());
    in_out.Send((char*)&size, 4);
    in_out.Send(meta_str);
  }

  JSON::Value meta = JSON::fromDTMI(meta_str);
  JSON::Value last_pack;

  bool meta_sent = false;
  long long now, timeDiff = 0, lastTime = 0;
  Stats sts;

  while (in_out.connected() && std::cin.good() && std::cout.good() && (time(0) - lasttime < 60)){
    if (in_out.spool()){
      while (in_out.Received().find('\n') != std::string::npos){
        std::string cmd = in_out.Received().substr(0, in_out.Received().find('\n'));
        in_out.Received().erase(0, in_out.Received().find('\n')+1);
        if (cmd != ""){
          switch (cmd[0]){
            case 'P':{ //Push
              #if DEBUG >= 4
              std::cerr << "Received push - ignoring (" << cmd << ")" << std::endl;
              #endif
              in_out.close();//pushing to VoD makes no sense
            } break;
            case 'S':{ //Stats
              if (!StatsSocket.connected()){
                StatsSocket = Socket::Connection("/tmp/mist/statistics", true);
              }
              if (StatsSocket.connected()){
                sts = Stats(cmd.substr(2));
                JSON::Value json_sts;
                json_sts["vod"]["down"] = (long long int)sts.down;
                json_sts["vod"]["up"] = (long long int)sts.up;
                json_sts["vod"]["time"] = (long long int)sts.conntime;
                json_sts["vod"]["host"] = sts.host;
                json_sts["vod"]["connector"] = sts.connector;
                json_sts["vod"]["filename"] = conf.getString("filename");
                json_sts["vod"]["now"] = (long long int)time(0);
                json_sts["vod"]["start"] = (long long int)(time(0) - sts.conntime);
                if (!meta_sent){
                  json_sts["vod"]["meta"] = meta;
                  meta_sent = true;
                }
                StatsSocket.Send(json_sts.toString().c_str());
                StatsSocket.Send("\n\n");
                StatsSocket.flush();
              }
            } break;
            case 's':{ //second-seek
              #if DEBUG >= 4
              std::cerr << "Received ms-seek (" << cmd << ")" << std::endl;
              #endif
              int ms = JSON::Value(cmd.substr(2)).asInt();
              bool ret = source.seek_time(ms);
              #if DEBUG >= 4
              std::cerr << "Second-seek completed (time " << ms << "ms) " << ret << std::endl;
              #endif
            } break;
            case 'f':{ //frame-seek
              #if DEBUG >= 4
              std::cerr << "Received frame-seek (" << cmd << ")" << std::endl;
              #endif
              bool ret = source.seek_frame(JSON::Value(cmd.substr(2)).asInt());
              #if DEBUG >= 4
              std::cerr << "Frame-seek completed " << ret << std::endl;
              #endif
            } break;
            case 'p':{ //play
              #if DEBUG >= 4
              std::cerr << "Received play" << std::endl;
              #endif
              playing = -1;
              in_out.setBlocking(false);
            } break;
            case 'o':{ //once-play
              #if DEBUG >= 4
              std::cerr << "Received once-play" << std::endl;
              #endif
              if (playing <= 0){playing = 1;}
              ++playing;
              in_out.setBlocking(false);
            } break;
            case 'q':{ //quit-playing
              #if DEBUG >= 4
              std::cerr << "Received quit-playing" << std::endl;
              #endif
              playing = 0;
              in_out.setBlocking(true);
            } break;
          }
        }
      }
    }
    if (playing != 0){
      now = getNowMS();
      if (playing > 0 || now - timeDiff >= lastTime || lastTime - (now - timeDiff) > 15000) {
        source.seekNext();
        lastTime = source.getJSON()["time"].asInt();
        if ((now - timeDiff - lastTime) > 5000 || (now - timeDiff - lastTime < -5000)){
          timeDiff = now - lastTime;
        }
        if (source.getJSON().isMember("keyframe")){
          if (playing > 0){--playing;}
          if (playing == 0){
            #if DEBUG >= 4
            std::cerr << "Sending pause_marker" << std::endl;
            #endif
            pausemark["time"] = (long long int)now;
            pausemark.toPacked();
            in_out.Send(pausemark.toNetPacked());
            in_out.flush();
            in_out.setBlocking(true);
          }
        }
        if (playing != 0){
          lasttime = time(0);
          //insert proper header for this type of data
          in_out.Send("DTPD");
          //insert the packet length
          unsigned int size = htonl(source.getPacket().size());
          in_out.Send((char*)&size, 4);
          in_out.Send(source.getPacket());
        }
      } else {
        usleep(std::min(10000LL, lastTime - (now - timeDiff)) * 1000);
      }
    }
    usleep(10000);//sleep 10ms
  }

  StatsSocket.close();
  in_out.close();
  return 0;
}
<|endoftext|>