<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/application/common/db_store_constants.h"
#include "base/strings/stringprintf.h"

namespace xwalk {
namespace db_store_constants {

const char kAppTableName[] = "applications";
const char kAppID[] = "id";
const char kAppManifest[] = "manifest";
const char kAppPath[] = "path";
const char kAppInstallTime[] = "install_time";

const char kEventTableName[] = "registered_events";
const char kEventAppID[] = "id";
const char kEventsName[] = "event_names";

const char kCreateAppTableOp[] =
    "CREATE TABLE applications ("
    "id TEXT NOT NULL UNIQUE PRIMARY KEY,"
    "manifest TEXT NOT NULL,"
    "path TEXT NOT NULL,"
    "install_time REAL)";

const char kCreateEventTableOp[] =
    "CREATE TABLE registered_events ("
    "id TEXT NOT NULL,"
    "event_names TEXT NOT NULL,"
    "PRIMARY KEY (id),"
    "FOREIGN KEY (id) REFERENCES applications(id)"
    "ON DELETE CASCADE)";

const char kGetAllRowsFromAppEventTableOp[] =
    "SELECT applications.id, manifest, path, install_time, event_names "
    "FROM applications "
    "LEFT JOIN registered_events "
    "ON applications.id = registered_events.id";

const char kSetApplicationWithBindOp[] =
    "INSERT INTO applications (manifest, path, install_time, id) "
    "VALUES (?,?,?,?)";

const char kUpdateApplicationWithBindOp[] =
    "UPDATE applications SET manifest = ?, path = ?,"
    "install_time = ? WHERE id = ?";

const char kDeleteApplicationWithBindOp[] =
    "DELETE FROM applications WHERE id = ?";

const char kSetManifestWithBindOp[] =
    "UPDATE applications SET manifest = ? WHERE id = ?";

const char kSetInstallTimeWithBindOp[] =
    "UPDATE applications SET install_time = ? WHERE id = ?";

const char kSetApplicationPathWithBindOp[] =
    "UPDATE applications SET path = ? WHERE id = ?";

const char kInsertEventsWithBindOp[] =
    "INSERT INTO registered_events (event_names, id) "
    "VALUES(?,?)";

const char kUpdateEventsWithBindOp[] =
    "UPDATE registered_events SET event_names = ? WHERE id = ?";

const char kDeleteEventsWithBindOp[] =
    "DELETE FROM registered_events WHERE id = ?";

}  // namespace db_store_constants
}  // namespace xwalk
<commit_msg>[Runtime] Polish a Sqlite table selection statement.<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/application/common/db_store_constants.h"
#include "base/strings/stringprintf.h"

namespace xwalk {
namespace db_store_constants {

const char kAppTableName[] = "applications";
const char kAppID[] = "id";
const char kAppManifest[] = "manifest";
const char kAppPath[] = "path";
const char kAppInstallTime[] = "install_time";

const char kEventTableName[] = "registered_events";
const char kEventAppID[] = "id";
const char kEventsName[] = "event_names";

const char kCreateAppTableOp[] =
    "CREATE TABLE applications ("
    "id TEXT NOT NULL UNIQUE PRIMARY KEY,"
    "manifest TEXT NOT NULL,"
    "path TEXT NOT NULL,"
    "install_time REAL)";

const char kCreateEventTableOp[] =
    "CREATE TABLE registered_events ("
    "id TEXT NOT NULL,"
    "event_names TEXT NOT NULL,"
    "PRIMARY KEY (id),"
    "FOREIGN KEY (id) REFERENCES applications(id)"
    "ON DELETE CASCADE)";

const char kGetAllRowsFromAppEventTableOp[] =
    "SELECT A.id, A.manifest, A.path, A.install_time, B.event_names "
    "FROM applications as A "
    "LEFT JOIN registered_events as B "
    "ON A.id = B.id";

const char kSetApplicationWithBindOp[] =
    "INSERT INTO applications (manifest, path, install_time, id) "
    "VALUES (?,?,?,?)";

const char kUpdateApplicationWithBindOp[] =
    "UPDATE applications SET manifest = ?, path = ?,"
    "install_time = ? WHERE id = ?";

const char kDeleteApplicationWithBindOp[] =
    "DELETE FROM applications WHERE id = ?";

const char kSetManifestWithBindOp[] =
    "UPDATE applications SET manifest = ? WHERE id = ?";

const char kSetInstallTimeWithBindOp[] =
    "UPDATE applications SET install_time = ? WHERE id = ?";

const char kSetApplicationPathWithBindOp[] =
    "UPDATE applications SET path = ? WHERE id = ?";

const char kInsertEventsWithBindOp[] =
    "INSERT INTO registered_events (event_names, id) "
    "VALUES(?,?)";

const char kUpdateEventsWithBindOp[] =
    "UPDATE registered_events SET event_names = ? WHERE id = ?";

const char kDeleteEventsWithBindOp[] =
    "DELETE FROM registered_events WHERE id = ?";

}  // namespace db_store_constants
}  // namespace xwalk
<|endoftext|>


<commit_before><commit_msg>Fixed triggers only prefix-matching on stream names<commit_after><|endoftext|>


<commit_before>#include <algorithm>
#include <cstdio>
#include <cstring>
#include <map>

#include "hash.hpp"
#include "pg.hpp"
#include "slice.hpp"

auto importHeightMap (const std::string& fileName) {
	std::map<hash256_t, uint32_t> map;

	auto file = fopen(fileName.c_str(), "r");
	if (file == nullptr) return map;

	uint32_t height = 0;
	do {
		hash256_t hash;
		const auto read = fread(&hash[0], 32, 1, file);

		// EOF?
		if (read == 0) break;

		map[hash] = height;
		++height;
	} while (true);

	return map;
}

int main (int argc, char** argv) {
	assert(argc >= 2);
	const auto headersFileName = std::string(argv[1]);
	const auto chainHeightMap = importHeightMap(headersFileName);
	assert(!chainHeightMap.empty());

	fwrite(PG_BINARY_HEADER, sizeof(PG_BINARY_HEADER), 1, stdout);

	while (true) {
		uint8_t buffer[84];
		const auto read = fread(buffer, sizeof(buffer), 1, stdin);

		// EOF?
		if (read == 0) break;

		hash256_t block_hash;
		memcpy(&block_hash[0], &buffer[0], 32);

		const auto heightPair = chainHeightMap.find(block_hash);
		if (heightPair == chainHeightMap.end()) continue;

		std::reverse(&buffer[32], &buffer[64]); // TX_HASH -> TX_ID

		uint8_t pbuffer[70];
		auto pslice = Slice(pbuffer, pbuffer + sizeof(pbuffer));

		// postgres COPY tuple
		pslice.write<int16_t, true>(3);

		pslice.write<int32_t, true>(20);
		memcpy(pslice.begin, buffer + 64, 20);
		pslice.popFrontN(20);

		pslice.write<int32_t, true>(32);
		memcpy(pslice.begin, buffer + 32, 32);
		pslice.popFrontN(32);

		pslice.write<int32_t, true>(4);
		pslice.write<int32_t>(heightPair->second);

		fwrite(pbuffer, sizeof(pbuffer), 1, stdout);
	}

	fwrite(PG_BINARY_TAIL, sizeof(PG_BINARY_TAIL), 1, stdout);

	return 0;
}
<commit_msg>tools: open in binary mode<commit_after>#include <algorithm>
#include <cstdio>
#include <cstring>
#include <map>

#include "hash.hpp"
#include "pg.hpp"
#include "slice.hpp"

auto importHeightMap (const std::string& fileName) {
	std::map<hash256_t, uint32_t> map;

	auto file = fopen(fileName.c_str(), "rb");
	if (file == nullptr) return map;

	uint32_t height = 0;
	do {
		hash256_t hash;
		const auto read = fread(&hash[0], 32, 1, file);

		// EOF?
		if (read == 0) break;

		map[hash] = height;
		++height;
	} while (true);

	return map;
}

int main (int argc, char** argv) {
	assert(argc >= 2);
	const auto headersFileName = std::string(argv[1]);
	const auto chainHeightMap = importHeightMap(headersFileName);
	assert(!chainHeightMap.empty());

	fwrite(PG_BINARY_HEADER, sizeof(PG_BINARY_HEADER), 1, stdout);

	while (true) {
		uint8_t buffer[84];
		const auto read = fread(buffer, sizeof(buffer), 1, stdin);

		// EOF?
		if (read == 0) break;

		hash256_t block_hash;
		memcpy(&block_hash[0], &buffer[0], 32);

		const auto heightPair = chainHeightMap.find(block_hash);
		if (heightPair == chainHeightMap.end()) continue;

		std::reverse(&buffer[32], &buffer[64]); // TX_HASH -> TX_ID

		uint8_t pbuffer[70];
		auto pslice = Slice(pbuffer, pbuffer + sizeof(pbuffer));

		// postgres COPY tuple
		pslice.write<int16_t, true>(3);

		pslice.write<int32_t, true>(20);
		memcpy(pslice.begin, buffer + 64, 20);
		pslice.popFrontN(20);

		pslice.write<int32_t, true>(32);
		memcpy(pslice.begin, buffer + 32, 32);
		pslice.popFrontN(32);

		pslice.write<int32_t, true>(4);
		pslice.write<int32_t>(heightPair->second);

		fwrite(pbuffer, sizeof(pbuffer), 1, stdout);
	}

	fwrite(PG_BINARY_TAIL, sizeof(PG_BINARY_TAIL), 1, stdout);

	return 0;
}
<|endoftext|>


<commit_before><commit_msg>table: new typemultiline edit<commit_after><|endoftext|>


<commit_before>#pragma once

#include <cstdint>
#include <boost/any.hpp>
#include <string>
#include <unordered_map>
#include <fstream>
#include <iostream>

#define MAGIC_VALUE 0x07564426

