<commit_before>#include "json_writer.hpp"

#include <limits>
#include <cmath>
#include <cinttypes>

#include "../libs/gdtoa/gdtoa.h"

// TODO: test putc_unlocked (EOF), snprintf, g_ffmt and g_dfmt (length if unlimited) output
namespace zizany {
    static
    void
    fputs_unlocked_(const char *str, FILE *output) {
        while (*str != 0)
            putc_unlocked(*str++, output);
    }

    static
    void
    print_with_leading_zero(const char *buffer, FILE *output) {
        if (buffer[0] == '-' && buffer[1] == '.') {
            putc_unlocked('-', output);
            putc_unlocked('0', output);
            fputs_unlocked_(buffer + 1, output);
        } else {
            if (buffer[0] == '.')
                putc_unlocked('0', output);
            fputs_unlocked_(buffer, output);
        }
    }

    json_writer::json_writer(FILE *output_, const int indent_width_)
            : output(output_),
              indent_width(indent_width_),
              indent_level(0),
              inline_level(std::numeric_limits<int>::max()),
              state(writer_state::after_start) {
    }

    void
    json_writer::add_string(const std::string &value) {
        insert_separator_if_needed();
        print_quoted_string(value);
        state = writer_state::after_value;
    }

    void
    json_writer::add_string(const char *chars, const std::size_t length) {
        insert_separator_if_needed();
        print_quoted_string(chars, length);
        state = writer_state::after_value;
    }

    void
    json_writer::add_number(std::int32_t value) {
        insert_separator_if_needed();
        char buffer[64];
        snprintf(buffer, 64, "%" PRIi32, value);
        fputs_unlocked_(buffer, output);
        state = writer_state::after_value;
    }

    void
    json_writer::add_number(std::uint32_t value) {
        insert_separator_if_needed();
        char buffer[64];
        snprintf(buffer, 64, "%" PRIu32, value);
        fputs_unlocked_(buffer, output);
        state = writer_state::after_value;
    }

    void
    json_writer::add_number(std::int64_t value) {
        insert_separator_if_needed();
        char buffer[64];
        snprintf(buffer, 64, "%" PRIi64, value);
        fputs_unlocked_(buffer, output);
        state = writer_state::after_value;
    }

    void
    json_writer::add_number(std::uint64_t value) {
        insert_separator_if_needed();
        char buffer[64];
        snprintf(buffer, 64, "%" PRIu64, value);
        fputs_unlocked_(buffer, output);
        state = writer_state::after_value;
    }

    void
    json_writer::add_number(float value) {
        insert_separator_if_needed();
        if (std::isnan(value) || std::isinf(value))
            fputs_unlocked_("null", output);
        else {
            char buffer[32];
            g_ffmt(buffer, &value, -1, sizeof(buffer));
            print_with_leading_zero(buffer, output);
        }
        state = writer_state::after_value;
    }

    void
    json_writer::add_number(double value) {
        insert_separator_if_needed();
        if (std::isnan(value) || std::isinf(value))
            fputs_unlocked_("null", output);
        else {
            char buffer[32];
            g_dfmt(buffer, &value, -1, sizeof(buffer));
            print_with_leading_zero(buffer, output);
        }
        state = writer_state::after_value;
    }

    void
    json_writer::add_bool(bool value) {
        insert_separator_if_needed();
        fputs_unlocked_(value ? "true" : "false", output);
        state = writer_state::after_value;
    }

    void
    json_writer::add_null() {
        insert_separator_if_needed();
        fputs_unlocked_("null", output);
        state = writer_state::after_value;
    }

    void
    json_writer::start_object(bool force_inline) {
        start_composite('{', force_inline);
    }

    void
    json_writer::add_key(const char *key) {
        insert_separator_if_needed();
        print_quoted_string(key);
        fputs_unlocked_(": ", output);
        state = writer_state::after_key;
    }

    void
    json_writer::add_key(const std::string &key) {
        insert_separator_if_needed();
        print_quoted_string(key);
        fputs_unlocked_(": ", output);
        state = writer_state::after_key;
    }

    void
    json_writer::end_object() {
        end_composite('}');
    }

    void
    json_writer::start_array(bool force_inline) {
        start_composite('[', force_inline);
    }

    void
    json_writer::end_array() {
        end_composite(']');
    }

    void
    json_writer::reset() {
        indent_level = 0;
        state = writer_state::after_start;
    }

    void
    json_writer::start_composite(char marker, bool force_inline) {
        insert_separator_if_needed();
        putc_unlocked(marker, output);
        if (force_inline)
            inline_level = std::min(inline_level, indent_level);
        indent_level += 1;
        state = writer_state::after_composite_start;
    }

    void
    json_writer::end_composite(char marker) {
        indent_level -= 1;
        if (state == writer_state::after_value && indent_level < inline_level)
            insert_newline();
        putc_unlocked(marker, output);
        state = writer_state::after_value;
        if (indent_level == inline_level)
            inline_level = std::numeric_limits<int>::max();
    }

    void
    json_writer::insert_separator_if_needed() {
        if (state == writer_state::after_value)
            putc_unlocked(',', output);
        if (state != writer_state::after_key) {
            if (state != writer_state::after_start && indent_level < inline_level)
                insert_newline();
            else if (state == writer_state::after_value)
                putc_unlocked(' ', output);
        }
    }

    void
    json_writer::insert_newline() {
        putc_unlocked('\n', output);
        for (int i = 0; i < indent_width * indent_level; ++i)
            putc_unlocked(' ', output);
    }

    inline
    void print_quoted_character(FILE *output, const char character) {
        const char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        switch (character) {
            case '\b':
                putc_unlocked('\\', output);
                putc_unlocked('b', output);
                break;
            case '\f':
                putc_unlocked('\\', output);
                putc_unlocked('f', output);
                break;
            case '\n':
                putc_unlocked('\\', output);
                putc_unlocked('n', output);
                break;
            case '\r':
                putc_unlocked('\\', output);
                putc_unlocked('r', output);
                break;
            case '\t':
                putc_unlocked('\\', output);
                putc_unlocked('t', output);
                break;
            case '\\':
                putc_unlocked('\\', output);
                putc_unlocked('\\', output);
                break;
            case '\"':
                putc_unlocked('\\', output);
                putc_unlocked('"', output);
                break;
            default:
                if (character > 0 && character < 32) {
                    putc_unlocked('\\', output);
                    putc_unlocked('u', output);
                    putc_unlocked('0', output);
                    putc_unlocked('0', output);
                    putc_unlocked(hex[character >> 4], output);
                    putc_unlocked(hex[character & 0xf], output);
                } else {
                    putc_unlocked(character, output);
                }
        }
    }

    void
    json_writer::print_quoted_string(const std::string &string) {
        putc_unlocked('"', output);
        for (std::size_t index = 0; index < string.size(); ++index)
            print_quoted_character(output, string[index]);
        putc_unlocked('"', output);
    }

    void
    json_writer::print_quoted_string(const char *string) {
        putc_unlocked('"', output);
        while (*string != 0)
            print_quoted_character(output, *string++);
        putc_unlocked('"', output);
    }

    void
    json_writer::print_quoted_string(const char *string, const std::size_t length) {
        putc_unlocked('"', output);
        for (std::size_t index = 0; index < length; ++index)
            print_quoted_character(output, string[index]);
        putc_unlocked('"', output);
    }
}
<commit_msg>Check status code from formatting and output functions in json_writer<commit_after>#include "json_writer.hpp"

#include "../libs/gdtoa/gdtoa.h"

#include <limits>
#include <cinttypes>
#include <cmath>
#include <cstring>
#include <stdexcept>
#include <sys/errno.h>

namespace zizany {
    static
    void
    putc_unlocked_checked(int c, FILE *output) {
        const int putc_status(putc_unlocked(c, output));
        if (putc_status == EOF)
            throw std::runtime_error(strerror(errno));
    }

    static
    void
    fputs_unlocked_(const char *str, FILE *output) {
        while (*str != 0)
            putc_unlocked_checked(*str++, output);
    }

    static
    void
    print_with_leading_zero(const char *buffer, FILE *output) {
        if (buffer[0] == '-' && buffer[1] == '.') {
            putc_unlocked_checked('-', output);
            putc_unlocked_checked('0', output);
            fputs_unlocked_(buffer + 1, output);
        } else {
            if (buffer[0] == '.')
                putc_unlocked_checked('0', output);
            fputs_unlocked_(buffer, output);
        }
    }

    json_writer::json_writer(FILE *output_, const int indent_width_)
            : output(output_),
              indent_width(indent_width_),
              indent_level(0),
              inline_level(std::numeric_limits<int>::max()),
              state(writer_state::after_start) {
    }

    void
    json_writer::add_string(const std::string &value) {
        insert_separator_if_needed();
        print_quoted_string(value);
        state = writer_state::after_value;
    }

    void
    json_writer::add_string(const char *chars, const std::size_t length) {
        insert_separator_if_needed();
        print_quoted_string(chars, length);
        state = writer_state::after_value;
    }

    void
    json_writer::add_number(std::int32_t value) {
        insert_separator_if_needed();
        char buffer[32];
        const int snprintf_status(snprintf(buffer, sizeof(buffer), "%" PRIi32, value));
        if (snprintf_status >= static_cast<int>(sizeof(buffer)))
            throw std::runtime_error("unexpected large number");
        fputs_unlocked_(buffer, output);
        state = writer_state::after_value;
    }

    void
    json_writer::add_number(std::uint32_t value) {
        insert_separator_if_needed();
        char buffer[32];
        const int snprintf_status(snprintf(buffer, sizeof(buffer), "%" PRIu32, value));
        if (snprintf_status >= static_cast<int>(sizeof(buffer)))
            throw std::runtime_error("unexpected large number");
        fputs_unlocked_(buffer, output);
        state = writer_state::after_value;
    }

    void
    json_writer::add_number(std::int64_t value) {
        insert_separator_if_needed();
        char buffer[32];
        const int snprintf_status(snprintf(buffer, 32, "%" PRIi64, value));
        if (snprintf_status >= static_cast<int>(sizeof(buffer)))
            throw std::runtime_error("unexpected large number");
        fputs_unlocked_(buffer, output);
        state = writer_state::after_value;
    }

    void
    json_writer::add_number(std::uint64_t value) {
        insert_separator_if_needed();
        char buffer[32];
        const int snprintf_status(snprintf(buffer, 32, "%" PRIu64, value));
        if (snprintf_status >= static_cast<int>(sizeof(buffer)))
            throw std::runtime_error("unexpected large number");
        fputs_unlocked_(buffer, output);
        state = writer_state::after_value;
    }

    void
    json_writer::add_number(float value) {
        insert_separator_if_needed();
        if (std::isnan(value) || std::isinf(value))
            fputs_unlocked_("null", output);
        else {
            char buffer[32];
            const char *g_ffmt_status(g_ffmt(buffer, &value, -1, sizeof(buffer)));
            if (g_ffmt_status == nullptr)
                throw std::runtime_error("unexpected large number");
            print_with_leading_zero(buffer, output);
        }
        state = writer_state::after_value;
    }