namespace SteamVdfParse
{
uint32_t read32_le(std::istream& stream)
{
    return static_cast<uint32_t>((stream.get()) | (stream.get() << 8) | (stream.get() << 16) |
                                 (stream.get() << 24));
}

uint64_t read64_le(std::istream& stream)
{
    return static_cast<uint64_t>(
        (stream.get()) | (stream.get() << 8) | (stream.get() << 16) | (stream.get() << 24) |
        ((uint64_t)stream.get() << 32) | ((uint64_t)stream.get() << 40) |
        ((uint64_t)stream.get() << 48) | ((uint64_t)stream.get() << 56));
}

std::string readString(std::istream& stream)
{
    std::string str;
    std::getline(stream, str, '\0');
    return str;
}

struct Section
{
    std::string name;
    std::unordered_map<std::string, boost::any> kv;

    template <typename Type>
    Type get(std::string key)
    {
        try
        {
            return boost::any_cast<Type>(kv[key]);
        }
        catch (const boost::bad_any_cast& e)
        {
            std::cerr << "Cannot cast value at " << key
                      << " to the wanted type." << std::endl;
            throw e;
        }
    }
};

struct Game
{
    uint32_t appID;
    uint32_t size;
    uint32_t infoState;  // 1-unavailable, 2-available
    uint32_t lastUpdated;
    uint64_t accessToken;
    uint8_t sha[20];
    uint32_t changeNumber;
    std::unordered_map<std::string, Section> sections;
};

Section parseSection(std::istream& input, bool root, std::string name)
{
    Section section;

    section.name = name;

    while (true)
    {
        uint8_t valueType = input.get();

        if (valueType == 0x08)
        {
            if (root)
            {
                input.get();
            }
            break;
        }

        std::string key = readString(input);

        boost::any value;

        switch (valueType)
        {
            case 0x00:  // None
            {
                value = parseSection(input, false, key);
                break;
            }
            case 0x01:  // string
            {
                value = readString(input);
                break;
            }
            case 0x02:  // int
            {
                value = read32_le(input);
                break;
            }
            case 0x03:  // float
            {
                std::cerr << "Floats are not implemented." << std::endl;
                break;
            }
            case 0x04:  // ptr
            {
                std::cerr << "Pointers are not implemented." << std::endl;
                break;
            }
            case 0x05:  // Wide string
            {
                std::cerr << "Wide strings are not implemented." << std::endl;
                break;
            }
            case 0x06:  // Colour
            {
                std::cerr << "Colours are not implemented." << std::endl;
                break;
            }
            case 0x07:  // 64 bit int
            {
                value = read64_le(input);
                break;
            }
            default:
                std::cerr << "Unknown type: " << (int)valueType << std::endl;
        }

        section.kv.insert(std::make_pair(key, value));
    }

    return section;
}

Game parseGame(std::istream& input)
{
    Game game;
    game.appID = read32_le(input);
    if (game.appID == 0)
    {
        return game;
    }
    std::cout << "Parsing game id: " << game.appID << std::endl;
    game.size = read32_le(input);
    game.infoState = read32_le(input);
    game.lastUpdated = read32_le(input);
    game.accessToken = read64_le(input);

    for (int i = 0; i < 20; i++)
    {
        game.sha[i] = input.get();
    }

    game.changeNumber = read32_le(input);

    while (true)
    {
        uint8_t sectionID = input.get();
        if (sectionID == 0x00)
        {
            break;
        }

        input.get();  // read the 00 before name

        std::string name = readString(input);
        Section section = parseSection(input, true, name);
        game.sections.insert(std::make_pair(name, section));
    }

    return game;
}

std::unordered_map<int, Game> parseVdf(std::string location)
{
    std::ifstream input(location, std::ifstream::binary);

    uint32_t magic = read32_le(input);
    uint32_t universe = read32_le(input);  // Parse this later

    std::unordered_map<int, Game> games;

    if (magic != MAGIC_VALUE)
    {
        std::cerr << "Invalid magic value!" << std::endl;
        return games;
    }

    while (!input.eof())
    {
        Game game = parseGame(input);
        if (game.appID == 0)
        {
            break;
        }
        games.insert(std::make_pair(game.appID, game));
    }

    return games;
}
}
<commit_msg>Remove spam printing<commit_after>#pragma once

#include <cstdint>
#include <boost/any.hpp>
#include <string>
#include <unordered_map>
#include <fstream>
#include <iostream>

#define MAGIC_VALUE 0x07564426

namespace SteamVdfParse
{
uint32_t read32_le(std::istream& stream)
{
    return static_cast<uint32_t>((stream.get()) | (stream.get() << 8) | (stream.get() << 16) |
                                 (stream.get() << 24));
}

uint64_t read64_le(std::istream& stream)
{
    return static_cast<uint64_t>(
        (stream.get()) | (stream.get() << 8) | (stream.get() << 16) | (stream.get() << 24) |
        ((uint64_t)stream.get() << 32) | ((uint64_t)stream.get() << 40) |
        ((uint64_t)stream.get() << 48) | ((uint64_t)stream.get() << 56));
}

std::string readString(std::istream& stream)
{
    std::string str;
    std::getline(stream, str, '\0');
    return str;
}

struct Section
{
    std::string name;
    std::unordered_map<std::string, boost::any> kv;

    template <typename Type>
    Type get(std::string key)
    {
        try
        {
            return boost::any_cast<Type>(kv[key]);
        }
        catch (const boost::bad_any_cast& e)
        {
            std::cerr << "Cannot cast value at " << key
                      << " to the wanted type." << std::endl;
            throw e;
        }
    }
};

struct Game
{
    uint32_t appID;
    uint32_t size;
    uint32_t infoState;  // 1-unavailable, 2-available
    uint32_t lastUpdated;
    uint64_t accessToken;
    uint8_t sha[20];
    uint32_t changeNumber;
    std::unordered_map<std::string, Section> sections;
};

Section parseSection(std::istream& input, bool root, std::string name)
{
    Section section;

    section.name = name;

    while (true)
    {
        uint8_t valueType = input.get();

        if (valueType == 0x08)
        {
            if (root)
            {
                input.get();
            }
            break;
        }

        std::string key = readString(input);

        boost::any value;

        switch (valueType)
        {
            case 0x00:  // None
            {
                value = parseSection(input, false, key);
                break;
            }
            case 0x01:  // string
            {
                value = readString(input);
                break;
            }
            case 0x02:  // int
            {
                value = read32_le(input);
                break;
            }
            case 0x03:  // float
            {
                std::cerr << "Floats are not implemented." << std::endl;
                break;
            }
            case 0x04:  // ptr
            {
                std::cerr << "Pointers are not implemented." << std::endl;
                break;
            }
            case 0x05:  // Wide string
            {
                std::cerr << "Wide strings are not implemented." << std::endl;
                break;
            }
            case 0x06:  // Colour
            {
                std::cerr << "Colours are not implemented." << std::endl;
                break;
            }
            case 0x07:  // 64 bit int
            {
                value = read64_le(input);
                break;
            }
            default:
                std::cerr << "Unknown type: " << (int)valueType << std::endl;
        }

        section.kv.insert(std::make_pair(key, value));
    }

    return section;
}

Game parseGame(std::istream& input)
{
    Game game;
    game.appID = read32_le(input);
    if (game.appID == 0)
    {
        return game;
    }

    game.size = read32_le(input);
    game.infoState = read32_le(input);
    game.lastUpdated = read32_le(input);
    game.accessToken = read64_le(input);

    for (int i = 0; i < 20; i++)
    {
        game.sha[i] = input.get();
    }

    game.changeNumber = read32_le(input);

    while (true)
    {
        uint8_t sectionID = input.get();
        if (sectionID == 0x00)
        {
            break;
        }

        input.get();  // read the 00 before name

        std::string name = readString(input);
        Section section = parseSection(input, true, name);
        game.sections.insert(std::make_pair(name, section));
    }

    return game;
}

std::unordered_map<int, Game> parseVdf(std::string location)
{
    std::ifstream input(location, std::ifstream::binary);

    uint32_t magic = read32_le(input);
    uint32_t universe = read32_le(input);  // Parse this later

    std::unordered_map<int, Game> games;

    if (magic != MAGIC_VALUE)
    {
        std::cerr << "Invalid magic value!" << std::endl;
        return games;
    }

    while (!input.eof())
    {
        Game game = parseGame(input);
        if (game.appID == 0)
        {
            break;
        }
        games.insert(std::make_pair(game.appID, game));
    }

    return games;
}
}
<|endoftext|>


<commit_before>/*
 * SPDX-FileCopyrightText: 2010-2018 CSSlayer <wengxt@gmail.com>
 *
 * SPDX-License-Identifier: LGPL-2.1-or-later
 *
 */

#include <codecvt>
#include <cstring>
#if defined(__linux__) || defined(__GLIBC__)
#include <endian.h>
#else
#include <sys/endian.h>
#endif
#include <fcitx-utils/fs.h>
#include <fcitx-utils/log.h>
#include <fcitx-utils/stringutils.h>
#include <fcitx-utils/unixfd.h>
#include <fcntl.h>
#include <fstream>
#include <getopt.h>
#include <locale>
#include <unistd.h>

using namespace fcitx;

#define HEADER_SIZE 12
#define DELTBL_SIZE 10
#define BUFLEN 0x1000

#define DESC_START 0x130
#define DESC_LENGTH (0x338 - 0x130)

#define LDESC_LENGTH (0x540 - 0x338)
#define NEXT_LENGTH (0x1540 - 0x540)

#define PINYIN_SIZE 4

template <typename T>
void readOrAbort(const UnixFD &fd, T *value, int n,
                 const char *error = nullptr) {
    if (fs::safeRead(fd.fd(), value, n * sizeof(T)) !=
        static_cast<int>(n * sizeof(T))) {
        if (error) {
            FCITX_FATAL() << error;
        } else {
            exit(0);
        }
    }
}

template <typename T>
void readOrAbort(const UnixFD &fd, T *value, const char *error = nullptr) {
    return readOrAbort(fd, value, 1, error);
}

void readUInt16(const UnixFD &fd, uint16_t *value,
                const char *error = nullptr) {
    readOrAbort(fd, value, error);
    *value = le16toh(*value);
}

std::string unicodeToUTF8(const char16_t *value, size_t size) {
    return std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>{}
        .to_bytes(value, value + size);
}

std::string unicodeToUTF8(const char *value, size_t size) {
    FCITX_ASSERT(size % 2 == 0) << "Invalid size of string";
    const auto *ustr = reinterpret_cast<const uint16_t *>(value);
    std::u16string str;
    str.reserve(size / 2);
    for (size_t i = 0; i < size / 2; i++) {
        // either le or be will be 0
        if (ustr[i] == 0) {
            break;
        }
        str.push_back(le16toh(ustr[i]));
    }

    return unicodeToUTF8(str.data(), str.size());
}

static const char header_str[HEADER_SIZE] = {'\x40', '\x15', '\0',   '\0',
                                             '\x44', '\x43', '\x53', '\x01',
                                             '\x01', '\0',   '\0',   '\0'};
static const char pinyin_str[PINYIN_SIZE] = {'\x9d', '\x01', '\0', '\0'};
static const char deltbl_str[HEADER_SIZE] = {
    '\x45', '\0', '\x4c', '\0', '\x54', '\0', '\x42', '\0', '\x4c', '\0'};

static void usage() {
    puts("scel2org - Convert .scel file to libime compatible file (SEE NOTES "
         "BELOW)\n"
         "\n"
         "  usage: scel2org [OPTION] [scel file]\n"
         "\n"
         "  -o <file>  specify the output file, if not specified, the output "
         "will\n"
         "             be stdout.\n"
         "  -h         display this help.\n"
         "\n"
         "NOTES:\n"
         "   Always check the produced output for errors.\n");
    exit(1);
}

int main(int argc, char **argv) {
    int c;
    const char *outputFile = nullptr;
    bool printDel = false;

    while ((c = getopt(argc, argv, "o:hd")) != -1) {
        switch (c) {
        case 'o':
            outputFile = optarg;
            break;
        case 'd':
            printDel = true;
            break;
        case 'h':
        default:
            usage();
            break;
        }
    }

    std::ofstream fout;
    std::ostream *out;
    if (!outputFile || strcmp(outputFile, "-") == 0) {
        out = &std::cout;
    } else {
        fout.open(outputFile, std::ios::out | std::ios::binary);
        out = &fout;
    }

    if (optind >= argc) {
        usage();
        return 1;
    }

    UnixFD fd = UnixFD::own(open(argv[optind], O_RDONLY));
    if (!fd.isValid()) {
        FCITX_ERROR() << "Cannot open file: " << argv[optind];
        return 1;
    }

    char headerBuf[HEADER_SIZE];
    readOrAbort(fd, headerBuf, HEADER_SIZE, "Failed to read header");
    FCITX_ASSERT(memcmp(headerBuf, header_str, HEADER_SIZE) == 0)
        << " format error.";

    FCITX_ASSERT(lseek(fd.fd(), DESC_START, SEEK_SET) !=
                 static_cast<off_t>(-1));

    char descBuf[DESC_LENGTH];
    readOrAbort(fd, descBuf, DESC_LENGTH, "Failed to read description");
    std::cerr << "DESC:" << unicodeToUTF8(descBuf, DESC_LENGTH) << std::endl;

    char ldescBuf[LDESC_LENGTH];
    readOrAbort(fd, ldescBuf, LDESC_LENGTH, "Failed to read long description");
    std::cerr << "LDESC:" << unicodeToUTF8(ldescBuf, LDESC_LENGTH) << std::endl;

    char nextBuf[NEXT_LENGTH];
    readOrAbort(fd, nextBuf, NEXT_LENGTH, "Failed to read next description");
    std::cerr << "NEXT:" << unicodeToUTF8(nextBuf, NEXT_LENGTH) << std::endl;

    char pyBuf[PINYIN_SIZE];
    readOrAbort(fd, pyBuf, PINYIN_SIZE, "Failed to read py");
    FCITX_ASSERT(memcmp(pyBuf, pinyin_str, PINYIN_SIZE) == 0);

    std::vector<std::string> pys;

    while (true) {
        uint16_t index;
        uint16_t count;
        readUInt16(fd, &index, "failed to read index");
        readUInt16(fd, &count, "failed to read pinyin count");

        std::vector<char> buf;
        buf.resize(count);

        readOrAbort(fd, buf.data(), count, "Failed to read py");

        std::string py = unicodeToUTF8(buf.data(), buf.size());

        // Replace ue with ve
        if (py == "lue" || py == "nue") {
            py[py.size() - 2] = 'v';
        }
        pys.push_back(py);

        if (py == "zuo") {
            break;
        }
    }

    while (true) {
        uint16_t symcount;
        uint16_t count;
        uint16_t wordcount;
        readUInt16(fd, &symcount);

        // Just in case we read a invalid value.
        if (symcount > 128) {
            FCITX_ERROR() << "Error at offset: " << lseek(fd.fd(), 0, SEEK_CUR);
            break;
        }

        readUInt16(fd, &count, "Failed to read count");

        wordcount = count / 2;
        std::vector<uint16_t> pyindex;
        pyindex.resize(wordcount);

        for (uint16_t i = 0; i < wordcount; i++) {
            readUInt16(fd, &pyindex[i], "Failed to read pyindex");
            if (pyindex[i] >= pys.size()) {
                FCITX_FATAL() << "Invalid pinyin index";
            }
        }

        for (uint16_t s = 0; s < symcount; s++) {
            std::vector<char> buf;
            readUInt16(fd, &count, "Failed to read count");
            buf.resize(count);
            readOrAbort(fd, buf.data(), count, "Failed to read text");
            std::string bufout = unicodeToUTF8(buf.data(), buf.size());

            *out << bufout << "\t";
            *out << pys[pyindex[0]];
            for (auto i = 1; i < wordcount; i++) {
                *out << '\'' << pys[pyindex[i]];
            }

            *out << "\t0" << std::endl;

            readUInt16(fd, &count, "failed to read count");
            buf.resize(count);
            readOrAbort(fd, buf.data(), buf.size(), "failed to read buf");
        }
    }

    char delTblBuf[DELTBL_SIZE];
    if (fs::safeRead(fd.fd(), delTblBuf, DELTBL_SIZE) != DELTBL_SIZE ||
        memcmp(delTblBuf, deltbl_str, DELTBL_SIZE) != 0) {
        return 0;
    }

    if (!printDel) {
        return 0;
    }

    uint16_t delTblCount;
    readUInt16(fd, &delTblCount);
    for (int i = 0; i < delTblCount; i++) {
        uint16_t count;
        readUInt16(fd, &count);
        count *= 2;
        std::vector<char> buf;
        buf.resize(count);
        readOrAbort(fd, buf.data(), count, "Failed to read text");
        std::string bufout = unicodeToUTF8(buf.data(), buf.size());
        std::cerr << "DEL:" << bufout << std::endl;
    }

    return 0;
}
<commit_msg>Fix del tbl handling.<commit_after>/*
 * SPDX-FileCopyrightText: 2010-2018 CSSlayer <wengxt@gmail.com>
 *
 * SPDX-License-Identifier: LGPL-2.1-or-later
 *
 */

#include <codecvt>
#include <cstring>
#if defined(__linux__) || defined(__GLIBC__)
#include <endian.h>
#else
#include <sys/endian.h>
#endif
#include <fcitx-utils/fs.h>
#include <fcitx-utils/log.h>
#include <fcitx-utils/stringutils.h>
#include <fcitx-utils/unixfd.h>
#include <fcntl.h>
#include <fstream>
#include <getopt.h>
#include <locale>
#include <unistd.h>

using namespace fcitx;

#define HEADER_SIZE 12
#define DELTBL_SIZE 8
#define BUFLEN 0x1000

#define DESC_START 0x130
#define DESC_LENGTH (0x338 - 0x130)

#define LDESC_LENGTH (0x540 - 0x338)
#define NEXT_LENGTH (0x1540 - 0x540)

#define PINYIN_SIZE 4

template <typename T>
void readOrAbort(const UnixFD &fd, T *value, int n,
                 const char *error = nullptr) {
    if (fs::safeRead(fd.fd(), value, n * sizeof(T)) !=
        static_cast<int>(n * sizeof(T))) {
        if (error) {
            FCITX_FATAL() << error;
        } else {
            exit(0);
        }
    }
}

template <typename T>
void readOrAbort(const UnixFD &fd, T *value, const char *error = nullptr) {
    return readOrAbort(fd, value, 1, error);
}

void readUInt16(const UnixFD &fd, uint16_t *value,
                const char *error = nullptr) {
    readOrAbort(fd, value, error);
    *value = le16toh(*value);
}

std::string unicodeToUTF8(const char16_t *value, size_t size) {
    return std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>{}
        .to_bytes(value, value + size);
}

std::string unicodeToUTF8(const char *value, size_t size) {
    FCITX_ASSERT(size % 2 == 0) << "Invalid size of string";
    const auto *ustr = reinterpret_cast<const uint16_t *>(value);
    std::u16string str;
    str.reserve(size / 2);
    for (size_t i = 0; i < size / 2; i++) {
        // either le or be will be 0
        if (ustr[i] == 0) {
            break;
        }
        str.push_back(le16toh(ustr[i]));
    }

    return unicodeToUTF8(str.data(), str.size());
}

static const char header_str[HEADER_SIZE] = {'\x40', '\x15', '\0',   '\0',
                                             '\x44', '\x43', '\x53', '\x01',
                                             '\x01', '\0',   '\0',   '\0'};
static const char pinyin_str[PINYIN_SIZE] = {'\x9d', '\x01', '\0', '\0'};
static const char deltbl_str[DELTBL_SIZE] = {'\x4c', '\0', '\x54', '\0',
                                             '\x42', '\0', '\x4c', '\0'};

static void usage() {
    puts("scel2org - Convert .scel file to libime compatible file (SEE NOTES "
         "BELOW)\n"
         "\n"
         "  usage: scel2org [OPTION] [scel file]\n"
         "\n"
         "  -o <file>  specify the output file, if not specified, the output "
         "will\n"
         "             be stdout.\n"
         "  -h         display this help.\n"
         "\n"
         "NOTES:\n"
         "   Always check the produced output for errors.\n");
    exit(1);
}