    void
    json_writer::add_number(double value) {
        insert_separator_if_needed();
        if (std::isnan(value) || std::isinf(value))
            fputs_unlocked_("null", output);
        else {
            char buffer[32];
            const char *g_dfmt_status(g_dfmt(buffer, &value, -1, sizeof(buffer)));
            if (g_dfmt_status == nullptr)
                throw std::runtime_error("unexpected large number");
            print_with_leading_zero(buffer, output);
        }
        state = writer_state::after_value;
    }

    void
    json_writer::add_bool(bool value) {
        insert_separator_if_needed();
        fputs_unlocked_(value ? "true" : "false", output);
        state = writer_state::after_value;
    }

    void
    json_writer::add_null() {
        insert_separator_if_needed();
        fputs_unlocked_("null", output);
        state = writer_state::after_value;
    }

    void
    json_writer::start_object(bool force_inline) {
        start_composite('{', force_inline);
    }

    void
    json_writer::add_key(const char *key) {
        insert_separator_if_needed();
        print_quoted_string(key);
        fputs_unlocked_(": ", output);
        state = writer_state::after_key;
    }

    void
    json_writer::add_key(const std::string &key) {
        insert_separator_if_needed();
        print_quoted_string(key);
        fputs_unlocked_(": ", output);
        state = writer_state::after_key;
    }

    void
    json_writer::end_object() {
        end_composite('}');
    }

    void
    json_writer::start_array(bool force_inline) {
        start_composite('[', force_inline);
    }

    void
    json_writer::end_array() {
        end_composite(']');
    }

    void
    json_writer::reset() {
        indent_level = 0;
        state = writer_state::after_start;
    }

    void
    json_writer::start_composite(char marker, bool force_inline) {
        insert_separator_if_needed();
        putc_unlocked_checked(marker, output);
        if (force_inline)
            inline_level = std::min(inline_level, indent_level);
        indent_level += 1;
        state = writer_state::after_composite_start;
    }

    void
    json_writer::end_composite(char marker) {
        indent_level -= 1;
        if (state == writer_state::after_value && indent_level < inline_level)
            insert_newline();
        putc_unlocked_checked(marker, output);
        state = writer_state::after_value;
        if (indent_level == inline_level)
            inline_level = std::numeric_limits<int>::max();
    }

    void
    json_writer::insert_separator_if_needed() {
        if (state == writer_state::after_value)
            putc_unlocked_checked(',', output);
        if (state != writer_state::after_key) {
            if (state != writer_state::after_start && indent_level < inline_level)
                insert_newline();
            else if (state == writer_state::after_value)
                putc_unlocked_checked(' ', output);
        }
    }

    void
    json_writer::insert_newline() {
        putc_unlocked_checked('\n', output);
        for (int i = 0; i < indent_width * indent_level; ++i)
            putc_unlocked_checked(' ', output);
    }

    inline
    void print_quoted_character(FILE *output, const char character) {
        const char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        switch (character) {
            case '\b':
                putc_unlocked_checked('\\', output);
                putc_unlocked_checked('b', output);
                break;
            case '\f':
                putc_unlocked_checked('\\', output);
                putc_unlocked_checked('f', output);
                break;
            case '\n':
                putc_unlocked_checked('\\', output);
                putc_unlocked_checked('n', output);
                break;
            case '\r':
                putc_unlocked_checked('\\', output);
                putc_unlocked_checked('r', output);
                break;
            case '\t':
                putc_unlocked_checked('\\', output);
                putc_unlocked_checked('t', output);
                break;
            case '\\':
                putc_unlocked_checked('\\', output);
                putc_unlocked_checked('\\', output);
                break;
            case '\"':
                putc_unlocked_checked('\\', output);
                putc_unlocked_checked('"', output);
                break;
            default:
                if (character > 0 && character < 32) {
                    putc_unlocked_checked('\\', output);
                    putc_unlocked_checked('u', output);
                    putc_unlocked_checked('0', output);
                    putc_unlocked_checked('0', output);
                    putc_unlocked_checked(hex[character >> 4], output);
                    putc_unlocked_checked(hex[character & 0xf], output);
                } else {
                    putc_unlocked_checked(character, output);
                }
        }
    }

    void
    json_writer::print_quoted_string(const std::string &string) {
        putc_unlocked_checked('"', output);
        for (std::size_t index = 0; index < string.size(); ++index)
            print_quoted_character(output, string[index]);
        putc_unlocked_checked('"', output);
    }

    void
    json_writer::print_quoted_string(const char *string) {
        putc_unlocked_checked('"', output);
        while (*string != 0)
            print_quoted_character(output, *string++);
        putc_unlocked_checked('"', output);
    }

    void
    json_writer::print_quoted_string(const char *string, const std::size_t length) {
        putc_unlocked_checked('"', output);
        for (std::size_t index = 0; index < length; ++index)
            print_quoted_character(output, string[index]);
        putc_unlocked_checked('"', output);
    }
}
<|endoftext|>


<commit_before>//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
//  This source code is licensed under the BSD-style license found in the
//  LICENSE file in the root directory of this source tree. An additional grant
//  of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include "db/db_test_util.h"
#include "port/stack_trace.h"
#include "util/sync_point.h"

namespace rocksdb {

class DBFlushTest : public DBTestBase {
 public:
  DBFlushTest() : DBTestBase("/db_flush_test") {}
};

// We had issue when two background threads trying to flush at the same time,
// only one of them get committed. The test verifies the issue is fixed.
TEST_F(DBFlushTest, FlushWhileWritingManifest) {
  Options options;
  options.disable_auto_compactions = true;
  options.max_background_flushes = 2;
  Reopen(options);
  FlushOptions no_wait;
  no_wait.wait = false;

  SyncPoint::GetInstance()->LoadDependency(
      {{"VersionSet::LogAndApply:WriteManifest",
        "DBFlushTest::FlushWhileWritingManifest:1"},
       {"MemTableList::InstallMemtableFlushResults:InProgress",
        "VersionSet::LogAndApply:WriteManifestDone"}});
  SyncPoint::GetInstance()->EnableProcessing();

  ASSERT_OK(Put("foo", "v"));
  ASSERT_OK(dbfull()->Flush(no_wait));
  TEST_SYNC_POINT("DBFlushTest::FlushWhileWritingManifest:1");
  ASSERT_OK(Put("bar", "v"));
  ASSERT_OK(dbfull()->Flush(no_wait));
  // If the issue is hit we will wait here forever.
  dbfull()->TEST_WaitForFlushMemTable();

  ASSERT_EQ(2, TotalTableFiles());
}

}  // namespace rocksdb