int main(int argc, char **argv) {
    int c;
    const char *outputFile = nullptr;
    bool printDel = false;

    while ((c = getopt(argc, argv, "o:hd")) != -1) {
        switch (c) {
        case 'o':
            outputFile = optarg;
            break;
        case 'd':
            printDel = true;
            break;
        case 'h':
        default:
            usage();
            break;
        }
    }

    std::ofstream fout;
    std::ostream *out;
    if (!outputFile || strcmp(outputFile, "-") == 0) {
        out = &std::cout;
    } else {
        fout.open(outputFile, std::ios::out | std::ios::binary);
        out = &fout;
    }

    if (optind >= argc) {
        usage();
        return 1;
    }

    UnixFD fd = UnixFD::own(open(argv[optind], O_RDONLY));
    if (!fd.isValid()) {
        FCITX_ERROR() << "Cannot open file: " << argv[optind];
        return 1;
    }

    char headerBuf[HEADER_SIZE];
    readOrAbort(fd, headerBuf, HEADER_SIZE, "Failed to read header");
    FCITX_ASSERT(memcmp(headerBuf, header_str, HEADER_SIZE) == 0)
        << " format error.";

    FCITX_ASSERT(lseek(fd.fd(), DESC_START, SEEK_SET) !=
                 static_cast<off_t>(-1));

    char descBuf[DESC_LENGTH];
    readOrAbort(fd, descBuf, DESC_LENGTH, "Failed to read description");
    std::cerr << "DESC:" << unicodeToUTF8(descBuf, DESC_LENGTH) << std::endl;

    char ldescBuf[LDESC_LENGTH];
    readOrAbort(fd, ldescBuf, LDESC_LENGTH, "Failed to read long description");
    std::cerr << "LDESC:" << unicodeToUTF8(ldescBuf, LDESC_LENGTH) << std::endl;

    char nextBuf[NEXT_LENGTH];
    readOrAbort(fd, nextBuf, NEXT_LENGTH, "Failed to read next description");
    std::cerr << "NEXT:" << unicodeToUTF8(nextBuf, NEXT_LENGTH) << std::endl;

    char pyBuf[PINYIN_SIZE];
    readOrAbort(fd, pyBuf, PINYIN_SIZE, "Failed to read py");
    FCITX_ASSERT(memcmp(pyBuf, pinyin_str, PINYIN_SIZE) == 0);

    std::vector<std::string> pys;

    while (true) {
        uint16_t index;
        uint16_t count;
        readUInt16(fd, &index, "failed to read index");
        readUInt16(fd, &count, "failed to read pinyin count");

        std::vector<char> buf;
        buf.resize(count);

        readOrAbort(fd, buf.data(), count, "Failed to read py");

        std::string py = unicodeToUTF8(buf.data(), buf.size());

        // Replace ue with ve
        if (py == "lue" || py == "nue") {
            py[py.size() - 2] = 'v';
        }
        pys.push_back(py);

        if (py == "zuo") {
            break;
        }
    }

    bool mightBeDelTbl = false;
    while (true) {
        uint16_t symcount;
        uint16_t count;
        uint16_t wordcount;
        readUInt16(fd, &symcount);

        // Just in case we read a invalid value.
        if (symcount > 128) {
            FCITX_ERROR() << "Error at offset: " << lseek(fd.fd(), 0, SEEK_CUR);
            break;
        }

        readUInt16(fd, &count, "Failed to read count");

        if (symcount == 0x44 && count == 0x45) {
            mightBeDelTbl = true;
            break;
        }

        wordcount = count / 2;
        std::vector<uint16_t> pyindex;
        pyindex.resize(wordcount);

        for (uint16_t i = 0; i < wordcount; i++) {
            readUInt16(fd, &pyindex[i], "Failed to read pyindex");
            if (pyindex[i] >= pys.size()) {
                FCITX_FATAL() << "Invalid pinyin index";
            }
        }

        for (uint16_t s = 0; s < symcount; s++) {
            std::vector<char> buf;
            readUInt16(fd, &count, "Failed to read count");
            buf.resize(count);
            readOrAbort(fd, buf.data(), count, "Failed to read text");
            std::string bufout = unicodeToUTF8(buf.data(), buf.size());

            *out << bufout << "\t";
            *out << pys[pyindex[0]];
            for (auto i = 1; i < wordcount; i++) {
                *out << '\'' << pys[pyindex[i]];
            }

            *out << "\t0" << std::endl;

            readUInt16(fd, &count, "failed to read count");
            buf.resize(count);
            readOrAbort(fd, buf.data(), buf.size(), "failed to read buf");
        }
    }

    if (!mightBeDelTbl) {
        return 0;
    }

    char delTblBuf[DELTBL_SIZE];
    if (fs::safeRead(fd.fd(), delTblBuf, DELTBL_SIZE) != DELTBL_SIZE ||
        memcmp(delTblBuf, deltbl_str, DELTBL_SIZE) != 0) {
        return 0;
    }

    if (!printDel) {
        return 0;
    }

    uint16_t delTblCount;
    readUInt16(fd, &delTblCount);
    for (int i = 0; i < delTblCount; i++) {
        uint16_t count;
        readUInt16(fd, &count);
        count *= 2;
        std::vector<char> buf;
        buf.resize(count);
        readOrAbort(fd, buf.data(), count, "Failed to read text");
        std::string bufout = unicodeToUTF8(buf.data(), buf.size());
        std::cerr << "DEL:" << bufout << std::endl;
    }

    return 0;
}
<|endoftext|>


<commit_before>
/**
 * PyOtherSide: Asynchronous Python 3 Bindings for Qt 5
 * Copyright (c) 2011, 2013, 2014, Thomas Perl <m@thp.io>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 **/

#include "qml_python_bridge.h"

#include "qpython.h"
#include "qpython_priv.h"
#include "qpython_worker.h"

#include <QDebug>

#include <QJSEngine>

QPythonPriv *
QPython::priv = NULL;

QPython::QPython(QObject *parent)
    : QObject(parent)
    , worker(new QPythonWorker(this))
    , thread()
    , handlers()
{
    if (priv == NULL) {
        priv = new QPythonPriv;
    }

    worker->moveToThread(&thread);

    QObject::connect(priv, SIGNAL(receive(QVariant)),
                     this, SLOT(receive(QVariant)));

    QObject::connect(this, SIGNAL(process(QString,QVariant,QJSValue)),
                     worker, SLOT(process(QString,QVariant,QJSValue)));
    QObject::connect(worker, SIGNAL(finished(QVariant,QJSValue)),
                     this, SLOT(finished(QVariant,QJSValue)));

    QObject::connect(this, SIGNAL(import(QString,QJSValue)),
                     worker, SLOT(import(QString,QJSValue)));
    QObject::connect(worker, SIGNAL(imported(bool,QJSValue)),
                     this, SLOT(imported(bool,QJSValue)));

    thread.start();
}

QPython::~QPython()
{
    thread.quit();
    thread.wait();

    delete worker;
}

void
QPython::addImportPath(QString path)
{
    priv->enter();
    QByteArray utf8bytes = path.toUtf8();

    PyObject *sys_path = PySys_GetObject((char*)"path");

    PyObject *cwd = PyUnicode_FromString(utf8bytes.constData());
    PyList_Insert(sys_path, 0, cwd);
    Py_DECREF(cwd);
    priv->leave();
}

void
QPython::importModule(QString name, QJSValue callback)
{
    emit import(name, callback);
}

bool
QPython::importModule_sync(QString name)
{
    // Lesson learned: name.toUtf8().constData() doesn't work, as the
    // temporary QByteArray will be destroyed after constData() has
    // returned, so we need to save the toUtf8() result in a local
    // variable that doesn't get destroyed until the function returns.
    QByteArray utf8bytes = name.toUtf8();
    const char *moduleName = utf8bytes.constData();

    priv->enter();
    PyObject *module = PyImport_ImportModule(moduleName);
    if (module == NULL) {
        emit error(QString("Cannot import module: %1 (%2)").arg(name).arg(priv->formatExc()));
        priv->leave();
        return false;
    }

    PyDict_SetItemString(priv->globals, moduleName, module);
    priv->leave();
    return true;
}

void
QPython::receive(QVariant variant)
{
    QVariantList list = variant.toList();
    QString event = list[0].toString();
    if (handlers.contains(event)) {
        QJSValue callback = handlers[event];
        QJSValueList args;
        for (int i=1; i<list.size(); i++) {
            args << callback.engine()->toScriptValue(list[i]);
        }
        QJSValue result = callback.call(args);
        if (result.isError()) {
            // Ideally we would throw the error back to Python (so that the
            // pyotherside.send() method fails, as this is where the call
            // originated). We can't do this, because the pyotherside.send()
            // call is asynchronous (it returns before we call into JS), so do
            // the next best thing and report the error to our error handler in
            // QML instead.
            emit error(QString("pyotherside.send() failed handler: %1")
                    .arg(result.toString()));
        }
    } else {
        // Default action
        emit received(variant);
    }
}

void
QPython::setHandler(QString event, QJSValue callback)
{
    if (!callback.isCallable() || callback.isNull() || callback.isUndefined()) {
        handlers.remove(event);
    } else {
        handlers[event] = callback;
    }
}

QVariant
QPython::evaluate(QString expr)
{
    priv->enter();
    PyObject *o = priv->eval(expr);
    if (o == NULL) {
        emit error(QString("Cannot evaluate '%1' (%2)").arg(expr).arg(priv->formatExc()));
        priv->leave();
        return QVariant();
    }

    QVariant v = convertPyObjectToQVariant(o);
    Py_DECREF(o);
    priv->leave();
    return v;
}

void
QPython::call(QString func, QVariant args, QJSValue callback)
{
    emit process(func, args, callback);
}

QVariant
QPython::call_sync(QString func, QVariant args)
{
    priv->enter();
    PyObject *callable = priv->eval(func);

    if (callable == NULL) {
        emit error(QString("Function not found: '%1' (%2)").arg(func).arg(priv->formatExc()));
        priv->leave();
        return QVariant();
    }

    if (PyCallable_Check(callable)) {
        QVariant v;

        PyObject *argl = convertQVariantToPyObject(args);
        if (!PyList_Check(argl)) {
            Py_DECREF(callable);
            Py_XDECREF(argl);
            emit error(QString("Not a parameter list in call to %1: %2")
                    .arg(func).arg(args.toString()));
            priv->leave();
            return QVariant();
        }

        PyObject *argt = PyList_AsTuple(argl);
        Py_DECREF(argl);
        PyObject *o = PyObject_Call(callable, argt, NULL);
        Py_DECREF(argt);

        if (o == NULL) {
            emit error(QString("Return value of PyObject call is NULL: %1").arg(priv->formatExc()));
        } else {
            v = convertPyObjectToQVariant(o);
            Py_DECREF(o);
        }

        Py_DECREF(callable);
        priv->leave();
        return v;
    }

    emit error(QString("Not a callable: %1").arg(func));
    Py_DECREF(callable);
    priv->leave();
    return QVariant();
}

void
QPython::finished(QVariant result, QJSValue callback)
{
    if (!callback.isNull() && !callback.isUndefined() && callback.isCallable()) {
        QJSValueList args;
        QJSValue v = callback.engine()->toScriptValue(result);
        args << v;
        callback.call(args);
    }
}

void
QPython::imported(bool result, QJSValue callback)
{
    if (!callback.isNull() && !callback.isUndefined() && callback.isCallable()) {
        QJSValueList args;
        QJSValue v = callback.engine()->toScriptValue(QVariant(result));
        args << v;
        callback.call(args);
    }
}
<commit_msg>Set object name on thread<commit_after>
/**
 * PyOtherSide: Asynchronous Python 3 Bindings for Qt 5
 * Copyright (c) 2011, 2013, 2014, Thomas Perl <m@thp.io>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 **/

#include "qml_python_bridge.h"

#include "qpython.h"
#include "qpython_priv.h"
#include "qpython_worker.h"

#include <QDebug>

#include <QJSEngine>

QPythonPriv *
QPython::priv = NULL;

QPython::QPython(QObject *parent)
    : QObject(parent)
    , worker(new QPythonWorker(this))
    , thread()
    , handlers()
{
    if (priv == NULL) {
        priv = new QPythonPriv;
    }

    worker->moveToThread(&thread);

    QObject::connect(priv, SIGNAL(receive(QVariant)),
                     this, SLOT(receive(QVariant)));

    QObject::connect(this, SIGNAL(process(QString,QVariant,QJSValue)),
                     worker, SLOT(process(QString,QVariant,QJSValue)));
    QObject::connect(worker, SIGNAL(finished(QVariant,QJSValue)),
                     this, SLOT(finished(QVariant,QJSValue)));

    QObject::connect(this, SIGNAL(import(QString,QJSValue)),
                     worker, SLOT(import(QString,QJSValue)));
    QObject::connect(worker, SIGNAL(imported(bool,QJSValue)),
                     this, SLOT(imported(bool,QJSValue)));

    thread.setObjectName("QPythonWorker");
    thread.start();
}

QPython::~QPython()
{
    thread.quit();
    thread.wait();

    delete worker;
}

void
QPython::addImportPath(QString path)
{
    priv->enter();
    QByteArray utf8bytes = path.toUtf8();

    PyObject *sys_path = PySys_GetObject((char*)"path");

    PyObject *cwd = PyUnicode_FromString(utf8bytes.constData());
    PyList_Insert(sys_path, 0, cwd);
    Py_DECREF(cwd);
    priv->leave();
}

void
QPython::importModule(QString name, QJSValue callback)
{
    emit import(name, callback);
}

bool
QPython::importModule_sync(QString name)
{
    // Lesson learned: name.toUtf8().constData() doesn't work, as the
    // temporary QByteArray will be destroyed after constData() has
    // returned, so we need to save the toUtf8() result in a local
    // variable that doesn't get destroyed until the function returns.
    QByteArray utf8bytes = name.toUtf8();
    const char *moduleName = utf8bytes.constData();

    priv->enter();
    PyObject *module = PyImport_ImportModule(moduleName);
    if (module == NULL) {
        emit error(QString("Cannot import module: %1 (%2)").arg(name).arg(priv->formatExc()));
        priv->leave();
        return false;
    }

    PyDict_SetItemString(priv->globals, moduleName, module);
    priv->leave();
    return true;
}

void
QPython::receive(QVariant variant)
{
    QVariantList list = variant.toList();
    QString event = list[0].toString();
    if (handlers.contains(event)) {
        QJSValue callback = handlers[event];
        QJSValueList args;
        for (int i=1; i<list.size(); i++) {
            args << callback.engine()->toScriptValue(list[i]);
        }
        QJSValue result = callback.call(args);
        if (result.isError()) {
            // Ideally we would throw the error back to Python (so that the
            // pyotherside.send() method fails, as this is where the call
            // originated). We can't do this, because the pyotherside.send()
            // call is asynchronous (it returns before we call into JS), so do
            // the next best thing and report the error to our error handler in
            // QML instead.
            emit error(QString("pyotherside.send() failed handler: %1")
                    .arg(result.toString()));
        }
    } else {
        // Default action
        emit received(variant);
    }
}

void
QPython::setHandler(QString event, QJSValue callback)
{
    if (!callback.isCallable() || callback.isNull() || callback.isUndefined()) {
        handlers.remove(event);
    } else {
        handlers[event] = callback;
    }
}

QVariant
QPython::evaluate(QString expr)
{
    priv->enter();
    PyObject *o = priv->eval(expr);
    if (o == NULL) {
        emit error(QString("Cannot evaluate '%1' (%2)").arg(expr).arg(priv->formatExc()));
        priv->leave();
        return QVariant();
    }

    QVariant v = convertPyObjectToQVariant(o);
    Py_DECREF(o);
    priv->leave();
    return v;
}

void
QPython::call(QString func, QVariant args, QJSValue callback)
{
    emit process(func, args, callback);
}

QVariant
QPython::call_sync(QString func, QVariant args)
{
    priv->enter();
    PyObject *callable = priv->eval(func);

    if (callable == NULL) {
        emit error(QString("Function not found: '%1' (%2)").arg(func).arg(priv->formatExc()));
        priv->leave();
        return QVariant();
    }

    if (PyCallable_Check(callable)) {
        QVariant v;

        PyObject *argl = convertQVariantToPyObject(args);
        if (!PyList_Check(argl)) {
            Py_DECREF(callable);
            Py_XDECREF(argl);
            emit error(QString("Not a parameter list in call to %1: %2")
                    .arg(func).arg(args.toString()));
            priv->leave();
            return QVariant();
        }

        PyObject *argt = PyList_AsTuple(argl);
        Py_DECREF(argl);
        PyObject *o = PyObject_Call(callable, argt, NULL);
        Py_DECREF(argt);

        if (o == NULL) {
            emit error(QString("Return value of PyObject call is NULL: %1").arg(priv->formatExc()));
        } else {
            v = convertPyObjectToQVariant(o);
            Py_DECREF(o);
        }

        Py_DECREF(callable);
        priv->leave();
        return v;
    }

    emit error(QString("Not a callable: %1").arg(func));
    Py_DECREF(callable);
    priv->leave();
    return QVariant();
}

void
QPython::finished(QVariant result, QJSValue callback)
{
    if (!callback.isNull() && !callback.isUndefined() && callback.isCallable()) {
        QJSValueList args;
        QJSValue v = callback.engine()->toScriptValue(result);
        args << v;
        callback.call(args);
    }
}

void
QPython::imported(bool result, QJSValue callback)
{
    if (!callback.isNull() && !callback.isUndefined() && callback.isCallable()) {
        QJSValueList args;
        QJSValue v = callback.engine()->toScriptValue(QVariant(result));
        args << v;
        callback.call(args);
    }
}
<|endoftext|>


<commit_before>//! @Alan
//!
//! Exercise 10.14:
//! Write a lambda that takes two ints and returns their sum.
//!
//! Exercise 10.15:
//! Write a lambda that captures an int from its enclosing function
//! and takes an int parameter. The lambda should return the sum of
//! the captured int and the int parameter.
//!
//! Exercise 10.16:
//! Write your own version of the biggies function using lambdas.
//!
//! Exercise 10.18:
//! Rewrite biggies to use partition instead of find_if.
//!
//! Exercise 10.19:
//! Rewrite the previous exercise to use stable_partition, which like
//! stable_sort maintains the original element order in the paritioned
//! sequence.
//!

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

//! Exercise 10.14
auto sum = [](const int i1, const int i2 )
{   return i1 + i2;     };
//!                      ^
//! @note There is a ";" here, just like that used after a body of a class.

//! Exercise 10.15
void f()
{
    int i = 0;
    auto sum = [i](const int j)
    {
        return i + j;
    };
}

//! Exercise 10.16
void
wy_elimdups(std::vector<std::string> &vs);
void
wy_biggies(std::vector<std::string> &vs,const std::vector<std::string>::size_type sz);

//! Exercise 10.18
void
wy_biggies_partition(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz);

//! Exercise 10.19
void
wy_biggies_STpartition(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz);
int main()
{

    return 0;
}
void wy_elimdups(std::vector<std::string> &vs)
{
    for (auto element : vs)
        std::cout << element
                  <<" ";
    std::cout <<"\n";

    //! sort alphabetically
    std::sort(vs.begin(), vs.end());
    for (auto element : vs)
        std::cout << element
                  <<" ";
    std::cout <<"\n";

    //! put all duplicates at the end of the vector
    //! and get the iterator pointing to the one past
    //! the last unique element.
    auto unique_iterator = std::unique(vs.begin(),vs.end());
    for (auto element : vs)
        std::cout << element
                  <<" ";
    std::cout <<"\n";

    vs.erase(unique_iterator, vs.end());
    for (auto element : vs)
        std::cout << element
                  <<" ";
    std::cout <<"\n";
}

//! Exercise 10.16
void
wy_biggies(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz)
{
    wy_elimdups(vs);

    // sort words by size, but maintain alphabetical order for words of the same size
    std::stable_sort(vs.begin(), vs.end(),
                     [](const std::string &s1, const std::string &s2){return s1.size() < s2.size();});

    // get an iterator to the first element whose size() is >= sz
    auto wc = std::find_if(vs.begin(), vs.end(),
                           [sz](const std::string &s)
                                {return s.size() > sz;});

    std::for_each(wc, vs.end(), [](const std::string &s)
                                         {std::cout << s;});
}