int main(int argc, char** argv) {
  rocksdb::port::InstallStackTraceHandler();
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>Fix unit test which breaks lite build<commit_after>//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
//  This source code is licensed under the BSD-style license found in the
//  LICENSE file in the root directory of this source tree. An additional grant
//  of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include "db/db_test_util.h"
#include "port/stack_trace.h"
#include "util/sync_point.h"

namespace rocksdb {

class DBFlushTest : public DBTestBase {
 public:
  DBFlushTest() : DBTestBase("/db_flush_test") {}
};

// We had issue when two background threads trying to flush at the same time,
// only one of them get committed. The test verifies the issue is fixed.
TEST_F(DBFlushTest, FlushWhileWritingManifest) {
  Options options;
  options.disable_auto_compactions = true;
  options.max_background_flushes = 2;
  Reopen(options);
  FlushOptions no_wait;
  no_wait.wait = false;

  SyncPoint::GetInstance()->LoadDependency(
      {{"VersionSet::LogAndApply:WriteManifest",
        "DBFlushTest::FlushWhileWritingManifest:1"},
       {"MemTableList::InstallMemtableFlushResults:InProgress",
        "VersionSet::LogAndApply:WriteManifestDone"}});
  SyncPoint::GetInstance()->EnableProcessing();

  ASSERT_OK(Put("foo", "v"));
  ASSERT_OK(dbfull()->Flush(no_wait));
  TEST_SYNC_POINT("DBFlushTest::FlushWhileWritingManifest:1");
  ASSERT_OK(Put("bar", "v"));
  ASSERT_OK(dbfull()->Flush(no_wait));
  // If the issue is hit we will wait here forever.
  dbfull()->TEST_WaitForFlushMemTable();
#ifndef ROCKSDB_LITE
  ASSERT_EQ(2, TotalTableFiles());
#endif  // ROCKSDB_LITE
}

}  // namespace rocksdb

int main(int argc, char** argv) {
  rocksdb::port::InstallStackTraceHandler();
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


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

#include "remoting/host/event_executor_win.h"

#include <windows.h>
#include "app/keyboard_codes.h"
#include "base/stl_util-inl.h"
#include "remoting/host/capturer.h"

namespace remoting {

// TODO(hclam): Move this method to base.
// TODO(hclam): Using values look ugly, change it to something else.
static app::KeyboardCode WindowsKeyCodeForPosixKeyCode(int keycode) {
  switch (keycode) {
    case 0x08:
      return app::VKEY_BACK;
    case 0x09:
      return app::VKEY_TAB;
    case 0x0C:
      return app::VKEY_CLEAR;
    case 0x0D:
      return app::VKEY_RETURN;
    case 0x10:
      return app::VKEY_SHIFT;
    case 0x11:
      return app::VKEY_CONTROL;
    case 0x12:
      return app::VKEY_MENU;
    case 0x13:
      return app::VKEY_PAUSE;
    case 0x14:
      return app::VKEY_CAPITAL;
    case 0x15:
      return app::VKEY_KANA;
    case 0x17:
      return app::VKEY_JUNJA;
    case 0x18:
      return app::VKEY_FINAL;
    case 0x19:
      return app::VKEY_KANJI;
    case 0x1B:
      return app::VKEY_ESCAPE;
    case 0x1C:
      return app::VKEY_CONVERT;
    case 0x1D:
      return app::VKEY_NONCONVERT;
    case 0x1E:
      return app::VKEY_ACCEPT;
    case 0x1F:
      return app::VKEY_MODECHANGE;
    case 0x20:
      return app::VKEY_SPACE;
    case 0x21:
      return app::VKEY_PRIOR;
    case 0x22:
      return app::VKEY_NEXT;
    case 0x23:
      return app::VKEY_END;
    case 0x24:
      return app::VKEY_HOME;
    case 0x25:
      return app::VKEY_LEFT;
    case 0x26:
      return app::VKEY_UP;
    case 0x27:
      return app::VKEY_RIGHT;
    case 0x28:
      return app::VKEY_DOWN;
    case 0x29:
      return app::VKEY_SELECT;
    case 0x2A:
      return app::VKEY_PRINT;
    case 0x2B:
      return app::VKEY_EXECUTE;
    case 0x2C:
      return app::VKEY_SNAPSHOT;
    case 0x2D:
      return app::VKEY_INSERT;
    case 0x2E:
      return app::VKEY_DELETE;
    case 0x2F:
      return app::VKEY_HELP;
    case 0x30:
      return app::VKEY_0;
    case 0x31:
      return app::VKEY_1;
    case 0x32:
      return app::VKEY_2;
    case 0x33:
      return app::VKEY_3;
    case 0x34:
      return app::VKEY_4;
    case 0x35:
      return app::VKEY_5;
    case 0x36:
      return app::VKEY_6;
    case 0x37:
      return app::VKEY_7;
    case 0x38:
      return app::VKEY_8;
    case 0x39:
      return app::VKEY_9;
    case 0x41:
      return app::VKEY_A;
    case 0x42:
      return app::VKEY_B;
    case 0x43:
      return app::VKEY_C;
    case 0x44:
      return app::VKEY_D;
    case 0x45:
      return app::VKEY_E;
    case 0x46:
      return app::VKEY_F;
    case 0x47:
      return app::VKEY_G;
    case 0x48:
      return app::VKEY_H;
    case 0x49:
      return app::VKEY_I;
    case 0x4A:
      return app::VKEY_J;
    case 0x4B:
      return app::VKEY_K;
    case 0x4C:
      return app::VKEY_L;
    case 0x4D:
      return app::VKEY_M;
    case 0x4E:
      return app::VKEY_N;
    case 0x4F:
      return app::VKEY_O;
    case 0x50:
      return app::VKEY_P;
    case 0x51:
      return app::VKEY_Q;
    case 0x52:
      return app::VKEY_R;
    case 0x53:
      return app::VKEY_S;
    case 0x54:
      return app::VKEY_T;
    case 0x55:
      return app::VKEY_U;
    case 0x56:
      return app::VKEY_V;
    case 0x57:
      return app::VKEY_W;
    case 0x58:
      return app::VKEY_X;
    case 0x59:
      return app::VKEY_Y;
    case 0x5A:
      return app::VKEY_Z;
    case 0x5B:
      return app::VKEY_LWIN;
    case 0x5C:
      return app::VKEY_RWIN;
    case 0x5D:
      return app::VKEY_APPS;
    case 0x5F:
      return app::VKEY_SLEEP;
    case 0x60:
      return app::VKEY_NUMPAD0;
    case 0x61:
      return app::VKEY_NUMPAD1;
    case 0x62:
      return app::VKEY_NUMPAD2;
    case 0x63:
      return app::VKEY_NUMPAD3;
    case 0x64:
      return app::VKEY_NUMPAD4;
    case 0x65:
      return app::VKEY_NUMPAD5;
    case 0x66:
      return app::VKEY_NUMPAD6;
    case 0x67:
      return app::VKEY_NUMPAD7;
    case 0x68:
      return app::VKEY_NUMPAD8;
    case 0x69:
      return app::VKEY_NUMPAD9;
    case 0x6A:
      return app::VKEY_MULTIPLY;
    case 0x6B:
      return app::VKEY_ADD;
    case 0x6C:
      return app::VKEY_SEPARATOR;
    case 0x6D:
      return app::VKEY_SUBTRACT;
    case 0x6E:
      return app::VKEY_DECIMAL;
    case 0x6F:
      return app::VKEY_DIVIDE;
    case 0x70:
      return app::VKEY_F1;
    case 0x71:
      return app::VKEY_F2;
    case 0x72:
      return app::VKEY_F3;
    case 0x73:
      return app::VKEY_F4;
    case 0x74:
      return app::VKEY_F5;
    case 0x75:
      return app::VKEY_F6;
    case 0x76:
      return app::VKEY_F7;
    case 0x77:
      return app::VKEY_F8;
    case 0x78:
      return app::VKEY_F9;
    case 0x79:
      return app::VKEY_F10;
    case 0x7A:
      return app::VKEY_F11;
    case 0x7B:
      return app::VKEY_F12;
    case 0x7C:
      return app::VKEY_F13;
    case 0x7D:
      return app::VKEY_F14;
    case 0x7E:
      return app::VKEY_F15;
    case 0x7F:
      return app::VKEY_F16;
    case 0x80:
      return app::VKEY_F17;
    case 0x81:
      return app::VKEY_F18;
    case 0x82:
      return app::VKEY_F19;
    case 0x83:
      return app::VKEY_F20;
    case 0x84:
      return app::VKEY_F21;
    case 0x85:
      return app::VKEY_F22;
    case 0x86:
      return app::VKEY_F23;
    case 0x87:
      return app::VKEY_F24;
    case 0x90:
      return app::VKEY_NUMLOCK;
    case 0x91:
      return app::VKEY_SCROLL;
    case 0xA0:
      return app::VKEY_LSHIFT;
    case 0xA1:
      return app::VKEY_RSHIFT;
    case 0xA2:
      return app::VKEY_LCONTROL;
    case 0xA3:
      return app::VKEY_RCONTROL;
    case 0xA4:
      return app::VKEY_LMENU;
    case 0xA5:
      return app::VKEY_RMENU;
    case 0xA6:
      return app::VKEY_BROWSER_BACK;
    case 0xA7:
      return app::VKEY_BROWSER_FORWARD;
    case 0xA8:
      return app::VKEY_BROWSER_REFRESH;
    case 0xA9:
      return app::VKEY_BROWSER_STOP;
    case 0xAA:
      return app::VKEY_BROWSER_SEARCH;
    case 0xAB:
      return app::VKEY_BROWSER_FAVORITES;
    case 0xAC:
      return app::VKEY_BROWSER_HOME;
    case 0xAD:
      return app::VKEY_VOLUME_MUTE;
    case 0xAE:
      return app::VKEY_VOLUME_DOWN;
    case 0xAF:
      return app::VKEY_VOLUME_UP;
    case 0xB0:
      return app::VKEY_MEDIA_NEXT_TRACK;
    case 0xB1:
      return app::VKEY_MEDIA_PREV_TRACK;
    case 0xB2:
      return app::VKEY_MEDIA_STOP;
    case 0xB3:
      return app::VKEY_MEDIA_PLAY_PAUSE;
    case 0xB4:
      return app::VKEY_MEDIA_LAUNCH_MAIL;
    case 0xB5:
      return app::VKEY_MEDIA_LAUNCH_MEDIA_SELECT;
    case 0xB6:
      return app::VKEY_MEDIA_LAUNCH_APP1;
    case 0xB7:
      return app::VKEY_MEDIA_LAUNCH_APP2;
    case 0xBA:
      return app::VKEY_OEM_1;
    case 0xBB:
      return app::VKEY_OEM_PLUS;
    case 0xBC:
      return app::VKEY_OEM_COMMA;
    case 0xBD:
      return app::VKEY_OEM_MINUS;
    case 0xBE:
      return app::VKEY_OEM_PERIOD;
    case 0xBF:
      return app::VKEY_OEM_2;
    case 0xC0:
      return app::VKEY_OEM_3;
    case 0xDB:
      return app::VKEY_OEM_4;
    case 0xDC:
      return app::VKEY_OEM_5;
    case 0xDD:
      return app::VKEY_OEM_6;
    case 0xDE:
      return app::VKEY_OEM_7;
    case 0xDF:
      return app::VKEY_OEM_8;
    case 0xE2:
      return app::VKEY_OEM_102;
    case 0xE5:
      return app::VKEY_PROCESSKEY;
    case 0xE7:
      return app::VKEY_PACKET;
    case 0xF6:
      return app::VKEY_ATTN;
    case 0xF7:
      return app::VKEY_CRSEL;
    case 0xF8:
      return app::VKEY_EXSEL;
    case 0xF9:
      return app::VKEY_EREOF;
    case 0xFA:
      return app::VKEY_PLAY;
    case 0xFB:
      return app::VKEY_ZOOM;
    case 0xFC:
      return app::VKEY_NONAME;
    case 0xFD:
      return app::VKEY_PA1;
    case 0xFE:
      return app::VKEY_OEM_CLEAR;
    default:
      return app::VKEY_UNKNOWN;
  }
}

EventExecutorWin::EventExecutorWin(Capturer* capturer)
  : EventExecutor(capturer) {
}

EventExecutorWin::~EventExecutorWin() {
}

void EventExecutorWin::HandleInputEvent(ChromotingClientMessage* msg) {
  if (msg->has_mouse_set_position_event()) {
    HandleMouseSetPosition(msg);
  } else if (msg->has_mouse_move_event()) {
    HandleMouseMove(msg);
  } else if (msg->has_mouse_wheel_event()) {
    HandleMouseWheel(msg);
  } else if (msg->has_mouse_down_event()) {
    HandleMouseButtonDown(msg);
  } else if (msg->has_mouse_up_event()) {
    HandleMouseButtonUp(msg);
  } else if (msg->has_key_event()) {
    HandleKey(msg);
  }
  delete msg;
}

void EventExecutorWin::HandleMouseSetPosition(ChromotingClientMessage* msg) {
  int x = msg->mouse_set_position_event().x();
  int y = msg->mouse_set_position_event().y();
  int width = msg->mouse_set_position_event().width();
  int height = msg->mouse_set_position_event().height();

  // Get width and height from the capturer if they are missing from the
  // message.
  if (width == 0 || height == 0) {
    width = capturer_->width();
    height = capturer_->height();
  }
  if (width == 0 || height == 0) {
    return;
  }

  INPUT input;
  input.type = INPUT_MOUSE;
  input.mi.time = 0;
  input.mi.dx = static_cast<int>((x * 65535) / width);
  input.mi.dy = static_cast<int>((y * 65535) / height);
  input.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
  SendInput(1, &input, sizeof(INPUT));
}

void EventExecutorWin::HandleMouseMove(ChromotingClientMessage* msg) {
  INPUT input;
  input.type = INPUT_MOUSE;
  input.mi.time = 0;
  input.mi.dx = msg->mouse_move_event().offset_x();
  input.mi.dy = msg->mouse_move_event().offset_y();
  input.mi.dwFlags = MOUSEEVENTF_MOVE;
  SendInput(1, &input, sizeof(INPUT));
}

void EventExecutorWin::HandleMouseWheel(ChromotingClientMessage* msg) {
  INPUT input;
  input.type = INPUT_MOUSE;
  input.mi.time = 0;

  int dx = msg->mouse_wheel_event().offset_x();
  int dy = msg->mouse_wheel_event().offset_y();

  if (dx != 0) {
    input.mi.mouseData = dx;
    input.mi.dwFlags = MOUSEEVENTF_HWHEEL;
    SendInput(1, &input, sizeof(INPUT));
  }
  if (dy != 0) {
    input.mi.mouseData = dy;
    input.mi.dwFlags = MOUSEEVENTF_WHEEL;
    SendInput(1, &input, sizeof(INPUT));
  }
}

void EventExecutorWin::HandleMouseButtonDown(ChromotingClientMessage* msg) {
  INPUT input;
  input.type = INPUT_MOUSE;
  input.mi.time = 0;
  input.mi.dx = 0;
  input.mi.dy = 0;

  MouseButton button = msg->mouse_down_event().button();
  if (button == MouseButtonLeft) {
    input.mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
  } else if (button == MouseButtonMiddle) {
    input.mi.dwFlags = MOUSEEVENTF_MIDDLEDOWN;
  } else if (button == MouseButtonRight) {
    input.mi.dwFlags = MOUSEEVENTF_RIGHTDOWN;
  } else {
    input.mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
  }

  SendInput(1, &input, sizeof(INPUT));
}

void EventExecutorWin::HandleMouseButtonUp(ChromotingClientMessage* msg) {
  INPUT input;
  input.type = INPUT_MOUSE;
  input.mi.time = 0;
  input.mi.dx = 0;
  input.mi.dy = 0;

  MouseButton button = msg->mouse_down_event().button();
  if (button == MouseButtonLeft) {
    input.mi.dwFlags = MOUSEEVENTF_LEFTUP;
  } else if (button == MouseButtonMiddle) {
    input.mi.dwFlags = MOUSEEVENTF_MIDDLEUP;
  } else if (button == MouseButtonRight) {
    input.mi.dwFlags = MOUSEEVENTF_RIGHTUP;
  } else {
    input.mi.dwFlags = MOUSEEVENTF_LEFTUP;
  }

  SendInput(1, &input, sizeof(INPUT));
}

void EventExecutorWin::HandleKey(ChromotingClientMessage* msg) {
  INPUT input;
  input.type = INPUT_KEYBOARD;
  input.ki.time = 0;
  input.ki.wVk = 0;
  input.ki.wScan = msg->key_event().key();
  input.ki.dwFlags = KEYEVENTF_UNICODE;
  if (!msg->key_event().pressed()) {
    input.ki.dwFlags |= KEYEVENTF_KEYUP;
  }

  SendInput(1, &input, sizeof(INPUT));
}

}  // namespace remoting
<commit_msg>Basic client-host key (+ dead key) support for Chromoting (Windows).<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "remoting/host/event_executor_win.h"

#include <windows.h>
#include "app/keyboard_codes.h"
#include "base/stl_util-inl.h"
#include "remoting/host/capturer.h"

namespace remoting {

EventExecutorWin::EventExecutorWin(Capturer* capturer)
  : EventExecutor(capturer) {
}

EventExecutorWin::~EventExecutorWin() {
}

void EventExecutorWin::HandleInputEvent(ChromotingClientMessage* msg) {
  if (msg->has_mouse_set_position_event()) {
    HandleMouseSetPosition(msg);
  } else if (msg->has_mouse_move_event()) {
    HandleMouseMove(msg);
  } else if (msg->has_mouse_wheel_event()) {
    HandleMouseWheel(msg);
  } else if (msg->has_mouse_down_event()) {
    HandleMouseButtonDown(msg);
  } else if (msg->has_mouse_up_event()) {
    HandleMouseButtonUp(msg);
  } else if (msg->has_key_event()) {
    HandleKey(msg);
  }
  delete msg;
}

void EventExecutorWin::HandleMouseSetPosition(ChromotingClientMessage* msg) {
  int x = msg->mouse_set_position_event().x();
  int y = msg->mouse_set_position_event().y();
  int width = msg->mouse_set_position_event().width();
  int height = msg->mouse_set_position_event().height();

  // Get width and height from the capturer if they are missing from the
  // message.
  if (width == 0 || height == 0) {
    width = capturer_->width();
    height = capturer_->height();
  }
  if (width == 0 || height == 0) {
    return;
  }

  INPUT input;
  input.type = INPUT_MOUSE;
  input.mi.time = 0;
  input.mi.dx = static_cast<int>((x * 65535) / width);
  input.mi.dy = static_cast<int>((y * 65535) / height);
  input.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
  SendInput(1, &input, sizeof(INPUT));
}

void EventExecutorWin::HandleMouseMove(ChromotingClientMessage* msg) {
  INPUT input;
  input.type = INPUT_MOUSE;
  input.mi.time = 0;
  input.mi.dx = msg->mouse_move_event().offset_x();
  input.mi.dy = msg->mouse_move_event().offset_y();
  input.mi.dwFlags = MOUSEEVENTF_MOVE;
  SendInput(1, &input, sizeof(INPUT));
}

void EventExecutorWin::HandleMouseWheel(ChromotingClientMessage* msg) {
  INPUT input;
  input.type = INPUT_MOUSE;
  input.mi.time = 0;

  int dx = msg->mouse_wheel_event().offset_x();
  int dy = msg->mouse_wheel_event().offset_y();

  if (dx != 0) {
    input.mi.mouseData = dx;
    input.mi.dwFlags = MOUSEEVENTF_HWHEEL;
    SendInput(1, &input, sizeof(INPUT));
  }
  if (dy != 0) {
    input.mi.mouseData = dy;
    input.mi.dwFlags = MOUSEEVENTF_WHEEL;
    SendInput(1, &input, sizeof(INPUT));
  }
}

void EventExecutorWin::HandleMouseButtonDown(ChromotingClientMessage* msg) {
  INPUT input;
  input.type = INPUT_MOUSE;
  input.mi.time = 0;
  input.mi.dx = 0;
  input.mi.dy = 0;

  MouseButton button = msg->mouse_down_event().button();
  if (button == MouseButtonLeft) {
    input.mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
  } else if (button == MouseButtonMiddle) {
    input.mi.dwFlags = MOUSEEVENTF_MIDDLEDOWN;
  } else if (button == MouseButtonRight) {
    input.mi.dwFlags = MOUSEEVENTF_RIGHTDOWN;
  } else {
    input.mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
  }

  SendInput(1, &input, sizeof(INPUT));
}

void EventExecutorWin::HandleMouseButtonUp(ChromotingClientMessage* msg) {
  INPUT input;
  input.type = INPUT_MOUSE;
  input.mi.time = 0;
  input.mi.dx = 0;
  input.mi.dy = 0;

  MouseButton button = msg->mouse_down_event().button();
  if (button == MouseButtonLeft) {
    input.mi.dwFlags = MOUSEEVENTF_LEFTUP;
  } else if (button == MouseButtonMiddle) {
    input.mi.dwFlags = MOUSEEVENTF_MIDDLEUP;
  } else if (button == MouseButtonRight) {
    input.mi.dwFlags = MOUSEEVENTF_RIGHTUP;
  } else {
    input.mi.dwFlags = MOUSEEVENTF_LEFTUP;
  }

  SendInput(1, &input, sizeof(INPUT));
}

void EventExecutorWin::HandleKey(ChromotingClientMessage* msg) {
  int key = msg->key_event().key();
  bool down = msg->key_event().pressed();

  // Calculate scan code from virtual key.
  HKL hkl = GetKeyboardLayout(0);
  int scan_code = MapVirtualKeyEx(key, MAPVK_VK_TO_VSC_EX, hkl);

  INPUT input;
  input.type = INPUT_KEYBOARD;
  input.ki.time = 0;
  input.ki.wVk = key;
  input.ki.wScan = scan_code;

  // Flag to mark extended 'e0' key scancodes. Without this, the left and
  // right windows keys will not be handled properly (on US keyboard).
  if ((scan_code & 0xFF00) == 0xE000) {
    input.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY;
  }

  // Flag to mark keyup events. Default is keydown.
  if (!down) {
    input.ki.dwFlags |= KEYEVENTF_KEYUP;
  }

  SendInput(1, &input, sizeof(INPUT));
}

}  // namespace remoting
<|endoftext|>


<commit_before>/**
*  Copyright (C) 2015 3D Repo Ltd
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU Affero General Public License as
*  published by the Free Software Foundation, either version 3 of the
*  License, or (at your option) any later version.
*
*  This program 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 Affero General Public License for more details.
*
*  You should have received a copy of the GNU Affero General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <gtest/gtest.h>
#include <cstdlib>
#include <repo/manipulator/modeloptimizer/repo_optimizer_multipart.h>
#include <repo/core/model/bson/repo_bson_factory.h>

using namespace repo::manipulator::modeloptimizer;

TEST(MultipartOptimizer, ConstructorTest)
{
	MultipartOptimizer();
}

TEST(MultipartOptimizer, DeconstructorTest)
{
	auto ptr = new MultipartOptimizer();
	delete ptr;
}

TEST(MultipartOptimizer, ApplyOptimizationTestEmpty)
{
	auto opt = MultipartOptimizer();
	repo::core::model::RepoScene *empty = nullptr;
	repo::core::model::RepoScene *empty2 = new repo::core::model::RepoScene();

	EXPECT_FALSE(opt.apply(empty));
	EXPECT_FALSE(opt.apply(empty2));

	delete empty2;
}

repo::core::model::MeshNode* createRandomMesh(const bool hasUV, const bool isIndependent, const std::vector<repo::lib::RepoUUID> &parent) {
	int nVertices = 10;
	int nFaces = 3;
	std::vector<repo::lib::RepoVector3D> vertices;
	std::vector<repo_face_t> faces;

	for (int i = 0; i < nVertices; ++i) {
		vertices.push_back({std::rand(), std::rand(), std::rand()});
	}

	for (int i = 0; i < nFaces; ++i) {
		repo_face_t face;
		for(int j = 0; j < 3; ++j)
			face.push_back(std::rand() / nVertices);
		faces.push_back(face);
	}

	new repo::core::model::MeshNode(repo::core::model::RepoBSONFactory::makeMeshNode(vertices, faces, {}, {}, parent));
}

TEST(MultipartOptimizer, TestAllMerged)
{
	auto opt = MultipartOptimizer();
	auto root = new repo::core::model::TransformationNode(repo::core::model::RepoBSONFactory::makeTransformationNode());
	auto rootID = root->getSharedID();

	auto nMesh = 3;
	repo::core::model::RepoNodeSet meshes, trans, dummy;
	trans.insert(root);
	for(int i =0; i < nMesh; ++i)
		meshes.insert(createRandomMesh(false, false, {rootID}));

	repo::core::model::RepoScene *scene = new repo::core::model::RepoScene({}, dummy, meshes, dummy, dummy, dummy, trans);
	ASSERT_TRUE(scene->hasRoot(repo::core::model::RepoScene::GraphType::DEFAULT));
	ASSERT_FALSE(scene->hasRoot(repo::core::model::RepoScene::GraphType::OPTIMIZED));

	EXPECT_TRUE(opt.apply(scene));
	EXPECT_TRUE(scene->hasRoot(repo::core::model::RepoScene::GraphType::DEFAULT));
	EXPECT_TRUE(scene->hasRoot(repo::core::model::RepoScene::GraphType::OPTIMIZED));

	EXPECT_EQ(1, scene->getAllMeshes(repo::core::model::RepoScene::GraphType::OPTIMIZED).size());

}
<commit_msg>ISSUE #352 add more tests<commit_after>/**
*  Copyright (C) 2015 3D Repo Ltd
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU Affero General Public License as
*  published by the Free Software Foundation, either version 3 of the
*  License, or (at your option) any later version.
*
*  This program 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 Affero General Public License for more details.
*
*  You should have received a copy of the GNU Affero General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <gtest/gtest.h>
#include <cstdlib>
#include <repo/manipulator/modeloptimizer/repo_optimizer_multipart.h>
#include <repo/core/model/bson/repo_bson_factory.h>

using namespace repo::manipulator::modeloptimizer;

const static repo::core::model::RepoScene::GraphType DEFAULT_GRAPH = repo::core::model::RepoScene::GraphType::DEFAULT;
const static repo::core::model::RepoScene::GraphType OPTIMIZED_GRAPH = repo::core::model::RepoScene::GraphType::OPTIMIZED;

TEST(MultipartOptimizer, ConstructorTest)
{
	MultipartOptimizer();
}

TEST(MultipartOptimizer, DeconstructorTest)
{
	auto ptr = new MultipartOptimizer();
	delete ptr;
}

TEST(MultipartOptimizer, ApplyOptimizationTestEmpty)
{
	auto opt = MultipartOptimizer();
	repo::core::model::RepoScene *empty = nullptr;
	repo::core::model::RepoScene *empty2 = new repo::core::model::RepoScene();

	EXPECT_FALSE(opt.apply(empty));
	EXPECT_FALSE(opt.apply(empty2));

	delete empty2;
}

repo::core::model::MeshNode* createRandomMesh(const bool hasUV, const bool isIndependent, const std::vector<repo::lib::RepoUUID> &parent) {
	int nVertices = 10;
	int nFaces = 3;
	std::vector<repo::lib::RepoVector3D> vertices;
	std::vector<repo_face_t> faces;

	for (int i = 0; i < nVertices; ++i) {
		vertices.push_back({ std::rand(), std::rand(), std::rand() });
	}

	for (int i = 0; i < nFaces; ++i) {
		repo_face_t face;
		for (int j = 0; j < 3; ++j)
			face.push_back(std::rand() / nVertices);
		faces.push_back(face);
	}

	std::vector<repo::lib::RepoVector2D> uvs;
	if (hasUV) {
		for (int i = 0; i < nVertices; ++i) {
			uvs.push_back({ (float)std::rand() / RAND_MAX, (float)std::rand() / RAND_MAX });
		}
	}

	auto mesh = new repo::core::model::MeshNode(repo::core::model::RepoBSONFactory::makeMeshNode(vertices, faces, {}, {}, { uvs }, {}, {}, "mesh",parent));

	if (isIndependent)
		mesh->swap(mesh->cloneAndFlagIndependent());

	return mesh;
}

TEST(MultipartOptimizer, TestAllMerged)
{
	auto opt = MultipartOptimizer();
	auto root = new repo::core::model::TransformationNode(repo::core::model::RepoBSONFactory::makeTransformationNode());
	auto rootID = root->getSharedID();

	auto nMesh = 3;
	repo::core::model::RepoNodeSet meshes, trans, dummy;
	trans.insert(root);
	for(int i =0; i < nMesh; ++i)
		meshes.insert(createRandomMesh(false, false, {rootID}));

	repo::core::model::RepoScene *scene = new repo::core::model::RepoScene({}, dummy, meshes, dummy, dummy, dummy, trans);
	ASSERT_TRUE(scene->hasRoot(DEFAULT_GRAPH));
	ASSERT_FALSE(scene->hasRoot(OPTIMIZED_GRAPH));

	EXPECT_TRUE(opt.apply(scene));
	EXPECT_TRUE(scene->hasRoot(DEFAULT_GRAPH));
	EXPECT_TRUE(scene->hasRoot(OPTIMIZED_GRAPH));

	EXPECT_EQ(1, scene->getAllMeshes(OPTIMIZED_GRAPH).size());

}

TEST(MultipartOptimizer, TestWithIndependent)
{
	auto opt = MultipartOptimizer();
	auto root = new repo::core::model::TransformationNode(repo::core::model::RepoBSONFactory::makeTransformationNode());
	auto rootID = root->getSharedID();

	auto nMesh = 3;
	repo::core::model::RepoNodeSet meshes, trans, dummy;
	trans.insert(root);
	for (int i = 0; i < nMesh; ++i)
		meshes.insert(createRandomMesh(false, i == 1, { rootID }));

	repo::core::model::RepoScene *scene = new repo::core::model::RepoScene({}, dummy, meshes, dummy, dummy, dummy, trans);
	ASSERT_TRUE(scene->hasRoot(DEFAULT_GRAPH));
	ASSERT_FALSE(scene->hasRoot(OPTIMIZED_GRAPH));

	EXPECT_TRUE(opt.apply(scene));
	EXPECT_TRUE(scene->hasRoot(DEFAULT_GRAPH));
	EXPECT_TRUE(scene->hasRoot(OPTIMIZED_GRAPH));

	EXPECT_EQ(2, scene->getAllMeshes(OPTIMIZED_GRAPH).size());

}
<|endoftext|>


<commit_before>#include <iostream>

#include "vtrc-server/vtrc-application.h"
#include "vtrc-server/vtrc-listener-tcp.h"
#include "vtrc-server/vtrc-listener-local.h"

#include "vtrc-common/vtrc-pool-pair.h"
#include "vtrc-common/vtrc-rpc-service-wrapper.h"

#include "protocol/hello.pb.h" /// hello protocol

#include "boost/lexical_cast.hpp"

using namespace vtrc;

namespace {

class  hello_service_impl: public howto::hello_service {

    void send_hello(::google::protobuf::RpcController*  controller,
                    const ::howto::request_message*     request,
                    ::howto::response_message*          response,
                    ::google::protobuf::Closure*        done) /*override*/
    {
        std::ostringstream oss;

        oss << "Hello " << request->name( )
            << " from hello_service_impl::send_hello!";

        response->set_hello( oss.str( ) );
        done->Run( );
    }

public:
    static std::string const &service_name(  )
    {
        return howto::hello_service::descriptor( )->full_name( );
    }

};

class hello_application: public server::application {

    typedef vtrc::shared_ptr<common::rpc_service_wrapper> wrapper_sptr;

public:

    hello_application( vtrc::common::pool_pair &pp )
        :vtrc::server::application(pp)
    { }

    wrapper_sptr get_service_by_name( common::connection_iface* connection,
                                      const std::string &service_name )
    {
        if( service_name == hello_service_impl::service_name( ) ) {

             hello_service_impl *new_impl = new  hello_service_impl;

             return vtrc::make_shared<common::rpc_service_wrapper>( new_impl );

        }
        return wrapper_sptr( );
    }

};

}