//! Exercise 10.18
void wy_biggies_partition(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz)
{
    wy_elimdups(vs);

    // sort words by size, but maintain alphabetical order for words of the same size
    std::stable_sort(vs.begin(), vs.end(),
                     [](const std::string &s1, const std::string &s2){return s1.size() < s2.size();});

    auto wc = std::partition(vs.begin(), vs.end(),
                             [sz](const std::string &s)
                                        {return s.size() > sz;});
    std::for_each(wc, vs.end(), [](const std::string &s)
                                         {std::cout << s;});

}

//! Exercise 10.19
void wy_biggies_STpartition(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz)
{
    wy_elimdups(vs);

    // sort words by size, but maintain alphabetical order for words of the same size
    std::stable_sort(vs.begin(), vs.end(),
                     [](const std::string &s1, const std::string &s2){return s1.size() < s2.size();});

    auto wc = std::stable_partition(vs.begin(), vs.end(),
                             [sz](const std::string &s)
                                        {return s.size() > sz;});

    std::for_each(wc, vs.end(), [](const std::string &s)
                                         {std::cout << s;});
}

<commit_msg>Update ex10_14_15_16_18_19.cpp<commit_after>//! @Alan
//!
//! Exercise 10.14:
//! Write a lambda that takes two ints and returns their sum.
//!
//! Exercise 10.15:
//! Write a lambda that captures an int from its enclosing function
//! and takes an int parameter. The lambda should return the sum of
//! the captured int and the int parameter.
//!
//! Exercise 10.16:
//! Write your own version of the biggies function using lambdas.
//!
//! Exercise 10.18:
//! Rewrite biggies to use partition instead of find_if.
//!
//! Exercise 10.19:
//! Rewrite the previous exercise to use stable_partition, which like
//! stable_sort maintains the original element order in the paritioned
//! sequence.
//!

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

//! Exercise 10.14
auto sum = [](const int i1, const int i2 )
{   return i1 + i2;     };
//!                      ^
//! @note There is a ";" here, just like that used after a body of a class.

//! Exercise 10.15
void f()
{
    int i = 0;
    auto sum = [i](const int j)
    {
        return i + j;
    };
}

//! Exercise 10.16
void
wy_elimdups(std::vector<std::string> &vs);
void
wy_biggies(std::vector<std::string> &vs,const std::vector<std::string>::size_type sz);

//! Exercise 10.18
void
wy_biggies_partition(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz);

//! Exercise 10.19
void
wy_biggies_STpartition(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz);
int main()
{

    return 0;
}
void wy_elimdups(std::vector<std::string> &vs)
{
    for (auto element : vs)
        std::cout << element
                  <<" ";
    std::cout <<"\n";

    //! sort alphabetically
    std::sort(vs.begin(), vs.end());
    for (auto element : vs)
        std::cout << element
                  <<" ";
    std::cout <<"\n";

    //! put all duplicates at the end of the vector
    //! and get the iterator pointing to the one past
    //! the last unique element.
    auto unique_iterator = std::unique(vs.begin(),vs.end());
    for (auto element : vs)
        std::cout << element
                  <<" ";
    std::cout <<"\n";

    vs.erase(unique_iterator, vs.end());
    for (auto element : vs)
        std::cout << element
                  <<" ";
    std::cout <<"\n";
}

//! Exercise 10.16
void
wy_biggies(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz)
{
    wy_elimdups(vs);

    // sort words by size, but maintain alphabetical order for words of the same size
    std::stable_sort(vs.begin(), vs.end(),
                     [](const std::string &s1, const std::string &s2){return s1.size() < s2.size();});

    // get an iterator to the first element whose size() is >= sz
    auto wc = std::find_if(vs.begin(), vs.end(),
                           [sz](const std::string &s)
                                {return s.size() > sz;});

    std::for_each(wc, vs.end(), [](const std::string &s)
                                         {std::cout << s;});
}

//! Exercise 10.18
void wy_biggies_partition(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz)
{
    wy_elimdups(vs);

    // sort words by size, but maintain alphabetical order for words of the same size
    std::stable_sort(vs.begin(), vs.end(),
                     [](const std::string &s1, const std::string &s2){return s1.size() < s2.size();});

    auto wc = std::partition(vs.begin(), vs.end(),
                             [sz](const std::string &s)
                                        {return s.size() > sz;});
    std::for_each(vs.begin(),wc, [](const std::string &s)
                                         {std::cout << s;});

}

//! Exercise 10.19
void wy_biggies_STpartition(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz)
{
    wy_elimdups(vs);

    // sort words by size, but maintain alphabetical order for words of the same size
    std::stable_sort(vs.begin(), vs.end(),
                     [](const std::string &s1, const std::string &s2){return s1.size() < s2.size();});

    auto wc = std::stable_partition(vs.begin(), vs.end(),
                             [sz](const std::string &s)
                                        {return s.size() > sz;});

    std::for_each(wc, vs.end(), [](const std::string &s)
                                         {std::cout << s;});
}

<|endoftext|>


<commit_before>// Copyright 2004-present Facebook. All Rights Reserved.

#include "osquery/tables/system/processes.h"

#include <algorithm>
#include <map>
#include <string>
#include <unordered_set>

#include <libproc.h>
#include <stdlib.h>

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/lexical_cast.hpp>

#include <glog/logging.h>

#include "osquery/core.h"

using namespace osquery::core;
using namespace osquery::db;

namespace osquery { namespace tables {

QueryData genProcesses() {
  QueryData results;
  std::unordered_set<int> processed;
  std::unordered_map<int, int> parent_pid;

  // find how how many pids there are so that we can create an appropriately
  // sized data structure to store them
  int num_pids = proc_listpids(PROC_ALL_PIDS, 0, NULL, 0);
  if (num_pids <= 0) {
    LOG(ERROR) << "An error occured retrieving the process list";
    return {};
  }

  // arbitrarily create a list with 2x capacity in case more processes have
  // been loaded since the last proc_listpids was executed
  pid_t pids[num_pids * 2];
  memset(pids, 0, sizeof(pids));
  int s = proc_listpids(PROC_ALL_PIDS, 0, pids, sizeof(pids));
  if (s <= 0) {
    LOG(ERROR) << "An error occured retrieving the process list";
    return {};
  }

  for (const auto& pid : pids) {
    pid_t children[num_pids * 2];
    memset(children, 0, sizeof(children));
    proc_listchildpids(pid, children, sizeof(children));
    for (const auto& child : children) {
      parent_pid[child] = pid;
    }
  }

  for (const auto& pid : pids) {
    // if the pid is negative or 0, it doesn't represent a real process so
    // continue the iterations so that we don't add it to the results set
    if (pid <= 0) {
      continue;
    }

    // ensure that we process a pid once and only once
    if (std::find(processed.begin(), processed.end(), pid) != processed.end()) {
      continue;
    }
    processed.insert(pid);

    // gather column data
    Row r;

    const auto parent_it = parent_pid.find(pid);
    if (parent_it != parent_pid.end()) {
      r["parent"] = boost::lexical_cast<std::string>(parent_it->second);
    } else {
      r["parent"] = "-1";
    }

    // process id
    r["pid"] = boost::lexical_cast<std::string>(pid);

    // process name
    char name[1024];
    memset(name, 0, 1024);
    proc_name(pid, name, sizeof(name));
    r["name"] = std::string(name);

    // if the path of the executable that started the process is available and
    // the path exists on disk, set on_disk to 1.  if the path is not
    // available, set on_disk to -1.  if, and only if, the path of the
    // executable is available and the file does not exist on disk, set on_disk
    // to 0.
    char path[PROC_PIDPATHINFO_MAXSIZE];
    memset(path, 0, sizeof(path));
    proc_pidpath(pid, path, sizeof(path));
    r["path"] = std::string(path);
    if (strlen(path) > 0) {
      if (!boost::filesystem::exists(r["path"])) {
        r["on_disk"] = "0";
      } else {
        r["on_disk"] = "1";
      }
    } else {
      r["on_disk"] = "-1";
    }

    // systems usage and time information
    struct rusage_info_v2 rusage_info_data;
    int rusage_status = proc_pid_rusage(
      pid, RUSAGE_INFO_V2, (rusage_info_t*)&rusage_info_data);
    // proc_pid_rusage returns -1 if it was unable to gather information
    if (rusage_status == 0) {
      // size information
      r["wired_size"] = boost::lexical_cast<std::string>(
        rusage_info_data.ri_wired_size);
      r["resident_size"] = boost::lexical_cast<std::string>(
        rusage_info_data.ri_resident_size);
      r["phys_footprint"] = boost::lexical_cast<std::string>(
        rusage_info_data.ri_phys_footprint);

      // time information
      r["user_time"] = boost::lexical_cast<std::string>(
        rusage_info_data.ri_user_time);
      r["system_time"] = boost::lexical_cast<std::string>(
        rusage_info_data.ri_system_time);
      r["start_time"] = boost::lexical_cast<std::string>(
        rusage_info_data.ri_proc_start_abstime);
    }

    // save the results
    results.push_back(r);
  }

  return results;
}

}}
<commit_msg>string::length instead of strlen<commit_after>// Copyright 2004-present Facebook. All Rights Reserved.

#include "osquery/tables/system/processes.h"

#include <algorithm>
#include <map>
#include <string>
#include <unordered_set>

#include <libproc.h>
#include <stdlib.h>

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/lexical_cast.hpp>

#include <glog/logging.h>

#include "osquery/core.h"

using namespace osquery::core;
using namespace osquery::db;