int main( int argc, const char **argv )
{
    common::pool_pair pp( 1, 1 );

    hello_application app( pp );

    const char *address = "127.0.0.1";
    unsigned short port = 56560;

    if( argc > 2 ) {
        address = argv[1];
        port = boost::lexical_cast<unsigned short>( argv[2] );
    } else if( argc > 1 ) {
        port = boost::lexical_cast<unsigned short>( argv[1] );
    }

    try {
        vtrc::shared_ptr<server::listener>
                tcp( server::listeners::tcp::create( app, address, port ) );

        tcp->start( );
    } catch( const std::exception &ex ) {
        std::cerr << "Hello, world failed: " << ex.what( ) << "\n";
    }

    pp.join_all( );

    /// make valgrind happy.
    google::protobuf::ShutdownProtobufLibrary( );

    return 0;
}

<commit_msg>proto<commit_after>#include <iostream>

#include "vtrc-server/vtrc-application.h"
#include "vtrc-server/vtrc-listener-tcp.h"
#include "vtrc-server/vtrc-listener-local.h"

#include "vtrc-common/vtrc-connection-iface.h"

#include "vtrc-common/vtrc-pool-pair.h"
#include "vtrc-common/vtrc-rpc-service-wrapper.h"

#include "protocol/hello.pb.h" /// hello protocol

#include "boost/lexical_cast.hpp"

using namespace vtrc;

namespace {

class  hello_service_impl: public howto::hello_service {

    common::connection_iface *cl_;

    void send_hello(::google::protobuf::RpcController*  controller,
                    const ::howto::request_message*     request,
                    ::howto::response_message*          response,
                    ::google::protobuf::Closure*        done) /*override*/
    {
        std::ostringstream oss;

        oss << "Hello " << request->name( )
            << " from hello_service_impl::send_hello!\n"
            << "Your client name is '"
            << cl_->name( ) << "'.\nHave a nice day.";

        response->set_hello( oss.str( ) );
        done->Run( );
    }

public:

    hello_service_impl( common::connection_iface *cl )
        :cl_(cl)
    { }

    static std::string const &service_name(  )
    {
        return howto::hello_service::descriptor( )->full_name( );
    }

};

class hello_application: public server::application {

    typedef vtrc::shared_ptr<common::rpc_service_wrapper> wrapper_sptr;

public:

    hello_application( vtrc::common::pool_pair &pp )
        :vtrc::server::application(pp)
    { }

    wrapper_sptr get_service_by_name( common::connection_iface* connection,
                                      const std::string &service_name )
    {
        if( service_name == hello_service_impl::service_name( ) ) {

             hello_service_impl *new_impl = new hello_service_impl(connection);

             return vtrc::make_shared<common::rpc_service_wrapper>( new_impl );

        }
        return wrapper_sptr( );
    }

};

}

int main( int argc, const char **argv )
{
    common::pool_pair pp( 1, 1 );

    hello_application app( pp );

    const char *address = "127.0.0.1";
    unsigned short port = 56560;

    if( argc > 2 ) {
        address = argv[1];
        port = boost::lexical_cast<unsigned short>( argv[2] );
    } else if( argc > 1 ) {
        port = boost::lexical_cast<unsigned short>( argv[1] );
    }

    try {
        vtrc::shared_ptr<server::listener>
                tcp( server::listeners::tcp::create( app, address, port ) );

        tcp->start( );
    } catch( const std::exception &ex ) {
        std::cerr << "Hello, world failed: " << ex.what( ) << "\n";
    }

    pp.join_all( );

    /// make valgrind happy.
    google::protobuf::ShutdownProtobufLibrary( );

    return 0;
}

<|endoftext|>


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

#include "curlfetch.h"
#include <string>
#include <curl/curl.h>

using std::string;

// CURLOPT_WRITEFUNCTION:
// size*nmemb bytes of data are at ptr, stream is user data
// return must be size*nmemb or curl itself will fail.
static size_t FetchToString(void* ptr, size_t size, size_t nmemb, void* user) {
  // static function, only user is DoCurlToString which uses CURLOPT_WRITEDATA
  // to set the "user" arg which is the C++ string (buffer) to write to.
  assert(user);
  size_t nbytes = size * nmemb;
  string *output_buffer = reinterpret_cast<string*>(user);
  output_buffer->append(reinterpret_cast<char*>(ptr), nbytes);
  return nbytes;
}