namespace osquery { namespace tables {

QueryData genProcesses() {
  QueryData results;
  std::unordered_set<int> processed;
  std::unordered_map<int, int> parent_pid;

  // find how how many pids there are so that we can create an appropriately
  // sized data structure to store them
  int num_pids = proc_listpids(PROC_ALL_PIDS, 0, NULL, 0);
  if (num_pids <= 0) {
    LOG(ERROR) << "An error occured retrieving the process list";
    return {};
  }

  // arbitrarily create a list with 2x capacity in case more processes have
  // been loaded since the last proc_listpids was executed
  pid_t pids[num_pids * 2];
  memset(pids, 0, sizeof(pids));
  int s = proc_listpids(PROC_ALL_PIDS, 0, pids, sizeof(pids));
  if (s <= 0) {
    LOG(ERROR) << "An error occured retrieving the process list";
    return {};
  }

  for (const auto& pid : pids) {
    pid_t children[num_pids * 2];
    memset(children, 0, sizeof(children));
    proc_listchildpids(pid, children, sizeof(children));
    for (const auto& child : children) {
      parent_pid[child] = pid;
    }
  }

  for (const auto& pid : pids) {
    // if the pid is negative or 0, it doesn't represent a real process so
    // continue the iterations so that we don't add it to the results set
    if (pid <= 0) {
      continue;
    }

    // ensure that we process a pid once and only once
    if (std::find(processed.begin(), processed.end(), pid) != processed.end()) {
      continue;
    }
    processed.insert(pid);

    // gather column data
    Row r;

    const auto parent_it = parent_pid.find(pid);
    if (parent_it != parent_pid.end()) {
      r["parent"] = boost::lexical_cast<std::string>(parent_it->second);
    } else {
      r["parent"] = "-1";
    }

    // process id
    r["pid"] = boost::lexical_cast<std::string>(pid);

    // process name
    char name[1024];
    memset(name, 0, sizeof(name));
    proc_name(pid, name, sizeof(name));
    r["name"] = std::string(name);

    // if the path of the executable that started the process is available and
    // the path exists on disk, set on_disk to 1.  if the path is not
    // available, set on_disk to -1.  if, and only if, the path of the
    // executable is available and the file does not exist on disk, set on_disk
    // to 0.
    char path[PROC_PIDPATHINFO_MAXSIZE];
    memset(path, 0, sizeof(path));
    proc_pidpath(pid, path, sizeof(path));
    r["path"] = std::string(path);
    if ((r["path"]).length() > 0) {
      if (!boost::filesystem::exists(r["path"])) {
        r["on_disk"] = "0";
      } else {
        r["on_disk"] = "1";
      }
    } else {
      r["on_disk"] = "-1";
    }

    // systems usage and time information
    struct rusage_info_v2 rusage_info_data;
    int rusage_status = proc_pid_rusage(
      pid, RUSAGE_INFO_V2, (rusage_info_t*)&rusage_info_data);
    // proc_pid_rusage returns -1 if it was unable to gather information
    if (rusage_status == 0) {
      // size information
      r["wired_size"] = boost::lexical_cast<std::string>(
        rusage_info_data.ri_wired_size);
      r["resident_size"] = boost::lexical_cast<std::string>(
        rusage_info_data.ri_resident_size);
      r["phys_footprint"] = boost::lexical_cast<std::string>(
        rusage_info_data.ri_phys_footprint);

      // time information
      r["user_time"] = boost::lexical_cast<std::string>(
        rusage_info_data.ri_user_time);
      r["system_time"] = boost::lexical_cast<std::string>(
        rusage_info_data.ri_system_time);
      r["start_time"] = boost::lexical_cast<std::string>(
        rusage_info_data.ri_proc_start_abstime);
    }

    // save the results
    results.push_back(r);
  }

  return results;
}

}}
<|endoftext|>


<commit_before>//===- PowerPCInstrInfo.cpp - PowerPC Instruction Information ---*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the PowerPC implementation of the TargetInstrInfo class.
//
//===----------------------------------------------------------------------===//

#include "PowerPCInstrInfo.h"
#include "PowerPC.h"
#include "PowerPCGenInstrInfo.inc"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include <iostream>
using namespace llvm;

PowerPCInstrInfo::PowerPCInstrInfo()
  : TargetInstrInfo(PowerPCInsts, sizeof(PowerPCInsts)/sizeof(PowerPCInsts[0]))
{ }

bool PowerPCInstrInfo::isMoveInstr(const MachineInstr& MI,
                                   unsigned& sourceReg,
                                   unsigned& destReg) const {
  MachineOpCode oc = MI.getOpcode();
  if (oc == PPC32::OR) {                      // or r1, r2, r2
    assert(MI.getNumOperands() == 3 &&
           MI.getOperand(0).isRegister() &&
           MI.getOperand(1).isRegister() &&
           MI.getOperand(2).isRegister() &&
           "invalid register-register int move instruction");
    if (MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) {
      sourceReg = MI.getOperand(1).getReg();
      destReg = MI.getOperand(0).getReg();
      return true;
    }
  } else if (oc == PPC32::ADDI) {             // addi r1, r2, 0
    if (MI.getNumOperands() == 3 &&
        MI.getOperand(0).isRegister() &&
        MI.getOperand(1).isRegister() &&
        MI.getOperand(2).isImmediate() &&
        MI.getOperand(2).getImmedValue() == 0) {
      sourceReg = MI.getOperand(1).getReg();
      destReg = MI.getOperand(0).getReg();
      return true;
    }
  } else if (oc == PPC32::FMR) {              // fmr r1, r2
    assert(MI.getNumOperands() == 2 &&
           MI.getOperand(0).isRegister() &&
           MI.getOperand(1).isRegister() &&
           "invalid register-register fp move instruction");
    sourceReg = MI.getOperand(1).getReg();
    destReg = MI.getOperand(0).getReg();
    return true;
  }
  return false;
}
<commit_msg>assert() on MachineInstr properties instead of checking them dynamically<commit_after>//===- PowerPCInstrInfo.cpp - PowerPC Instruction Information ---*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the PowerPC implementation of the TargetInstrInfo class.
//
//===----------------------------------------------------------------------===//

#include "PowerPCInstrInfo.h"
#include "PowerPC.h"
#include "PowerPCGenInstrInfo.inc"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include <iostream>
using namespace llvm;

PowerPCInstrInfo::PowerPCInstrInfo()
  : TargetInstrInfo(PowerPCInsts, sizeof(PowerPCInsts)/sizeof(PowerPCInsts[0]))
{ }

bool PowerPCInstrInfo::isMoveInstr(const MachineInstr& MI,
                                   unsigned& sourceReg,
                                   unsigned& destReg) const {
  MachineOpCode oc = MI.getOpcode();
  if (oc == PPC32::OR) {                      // or r1, r2, r2
    assert(MI.getNumOperands() == 3 &&
           MI.getOperand(0).isRegister() &&
           MI.getOperand(1).isRegister() &&
           MI.getOperand(2).isRegister() &&
           "invalid PPC32 OR instruction!");
    if (MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) {
      sourceReg = MI.getOperand(1).getReg();
      destReg = MI.getOperand(0).getReg();
      return true;
    }
  } else if (oc == PPC32::ADDI) {             // addi r1, r2, 0
    assert(MI.getNumOperands() == 3 &&
           MI.getOperand(0).isRegister() &&
           MI.getOperand(1).isRegister() &&
           MI.getOperand(2).isImmediate() &&
           "invalid PPC32 ADDI instruction!");
    if (MI.getOperand(2).getImmedValue() == 0) {
      sourceReg = MI.getOperand(1).getReg();
      destReg = MI.getOperand(0).getReg();
      return true;
    }
  } else if (oc == PPC32::FMR) {              // fmr r1, r2
    assert(MI.getNumOperands() == 2 &&
           MI.getOperand(0).isRegister() &&
           MI.getOperand(1).isRegister() &&
           "invalid PPC32 FMR instruction");
    sourceReg = MI.getOperand(1).getReg();
    destReg = MI.getOperand(0).getReg();
    return true;
  }
  return false;
}
<|endoftext|>


<commit_before>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#include "sfidl-generator.hh"
#include "sfidl-options.hh"
#include "sfidl-parser.hh"

#define app_error(...)  do { g_printerr ("%s: ", g_get_prgname()); g_printerr (__VA_ARGS__); exit (-1); } while (0)

using namespace Sfidl;

namespace Bse {
String
program_alias ()
{
  return program_invocation_name;
}
} // Bse

#ifdef  SFIDL_INTERNALS
int main (int argc, char **argv)
{
  Options options;
  Parser parser;

  if (!options.parse (&argc, &argv, parser))
    {
      /* invalid options */
      return 1;
    }

  if (options.doExit)
    {
      return 0;
    }

  if (options.doHelp)
    {
      options.printUsage ();
      return 0;
    }

  if (argc != 2)
    {
      options.printUsage ();
      return 1;
    }

  if (!options.codeGenerator)
    {
      options.printUsage();
      return 1;
    }

  if (!parser.parse(argv[1]))
    {
      /* parse error */
      return 1;
    }

  if (!options.codeGenerator->run ())
    {
      delete options.codeGenerator;
      return 1;
    }

  delete options.codeGenerator;
  return 0;
}
#endif

#include "sfidl-generator.cc"
#include "sfidl-namespace.cc"
#include "sfidl-options.cc"
#include "sfidl-parser.cc"
#include "sfidl-factory.cc"
#include "sfidl-typelist.cc"
#include "sfidl-cbase.cc"
#include "sfidl-clientc.cc"
#include "sfidl-clientcxx.cc"
#include "sfidl-corec.cc"
#include "sfidl-corecxx.cc"
#include "sfidl-cxxbase.cc"
#include "sfidl-hostc.cc"
#include "sfidl-utils.cc"

/* vim:set ts=8 sts=2 sw=2: */
<commit_msg>SFI: sfidl: fix warning<commit_after>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#include "sfidl-generator.hh"
#include "sfidl-options.hh"
#include "sfidl-parser.hh"

#define app_error(...)  do { g_printerr ("%s: ", g_get_prgname()); g_printerr (__VA_ARGS__); exit (-1); } while (0)

using namespace Sfidl;

namespace Bse {
String program_alias ();

String
program_alias ()
{
  return program_invocation_name;
}
} // Bse

#ifdef  SFIDL_INTERNALS
int main (int argc, char **argv)
{
  Options options;
  Parser parser;

  if (!options.parse (&argc, &argv, parser))
    {
      /* invalid options */
      return 1;
    }

  if (options.doExit)
    {
      return 0;
    }

  if (options.doHelp)
    {
      options.printUsage ();
      return 0;
    }

  if (argc != 2)
    {
      options.printUsage ();
      return 1;
    }

  if (!options.codeGenerator)
    {
      options.printUsage();
      return 1;
    }

  if (!parser.parse(argv[1]))
    {
      /* parse error */
      return 1;
    }

  if (!options.codeGenerator->run ())
    {
      delete options.codeGenerator;
      return 1;
    }

  delete options.codeGenerator;
  return 0;
}
#endif