// Separate worker function to simplify bool return logic.
static bool DoCurlToString(CURL* curl, const char* url, string* data) {
  CURLcode result;
#define CURLOK(f) (f == CURLE_OK)
  if (CURLOK(curl_easy_setopt(curl, CURLOPT_URL, url)) &&
      CURLOK(curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, FetchToString)) &&
      CURLOK(curl_easy_setopt(curl, CURLOPT_WRITEDATA,
                              reinterpret_cast<void*>(data))) &&
      CURLOK(curl_easy_perform(curl))) {
    return true;
  }
  return false;
}

// Wrapper to manage curl handle.  Very simple stateless implementation.  Less
// simplistic would be to reuse the CURL* handle between invocations.
bool CurlToString(const char* url, string* data) {
  CURL* curl = curl_easy_init();
  bool ret = DoCurlToString(curl, url, data);
  curl_easy_cleanup(curl);
  return ret;
}
<commit_msg>Remove the assert() from curlfetch.cc<commit_after>// Copyright 2008, Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//  1. Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//  3. Neither the name of Google Inc. nor the names of its contributors may be
//     used to endorse or promote products derived from this software without
//     specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "curlfetch.h"
#include <string>
#include <curl/curl.h>

using std::string;

// CURLOPT_WRITEFUNCTION:
// size*nmemb bytes of data are at ptr, stream is user data
// return must be size*nmemb or curl itself will fail.
static size_t FetchToString(void* ptr, size_t size, size_t nmemb, void* user) {
  // static function, only user is DoCurlToString which uses CURLOPT_WRITEDATA
  // to set the "user" arg which is the C++ string (buffer) to write to.
  size_t nbytes = size * nmemb;
  string *output_buffer = reinterpret_cast<string*>(user);
  output_buffer->append(reinterpret_cast<char*>(ptr), nbytes);
  return nbytes;
}

// Separate worker function to simplify bool return logic.
static bool DoCurlToString(CURL* curl, const char* url, string* data) {
  CURLcode result;
#define CURLOK(f) (f == CURLE_OK)
  if (CURLOK(curl_easy_setopt(curl, CURLOPT_URL, url)) &&
      CURLOK(curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, FetchToString)) &&
      CURLOK(curl_easy_setopt(curl, CURLOPT_WRITEDATA,
                              reinterpret_cast<void*>(data))) &&
      CURLOK(curl_easy_perform(curl))) {
    return true;
  }
  return false;
}

// Wrapper to manage curl handle.  Very simple stateless implementation.  Less
// simplistic would be to reuse the CURL* handle between invocations.
bool CurlToString(const char* url, string* data) {
  CURL* curl = curl_easy_init();
  bool ret = DoCurlToString(curl, url, data);
  curl_easy_cleanup(curl);
  return ret;
}
<|endoftext|>


<commit_before>#include <shaderboiler.h>
#include <iostream>

void main()
{
	using namespace sb;
	using namespace sb::gl440;
	using namespace sb::fs;

	{
		context ctx;
		vec4 AmbientColor           = ctx.uniform<vec4>("AmbientColor");
		vec3 normal                 = ctx.in<vec3>("normal");
		vec3 vertex_to_light_vector = ctx.in<vec3>("vertex_to_light_vector");

		array<vec3> lights = ctx.uniform<array<vec3> >("lights[5]");

		array<vec3> lights2(3);

		lights2[0] = vec3(0.0);

		vec3 b = lights2[0];

		// Defining The Material Colors
		const vec4 DiffuseColor = vec4(1.0, 0.0, 0.0, 1.0).SetName("DiffuseColor");

		ivec1 a = gl_MaxProgramTexelOffset;

		// Scaling The Input Vector To Length 1
		//vec3 normalized_normal = normalize(normal);
		vec3 normalized_normal = normal;
		//vec3 normalized_vertex_to_light_vector = normalize(vertex_to_light_vector);
		vec3 normalized_vertex_to_light_vector = vertex_to_light_vector * 2;

		// Calculating The Diffuse Term And Clamping It To [0;1]
		Float DiffuseTerm = max(dot(normal, vertex_to_light_vector), 0.0).SetName("DiffuseTerm");

		// Calculating The Final Color
		ctx[fs::gl_FragColor] = AmbientColor + DiffuseColor * DiffuseTerm;

		std::cout << ctx.genShader();
	}
	std::cout << "Test3" << "\n";

	context ctx;
	vec2 a = ctx.in<vec2>("a");
	vec2 b = ctx.in<vec2>("b");
	vec2 d = ctx.out<vec2>("d");

	vec2 g(1.0f, 2.0f);

	a = 3.0f * (a + b * 1.0f) * g;

	d = a * (a * 1.0f);

	std::cout << ctx.genShader();
}
<commit_msg>Updated example.<commit_after>#include <shaderboiler.h>
#include <iostream>

void main()
{
	using namespace sb;
	using namespace sb::gl440;
	using namespace sb::fs;

	{
		context ctx;
		vec4 AmbientColor           = ctx.uniform<vec4>("AmbientColor");
		vec3 normal                 = ctx.in<vec3>("normal");
		vec3 vertex_to_light_vector = ctx.in<vec3>("vertex_to_light_vector");

		array<vec3> lights = ctx.uniform<array<vec3> >("lights[5]");

		lights[0] = vec3(0.0);

		vec3 b = lights[0];

		// Defining The Material Colors
		const vec4 DiffuseColor = vec4(1.0, 0.0, 0.0, 1.0).SetName("DiffuseColor");

		ivec1 a = gl_MaxProgramTexelOffset;

		// Scaling The Input Vector To Length 1
		//vec3 normalized_normal = normalize(normal);
		vec3 normalized_normal = normal;
		//vec3 normalized_vertex_to_light_vector = normalize(vertex_to_light_vector);
		vec3 normalized_vertex_to_light_vector = vertex_to_light_vector * 2;

		// Calculating The Diffuse Term And Clamping It To [0;1]
		Float DiffuseTerm = max(dot(normal, vertex_to_light_vector + b), 0.0).SetName("DiffuseTerm");

		AmbientColor += DiffuseTerm;

		// Calculating The Final Color
		ctx[fs::gl_FragColor] = AmbientColor + DiffuseColor * DiffuseTerm;

		std::cout << ctx.genShader();
	}
	std::cout << "Test3" << "\n";

	context ctx;
	vec2 a = ctx.in<vec2>("a");
	vec2 b = ctx.in<vec2>("b");
	vec2 d = ctx.out<vec2>("d");

	vec2 g(1.0f, 2.0f);

	a = 3.0f * (a + b * 1.0f) * g;

	d = a * (a * 1.0f);

	std::cout << ctx.genShader();
}
<|endoftext|>


<commit_before>#include <QApplication>
#include <QThread>
#include <QWebPage>
#include <QWebFrame>
#include <QMutexLocker>
#include <QtDebug>
#include "sunscraperinterface.h"
#include "sunscraperlibrary.h"
#include "sunscraperworker.h"

// #define DEBUG_SUNSCRAPERINTERFACE

QMutex SunscraperInterface::m_initializationMutex;
SunscraperInterface *SunscraperInterface::m_instance;

SunscraperInterface::SunscraperInterface() :
        m_nextQueryId(0)
{
    m_worker = new SunscraperWorker();
    m_worker->moveToThread(QApplication::instance()->thread());

    connect(this, SIGNAL(requestLoadHtml(uint,QString,QUrl)),
            m_worker, SLOT(loadHtml(uint,QString,QUrl)), Qt::QueuedConnection);
    connect(this, SIGNAL(requestLoadUrl(uint,QUrl)),
            m_worker, SLOT(loadUrl(uint,QUrl)), Qt::QueuedConnection);
    connect(this, SIGNAL(requestTimeout(uint,uint)),
            m_worker, SLOT(setTimeout(uint,uint)), Qt::QueuedConnection);
    connect(this, SIGNAL(requestFetch(uint)),
            m_worker, SLOT(fetchHtml(uint)), Qt::QueuedConnection);
    connect(this, SIGNAL(requestFinalize(uint)),
            m_worker, SLOT(finalize(uint)), Qt::QueuedConnection);

    connect(m_worker, SIGNAL(finished(uint)),
            this, SLOT(onFinish(uint)), Qt::DirectConnection);
    connect(m_worker, SIGNAL(timedOut(uint)),
            this, SLOT(onTimeout(uint)), Qt::DirectConnection);
    connect(m_worker, SIGNAL(htmlFetched(uint,QString)),
            this, SLOT(onFetchDone(uint,QString)), Qt::DirectConnection);
}

SunscraperInterface *SunscraperInterface::instance()
{
    QMutexLocker locker(&m_initializationMutex);

    if(m_instance == NULL)
        m_instance = new SunscraperInterface();

    return m_instance;
}

void SunscraperInterface::initSemaphore(unsigned queryId)
{
    QMutexLocker locker(&m_semaphoresMutex);

    Q_ASSERT(m_semaphores[queryId] == NULL);

    QSemaphore *semaphore = new QSemaphore(0);
    m_semaphores[queryId] = semaphore;
}

void SunscraperInterface::waitOnSemaphore(unsigned queryId)
{
    m_semaphoresMutex.lock();

    Q_ASSERT(m_semaphores[queryId] != NULL);

    QSemaphore *semaphore = m_semaphores[queryId];

    m_semaphoresMutex.unlock();

    semaphore->acquire(1);

    m_semaphoresMutex.lock();

    delete semaphore;
    m_semaphores.remove(queryId);

    m_semaphoresMutex.unlock();
}

void SunscraperInterface::signalSemaphore(unsigned queryId)
{
    QMutexLocker locker(&m_semaphoresMutex);

    Q_ASSERT(m_semaphores[queryId] != NULL);

    m_semaphores[queryId]->release(1);
}

unsigned SunscraperInterface::createQuery()
{
    QMutexLocker locker(&m_queryIdMutex);

    m_nextQueryId += 1;

#ifdef DEBUG_SUNSCRAPERINTERFACE
    qDebug() << "createQuery" << m_nextQueryId;
#endif

    return m_nextQueryId;
}

void SunscraperInterface::loadHtml(unsigned queryId, QString html, QUrl baseUrl)
{
#ifdef DEBUG_SUNSCRAPERINTERFACE
    qDebug() << "loadHtml" << queryId << html << baseUrl;
#endif

    emit requestLoadHtml(queryId, html, baseUrl);
}

void SunscraperInterface::loadUrl(unsigned queryId, QUrl url)
{
#ifdef DEBUG_SUNSCRAPERINTERFACE
    qDebug() << "loadUrl" << queryId << url;
#endif

    emit requestLoadUrl(queryId, url);
}

bool SunscraperInterface::wait(unsigned queryId, unsigned timeout)
{
#ifdef DEBUG_SUNSCRAPERINTERFACE
    qDebug() << "wait" << queryId << timeout;
#endif

    initSemaphore(queryId);
    emit requestTimeout(queryId, timeout);
    waitOnSemaphore(queryId);

    /* There was either a finish or timeout */

    {
        QMutexLocker locker(&m_resultsMutex);

        bool success = m_results[queryId];
        m_results.remove(queryId);

        return success;
    }
}

void SunscraperInterface::onFinish(unsigned queryId)
{
#ifdef DEBUG_SUNSCRAPERINTERFACE
    qDebug() << "onFinish" << queryId;
#endif

    QMutexLocker locker(&m_resultsMutex);
    m_results[queryId] = true;

    signalSemaphore(queryId);
}

void SunscraperInterface::onTimeout(unsigned queryId)
{
#ifdef DEBUG_SUNSCRAPERINTERFACE
    qDebug() << "onTimeout" << queryId;
#endif

    QMutexLocker locker(&m_resultsMutex);
    m_results[queryId] = false;

    signalSemaphore(queryId);
}

void SunscraperInterface::onFetchDone(unsigned queryId, QString html)
{
#ifdef DEBUG_SUNSCRAPERINTERFACE
    qDebug() << "onFetchDone" << queryId;
#endif

    QMutexLocker locker(&m_resultsMutex);
    m_htmlCache[queryId] = html.toLocal8Bit();

    signalSemaphore(queryId);
}

QByteArray SunscraperInterface::fetch(unsigned queryId)
{
#ifdef DEBUG_SUNSCRAPERINTERFACE
    qDebug() << "fetch" << queryId;
#endif

    initSemaphore(queryId);
    emit requestFetch(queryId);
    waitOnSemaphore(queryId);

    {
        QMutexLocker locker(&m_resultsMutex);
        return m_htmlCache[queryId];
    }
}

void SunscraperInterface::finalize(unsigned queryId)
{
#ifdef DEBUG_SUNSCRAPERINTERFACE
    qDebug() << "finalize" << queryId;
#endif

    emit requestFinalize(queryId);

    QMutexLocker locker(&m_resultsMutex);
    m_results.remove(queryId);
    m_htmlCache.remove(queryId);
}
<commit_msg>Fix another assertion failure.<commit_after>#include <QApplication>
#include <QThread>
#include <QWebPage>
#include <QWebFrame>
#include <QMutexLocker>
#include <QtDebug>
#include "sunscraperinterface.h"
#include "sunscraperlibrary.h"
#include "sunscraperworker.h"

// #define DEBUG_SUNSCRAPERINTERFACE

QMutex SunscraperInterface::m_initializationMutex;
SunscraperInterface *SunscraperInterface::m_instance;

SunscraperInterface::SunscraperInterface() :
        m_nextQueryId(0)
{
    m_worker = new SunscraperWorker();
    m_worker->moveToThread(QApplication::instance()->thread());

    connect(this, SIGNAL(requestLoadHtml(uint,QString,QUrl)),
            m_worker, SLOT(loadHtml(uint,QString,QUrl)), Qt::QueuedConnection);
    connect(this, SIGNAL(requestLoadUrl(uint,QUrl)),
            m_worker, SLOT(loadUrl(uint,QUrl)), Qt::QueuedConnection);
    connect(this, SIGNAL(requestTimeout(uint,uint)),
            m_worker, SLOT(setTimeout(uint,uint)), Qt::QueuedConnection);
    connect(this, SIGNAL(requestFetch(uint)),
            m_worker, SLOT(fetchHtml(uint)), Qt::QueuedConnection);
    connect(this, SIGNAL(requestFinalize(uint)),
            m_worker, SLOT(finalize(uint)), Qt::QueuedConnection);

    connect(m_worker, SIGNAL(finished(uint)),
            this, SLOT(onFinish(uint)), Qt::DirectConnection);
    connect(m_worker, SIGNAL(timedOut(uint)),
            this, SLOT(onTimeout(uint)), Qt::DirectConnection);
    connect(m_worker, SIGNAL(htmlFetched(uint,QString)),
            this, SLOT(onFetchDone(uint,QString)), Qt::DirectConnection);
}

SunscraperInterface *SunscraperInterface::instance()
{
    QMutexLocker locker(&m_initializationMutex);

    if(m_instance == NULL)
        m_instance = new SunscraperInterface();

    return m_instance;
}

void SunscraperInterface::initSemaphore(unsigned queryId)
{
    QMutexLocker locker(&m_semaphoresMutex);

    Q_ASSERT(m_semaphores[queryId] == NULL);

    QSemaphore *semaphore = new QSemaphore(0);
    m_semaphores[queryId] = semaphore;
}

void SunscraperInterface::waitOnSemaphore(unsigned queryId)
{
    m_semaphoresMutex.lock();

    Q_ASSERT(m_semaphores[queryId] != NULL);

    QSemaphore *semaphore = m_semaphores[queryId];

    m_semaphoresMutex.unlock();

    semaphore->acquire(1);

    m_semaphoresMutex.lock();

    delete semaphore;
    m_semaphores.remove(queryId);

    m_semaphoresMutex.unlock();
}

void SunscraperInterface::signalSemaphore(unsigned queryId)
{
    QMutexLocker locker(&m_semaphoresMutex);

    if(m_semaphores.contains(queryId))
        m_semaphores[queryId]->release(1);
}

unsigned SunscraperInterface::createQuery()
{
    QMutexLocker locker(&m_queryIdMutex);

    m_nextQueryId += 1;

#ifdef DEBUG_SUNSCRAPERINTERFACE
    qDebug() << "createQuery" << m_nextQueryId;
#endif

    return m_nextQueryId;
}

void SunscraperInterface::loadHtml(unsigned queryId, QString html, QUrl baseUrl)
{
#ifdef DEBUG_SUNSCRAPERINTERFACE
    qDebug() << "loadHtml" << queryId << html << baseUrl;
#endif

    emit requestLoadHtml(queryId, html, baseUrl);
}

void SunscraperInterface::loadUrl(unsigned queryId, QUrl url)
{
#ifdef DEBUG_SUNSCRAPERINTERFACE
    qDebug() << "loadUrl" << queryId << url;
#endif

    emit requestLoadUrl(queryId, url);
}

bool SunscraperInterface::wait(unsigned queryId, unsigned timeout)
{
#ifdef DEBUG_SUNSCRAPERINTERFACE
    qDebug() << "wait" << queryId << timeout;
#endif

    initSemaphore(queryId);
    emit requestTimeout(queryId, timeout);
    waitOnSemaphore(queryId);

    /* There was either a finish or timeout */

    {
        QMutexLocker locker(&m_resultsMutex);

        bool success = m_results[queryId];
        m_results.remove(queryId);

        return success;
    }
}

void SunscraperInterface::onFinish(unsigned queryId)
{
#ifdef DEBUG_SUNSCRAPERINTERFACE
    qDebug() << "onFinish" << queryId;
#endif

    QMutexLocker locker(&m_resultsMutex);
    m_results[queryId] = true;

    signalSemaphore(queryId);
}

void SunscraperInterface::onTimeout(unsigned queryId)
{
#ifdef DEBUG_SUNSCRAPERINTERFACE
    qDebug() << "onTimeout" << queryId;
#endif

    QMutexLocker locker(&m_resultsMutex);
    m_results[queryId] = false;

    signalSemaphore(queryId);
}

void SunscraperInterface::onFetchDone(unsigned queryId, QString html)
{
#ifdef DEBUG_SUNSCRAPERINTERFACE
    qDebug() << "onFetchDone" << queryId;
#endif

    QMutexLocker locker(&m_resultsMutex);
    m_htmlCache[queryId] = html.toLocal8Bit();

    signalSemaphore(queryId);
}

QByteArray SunscraperInterface::fetch(unsigned queryId)
{
#ifdef DEBUG_SUNSCRAPERINTERFACE
    qDebug() << "fetch" << queryId;
#endif

    initSemaphore(queryId);
    emit requestFetch(queryId);
    waitOnSemaphore(queryId);

    {
        QMutexLocker locker(&m_resultsMutex);
        return m_htmlCache[queryId];
    }
}

void SunscraperInterface::finalize(unsigned queryId)
{
#ifdef DEBUG_SUNSCRAPERINTERFACE
    qDebug() << "finalize" << queryId;
#endif

    emit requestFinalize(queryId);

    QMutexLocker locker(&m_resultsMutex);
    m_results.remove(queryId);
    m_htmlCache.remove(queryId);
}
<|endoftext|>


<commit_before>
#include "io/idemowriter.h"
#include "io/demoreader.h"
#include <cstdio>
#include <string>
#include <cassert>

std::string GetExtension(const std::string& filename)
{
    size_t index = filename.find_last_of(".");
    if (index != std::string::npos)
    {
        return filename.substr(index + 1);
    }
    return std::string();
}

enum class FileType
{
    None,
    Dem,
    Json,
    ConLog
};

FileType GetFileType(const std::string& filename)
{
    std::string ext = GetExtension(filename);
    if (ext == "dem")
    {
        return FileType::Dem;
    }
    if (ext == "json")
    {
        return FileType::Json;
    }
    if (ext == "con")
    {
        return FileType::ConLog;
    }
    return FileType::None;
}

int main(const int argc, const char* argv[])
{
    if (argc != 3)
    {
        fprintf(stderr, "Usage: %s <in>.dem/json <out>.dem/json/con\n", argv[0]);
        return -1;
    }

    std::string inputFile(argv[1]);
    std::string outputFile(argv[2]);

    FileType inputType = GetFileType(inputFile);
    FileType outputType = GetFileType(outputFile);
    if (inputType == FileType::None)
    {
        fprintf(stderr, "Error: Bad type for input file\n");
        return -1;
    }
    if (outputType == FileType::None)
    {
        fprintf(stderr, "Error: Bad type for output file\n");
        return -1;
    }

    FILE* inputFp = fopen(inputFile.c_str(), "rb");
    if (!inputFp)
    {
        fprintf(stderr, "Error: Could not open input file\n");
        return -1;
    }

    FILE* outputFp = fopen(outputFile.c_str(), "wb");
    if (!outputFp)
    {
        fprintf(stderr, "Error: Could not open input file\n");
        fclose(inputFp);
        return -1;
    }

    IDemoWriter* writer = nullptr;
    if (outputType == FileType::Dem)
    {
        writer = IDemoWriter::CreateDemoWriter(outputFp);
    }
    else if (outputType == FileType::Json)
    {
        writer = IDemoWriter::CreateJsonWriter(outputFp);
    }
    else if (outputType == FileType::ConLog)
    {
        writer = IDemoWriter::CreateConLogWriter(outputFp);
    }
    else
    {
        assert(false);
    }

    if (inputType == FileType::Dem)
    {
        DemoReader::ProcessDem(inputFp, writer);
    }
    else if (inputType == FileType::Json)
    {
        DemoReader::ProcessJson(inputFp, writer);
    }
    else
    {
        assert(false);
    }
    IDemoWriter::FreeDemoWriter(writer);

    fclose(inputFp);
    fclose(outputFp);
    return 0;
}
<commit_msg>Added verification for json output<commit_after>
#include "io/idemowriter.h"
#include "io/demoreader.h"
#include "json_checker/JSON_checker.h"
#include <cstdio>
#include <string>
#include <cassert>