#include "sfidl-generator.cc"
#include "sfidl-namespace.cc"
#include "sfidl-options.cc"
#include "sfidl-parser.cc"
#include "sfidl-factory.cc"
#include "sfidl-typelist.cc"
#include "sfidl-cbase.cc"
#include "sfidl-clientc.cc"
#include "sfidl-clientcxx.cc"
#include "sfidl-corec.cc"
#include "sfidl-corecxx.cc"
#include "sfidl-cxxbase.cc"
#include "sfidl-hostc.cc"
#include "sfidl-utils.cc"

/* vim:set ts=8 sts=2 sw=2: */
<|endoftext|>


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

#include <sfx2/basedlgs.hxx>
#include <sfx2/tabdlg.hxx>

#include <com/sun/star/container/XNameReplace.hpp>
#include <com/sun/star/util/XModifiable.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/uno/Reference.hxx>

#ifndef _SFXMACITEM_HXX //autogen
#include <svtools/macitem.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#include <rtl/ustring.hxx>

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

#include <hash_map>

typedef ::std::hash_map< ::rtl::OUString, ::std::pair< ::rtl::OUString, ::rtl::OUString >, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > EventsHash;
typedef ::std::hash_map< ::rtl::OUString, ::rtl::OUString, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > UIEventsStringHash;

class _SvxMacroTabPage;
class SvStringsDtor;
class SvTabListBox;
class Edit;
class String;

class _HeaderTabListBox;
class _SvxMacroTabPage_Impl;

class _SvxMacroTabPage : public SfxTabPage
{
#if _SOLAR__PRIVATE
    DECL_STATIC_LINK( _SvxMacroTabPage, SelectEvent_Impl, SvTabListBox * );
    DECL_STATIC_LINK( _SvxMacroTabPage, AssignDeleteHdl_Impl, PushButton * );
    DECL_STATIC_LINK( _SvxMacroTabPage, DoubleClickHdl_Impl, SvTabListBox * );

    static long GenericHandler_Impl( _SvxMacroTabPage* pThis, PushButton* pBtn );

#endif
protected:
    _SvxMacroTabPage_Impl*      mpImpl;
    ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > m_xAppEvents;
    ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > m_xDocEvents;
    ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifiable > m_xModifiable;
    EventsHash m_appEventsHash;
    EventsHash m_docEventsHash;
    bool bReadOnly, bDocModified, bAppEvents, bInitialized;
    UIEventsStringHash aUIStrings;

                                _SvxMacroTabPage( Window* pParent, const ResId& rId, const SfxItemSet& rItemSet );

    void                        EnableButtons( const String& rLanguage );
    ::com::sun::star::uno::Any  GetPropsByName( const ::rtl::OUString& eventName, EventsHash& eventsHash );
    ::std::pair< ::rtl::OUString, ::rtl::OUString > GetPairFromAny( ::com::sun::star::uno::Any aAny );

public:

    virtual                     ~_SvxMacroTabPage();
    void                        InitResources();

    void                        InitAndSetHandler( ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > xAppEvents, ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > xDocEvents, ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifiable > xModifiable );
    virtual BOOL                FillItemSet( SfxItemSet& rSet );

    using SfxTabPage::Reset;
    virtual void                Reset();

    void                        DisplayAppEvents( bool appEvents);
    void                        SetReadOnly( BOOL bSet );
    BOOL                        IsReadOnly() const;
};

class SvxMacroTabPage : public _SvxMacroTabPage
{
public:
    SvxMacroTabPage( Window* pParent, const ResId& rId,
                    const SfxItemSet& rSet, ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > xNameReplace, sal_uInt16 nSelectedIndex=0 );
    virtual ~SvxMacroTabPage();

    static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet, ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > xNameReplace, sal_uInt16 nSelectedIndex=0 );
};

// class SvxMacroAssignDlg --------------------------------------------------

typedef USHORT* (*GetTabPageRanges)(); // liefert internationale Which-Werte

class SVX_DLLPUBLIC SvxMacroAssignSingleTabDialog : public SfxModalDialog
{
public:
    SvxMacroAssignSingleTabDialog( Window* pParent, const SfxItemSet& rOptionsSet, USHORT nUniqueId );

    virtual             ~SvxMacroAssignSingleTabDialog();

    void                SetTabPage( SfxTabPage* pTabPage );
    // SfxTabPage*          GetTabPage() const { return pPage; }

    // OKButton*            GetOKButton() const { return pOKBtn; }
    // CancelButton*        GetCancelButton() const { return pCancelBtn; }

private:
    SfxViewFrame*       pFrame;

    FixedLine*          pFixedLine;

    OKButton*           pOKBtn;
    CancelButton*       pCancelBtn;
    HelpButton*         pHelpBtn;

    SfxTabPage*         pPage;
    const SfxItemSet*   pOptions;
    SfxItemSet*         pOutSet;

#if _SOLAR__PRIVATE
    DECL_DLLPRIVATE_LINK( OKHdl_Impl, Button * );
#endif
};

class SVX_DLLPUBLIC SvxMacroAssignDlg : public SvxMacroAssignSingleTabDialog
{
public:
    SvxMacroAssignDlg( Window* pParent, SfxItemSet& rSet, ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > xNameReplace, sal_uInt16 nSelectedIndex=0 );
    virtual ~SvxMacroAssignDlg();
};

#endif
<commit_msg>INTEGRATION: CWS odbmacros2 (1.9.560); FILE MERGED 2007/12/12 14:27:16 fs 1.9.560.1: #i49133# pass an XFrame to the SvxMacroAssignDlg and the SvxMacroTabPage<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: macropg.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-06 17:09:41 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _MACROPG_HXX
#define _MACROPG_HXX

#include <sfx2/basedlgs.hxx>
#include <sfx2/tabdlg.hxx>

#include <com/sun/star/container/XNameReplace.hpp>
#include <com/sun/star/util/XModifiable.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/uno/Reference.hxx>

#ifndef _SFXMACITEM_HXX //autogen
#include <svtools/macitem.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#include <rtl/ustring.hxx>

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

#include <hash_map>

typedef ::std::hash_map< ::rtl::OUString, ::std::pair< ::rtl::OUString, ::rtl::OUString >, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > EventsHash;
typedef ::std::hash_map< ::rtl::OUString, ::rtl::OUString, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > UIEventsStringHash;

class _SvxMacroTabPage;
class SvStringsDtor;
class SvTabListBox;
class Edit;
class String;

class _HeaderTabListBox;
class _SvxMacroTabPage_Impl;

class _SvxMacroTabPage : public SfxTabPage
{
#if _SOLAR__PRIVATE
    DECL_STATIC_LINK( _SvxMacroTabPage, SelectEvent_Impl, SvTabListBox * );
    DECL_STATIC_LINK( _SvxMacroTabPage, AssignDeleteHdl_Impl, PushButton * );
    DECL_STATIC_LINK( _SvxMacroTabPage, DoubleClickHdl_Impl, SvTabListBox * );

    static long GenericHandler_Impl( _SvxMacroTabPage* pThis, PushButton* pBtn );

#endif
protected:
    _SvxMacroTabPage_Impl*      mpImpl;
    ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > m_xAppEvents;
    ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > m_xDocEvents;
    ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifiable > m_xModifiable;
    EventsHash m_appEventsHash;
    EventsHash m_docEventsHash;
    bool bReadOnly, bDocModified, bAppEvents, bInitialized;
    UIEventsStringHash aUIStrings;

                                _SvxMacroTabPage( Window* pParent, const ResId& rId, const SfxItemSet& rItemSet );

    void                        EnableButtons( const String& rLanguage );
    ::com::sun::star::uno::Any  GetPropsByName( const ::rtl::OUString& eventName, EventsHash& eventsHash );
    ::std::pair< ::rtl::OUString, ::rtl::OUString > GetPairFromAny( ::com::sun::star::uno::Any aAny );

public:

    virtual                     ~_SvxMacroTabPage();
    void                        InitResources();

    void                        InitAndSetHandler( ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > xAppEvents, ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > xDocEvents, ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifiable > xModifiable );
    virtual BOOL                FillItemSet( SfxItemSet& rSet );

    using SfxTabPage::Reset;
    virtual void                Reset();

    void                        DisplayAppEvents( bool appEvents);
    void                        SetReadOnly( BOOL bSet );
    BOOL                        IsReadOnly() const;
};

class SvxMacroTabPage : public _SvxMacroTabPage
{
public:
    SvxMacroTabPage(
        Window* pParent,
        const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _rxDocumentFrame,
        const SfxItemSet& rSet,
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > xNameReplace,
        sal_uInt16 nSelectedIndex
    );
    virtual ~SvxMacroTabPage();
};

// class SvxMacroAssignDlg --------------------------------------------------

typedef USHORT* (*GetTabPageRanges)(); // liefert internationale Which-Werte

class SVX_DLLPUBLIC SvxMacroAssignSingleTabDialog : public SfxModalDialog
{
public:
    SvxMacroAssignSingleTabDialog( Window* pParent, const SfxItemSet& rOptionsSet, USHORT nUniqueId );

    virtual             ~SvxMacroAssignSingleTabDialog();

    void                SetTabPage( SfxTabPage* pTabPage );
    // SfxTabPage*          GetTabPage() const { return pPage; }

    // OKButton*            GetOKButton() const { return pOKBtn; }
    // CancelButton*        GetCancelButton() const { return pCancelBtn; }

private:
    SfxViewFrame*       pFrame;

    FixedLine*          pFixedLine;

    OKButton*           pOKBtn;
    CancelButton*       pCancelBtn;
    HelpButton*         pHelpBtn;

    SfxTabPage*         pPage;
    const SfxItemSet*   pOptions;
    SfxItemSet*         pOutSet;

#if _SOLAR__PRIVATE
    DECL_DLLPRIVATE_LINK( OKHdl_Impl, Button * );
#endif
};

class SVX_DLLPUBLIC SvxMacroAssignDlg : public SvxMacroAssignSingleTabDialog
{
public:
    SvxMacroAssignDlg(
        Window* pParent,
        const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _rxDocumentFrame,
        const SfxItemSet& rSet,
        const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace >& xNameReplace,
        sal_uInt16 nSelectedIndex
    );
    virtual ~SvxMacroAssignDlg();
};

#endif
<|endoftext|>