std::string GetExtension(const std::string& filename)
{
    size_t index = filename.find_last_of(".");
    if (index != std::string::npos)
    {
        return filename.substr(index + 1);
    }
    return std::string();
}

enum class FileType
{
    None,
    Dem,
    Json,
    ConLog
};

FileType GetFileType(const std::string& filename)
{
    std::string ext = GetExtension(filename);
    if (ext == "dem")
    {
        return FileType::Dem;
    }
    if (ext == "json")
    {
        return FileType::Json;
    }
    if (ext == "con")
    {
        return FileType::ConLog;
    }
    return FileType::None;
}

int main(const int argc, const char* argv[])
{
    if (argc != 3)
    {
        fprintf(stderr, "Usage: %s <in>.dem/json <out>.dem/json/con\n", argv[0]);
        return -1;
    }

    std::string inputFile(argv[1]);
    std::string outputFile(argv[2]);

    FileType inputType = GetFileType(inputFile);
    FileType outputType = GetFileType(outputFile);
    if (inputType == FileType::None)
    {
        fprintf(stderr, "Error: Bad type for input file\n");
        return -1;
    }
    if (outputType == FileType::None)
    {
        fprintf(stderr, "Error: Bad type for output file\n");
        return -1;
    }

    FILE* inputFp = fopen(inputFile.c_str(), "rb");
    if (!inputFp)
    {
        fprintf(stderr, "Error: Could not open input file\n");
        return -1;
    }

    FILE* outputFp = fopen(outputFile.c_str(), "wb");
    if (!outputFp)
    {
        fprintf(stderr, "Error: Could not open input file\n");
        fclose(inputFp);
        return -1;
    }

    IDemoWriter* writer = nullptr;
    if (outputType == FileType::Dem)
    {
        writer = IDemoWriter::CreateDemoWriter(outputFp);
    }
    else if (outputType == FileType::Json)
    {
        writer = IDemoWriter::CreateJsonWriter(outputFp);
    }
    else if (outputType == FileType::ConLog)
    {
        writer = IDemoWriter::CreateConLogWriter(outputFp);
    }
    else
    {
        assert(false);
    }

    if (inputType == FileType::Dem)
    {
        DemoReader::ProcessDem(inputFp, writer);
    }
    else if (inputType == FileType::Json)
    {
        DemoReader::ProcessJson(inputFp, writer);
    }
    else
    {
        assert(false);
    }
    IDemoWriter::FreeDemoWriter(writer);

    fclose(inputFp);
    fclose(outputFp);

    if (outputType == FileType::Json)
    {
        FILE* outputFp = fopen(outputFile.c_str(), "rb");
        JSON_checker jc = new_JSON_checker(20);
        int next_char = 0;
        while ((next_char = fgetc(outputFp)) > 0)
        {
            if (!JSON_checker_char(jc, next_char))
            {
                fprintf(stderr, "JSON_checker_char: syntax error\n");
            }
        }
        if (!JSON_checker_done(jc))
        {
            fprintf(stderr, "JSON_checker_end: syntax error\n");
        }
        fclose(outputFp);
    }
    return 0;
}
<|endoftext|>


<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_CONTAINER_FACTORY_EIGEN_HH
#define DUNE_DETAILED_DISCRETIZATIONS_CONTAINER_FACTORY_EIGEN_HH

#ifdef HAVE_EIGEN

// system
#include <vector>
#include <set>

// dune-common
#include <dune/common/shared_ptr.hh>

// local
#include "../backend/container/eigen.hh"

namespace Dune {

namespace Detailed {

namespace Discretizations {

namespace LA {

namespace Factory {

template <class EntryType>
class Eigen
{
public:
  typedef Dune::Detailed::Discretizations::LA::Backend::Container::Eigen::SparseMatrix<EntryType> SparseMatrixType;

  typedef Dune::Detailed::Discretizations::LA::Backend::Container::Eigen::DenseMatrix<EntryType> DenseMatrixType;

  typedef Dune::Detailed::Discretizations::LA::Backend::Container::Eigen::DenseVector<EntryType> DenseVectorType;

  template <class AnsatzSpaceType, class TestSpaceType>
  static SparseMatrixType createSparseMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace)
  {
    // init
    SparseMatrixType matrix(ansatzSpace.map().size(), testSpace.map().size());
    std::vector<std::set<unsigned int>> pattern(ansatzSpace.map().size());

    // generate sparsity pattern
    typedef typename AnsatzSpaceType::GridPartType::template Codim<0>::IteratorType IteratorType;
    IteratorType itEnd = ansatzSpace.gridPart().template end<0>();
    for (IteratorType it = ansatzSpace.gridPart().template begin<0>(); it != itEnd; ++it) {
      typename AnsatzSpaceType::GridPartType::template Codim<0>::IteratorType::Entity& entity = *it;
      for (unsigned int i = 0; i < ansatzSpace.baseFunctionSet().local(entity).size(); ++i) {
        for (unsigned int j = 0; j < testSpace.baseFunctionSet().local(entity).size(); ++j) {
          const unsigned int globalI = ansatzSpace.map().toGlobal(entity, i);
          const unsigned int globalJ = testSpace.map().toGlobal(entity, j);
          pattern[globalI].insert(globalJ);
        }
      }
    } // generate sparsity pattern

    // tell pattern to matrix
    for (unsigned int row = 0; row < ansatzSpace.map().size(); ++row) {
      matrix.storage()->startVec(row);
      for (typename std::set<unsigned int>::iterator it = pattern[row].begin(); it != pattern[row].end(); ++it) {
        unsigned int column = *it;
        matrix.storage()->insertBackByOuterInner(row, column);
      }
    } // tell pattern to matrix

    // finalize matrix
    matrix.storage()->finalize();
    matrix.storage()->makeCompressed();

    // return
    return matrix;
  }

  template <class AnsatzSpaceType, class TestSpaceType>
  static DenseMatrixType createDenseMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace)
  {
    // init
    DenseMatrixType matrix(ansatzSpace.map().size(), testSpace.map().size());
    // reserve
    matrix.reserve();
    // return
    return matrix;
  }

  template <class SpaceType>
  static DenseVectorType createDenseVector(const SpaceType& space)
  {
    // init
    DenseVectorType vector(space.map().size());
    // reserve
    vector.reserve();
    // return
    return vector;
  }
}; // class Eigen

} // namespace Factory

} // namespace LA

} // namespace Discretizations

} // namespace Detailed

} // namespace Dune

#endif // HAVE_EIGEN

#endif // DUNE_DETAILED_DISCRETIZATIONS_CONTAINER_FACTORY_EIGEN_HH
<commit_msg>[dune.detailed.discretizations.la.factory.eigen] added methods to generate matrices and vectors without the need for spaces<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_CONTAINER_FACTORY_EIGEN_HH
#define DUNE_DETAILED_DISCRETIZATIONS_CONTAINER_FACTORY_EIGEN_HH

//#ifdef HAVE_EIGEN

// system
#include <vector>
#include <set>

// dune-common
#include <dune/common/shared_ptr.hh>

// local
#include "../backend/container/eigen.hh"

namespace Dune {

namespace Detailed {

namespace Discretizations {

namespace LA {

namespace Factory {

template <class EntryType>
class Eigen
{
public:
  typedef Dune::Detailed::Discretizations::LA::Backend::Container::Eigen::SparseMatrix<EntryType> SparseMatrixType;

  typedef Dune::Detailed::Discretizations::LA::Backend::Container::Eigen::DenseMatrix<EntryType> DenseMatrixType;

  typedef Dune::Detailed::Discretizations::LA::Backend::Container::Eigen::DenseVector<EntryType> DenseVectorType;

  typedef std::map<unsigned int, std::set<unsigned int>> PatternType;

  template <class AnsatzSpaceType, class TestSpaceType>
  static SparseMatrixType createSparseMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace)
  {
    // generate sparsity pattern
    const PatternType pattern = ansatzSpace.computePattern(testSpace);
    return createSparseMatrix(ansatzSpace.map().size(), testSpace.map().size(), pattern);
  } // static SparseMatrixType createSparseMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace)

  static SparseMatrixType createSparseMatrix(const unsigned int rows, const unsigned int cols,
                                             const PatternType& pattern)
  {
    // init
    SparseMatrixType matrix(rows, cols);

    // tell pattern to matrix
    for (typename PatternType::const_iterator rowSet = pattern.begin(); rowSet != pattern.end(); ++rowSet) {
      const unsigned int row                   = rowSet->first;
      const std::set<unsigned int>& rowEntries = rowSet->second;
      matrix.storage()->startVec(row);
      for (typename std::set<unsigned int>::iterator rowEntry = rowEntries.begin(); rowEntry != rowEntries.end();
           ++rowEntry) {
        unsigned int column = *rowEntry;
        matrix.storage()->insertBackByOuterInner(row, column);
      }
    } // tell pattern to matrix

    // finalize matrix
    matrix.storage()->finalize();
    matrix.storage()->makeCompressed();

    // return
    return matrix;
  } // static SparseMatrixType createSparseMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace)

  template <class AnsatzSpaceType, class TestSpaceType>
  static DenseMatrixType createDenseMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace)
  {
    return createDenseMatrix(ansatzSpace.map().size(), testSpace.map().size());
  }

  static DenseMatrixType createDenseMatrix(const unsigned int rows, const unsigned int cols)
  {
    // init
    DenseMatrixType matrix(rows, cols);
    // reserve
    matrix.reserve();
    // return
    return matrix;
  } // static DenseMatrixType createDenseMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace)

  template <class SpaceType>
  static DenseVectorType createDenseVector(const SpaceType& space)
  {
    return createDenseVector(space.map().size());
  }

  static DenseVectorType createDenseVector(const unsigned int size)
  {
    // init
    DenseVectorType vector(size);
    // reserve
    vector.reserve();
    // return
    return vector;
  } // static DenseVectorType createDenseVector(const SpaceType& space)
}; // class Eigen

} // namespace Factory

} // namespace LA

} // namespace Discretizations

} // namespace Detailed

} // namespace Dune

//#endif // HAVE_EIGEN

#endif // DUNE_DETAILED_DISCRETIZATIONS_CONTAINER_FACTORY_EIGEN_HH
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS ooo19126 (1.2.124); FILE MERGED 2005/09/05 14:00:55 rt 1.2.124.1: #i54170# Change license header: remove SISSL<commit_after><|endoftext|>