<commit_before>#pragma once

// `krbn::hid_observer` can be used safely in a multi-threaded environment.

#include "boost_utility.hpp"
#include "human_interface_device.hpp"
#include "logger.hpp"
#include "thread_utility.hpp"

namespace krbn {
class hid_observer final {
public:
  // Signals

  boost::signals2::signal<void(std::shared_ptr<human_interface_device>)> device_observed;
  boost::signals2::signal<void(std::shared_ptr<human_interface_device>)> device_unobserved;

  // Methods

  hid_observer(const hid_observer&) = delete;

  hid_observer(std::shared_ptr<human_interface_device> human_interface_device) : human_interface_device_(human_interface_device),
                                                                                observed_(false) {
    queue_ = std::make_shared<thread_utility::queue>();

    // opened
    {
      auto c = human_interface_device->opened.connect([this] {
        queue_->push_back([this] {
          if (auto hid = human_interface_device_.lock()) {
            observed_ = true;

            device_observed(hid);

            hid->async_queue_start();
            hid->async_schedule();
          }
        });
      });
      human_interface_device_connections_.push_back(c);
    }

    // open_failed
    {
      auto c = human_interface_device->open_failed.connect([this](auto&& error) {
        queue_->push_back([this, error] {
          if (auto hid = human_interface_device_.lock()) {
            auto message = fmt::format("IOHIDDeviceOpen error: {0} ({1}) {2}",
                                       iokit_utility::get_error_name(error),
                                       error,
                                       hid->get_name_for_log());
            logger_unique_filter_.error(message);
          }
        });
      });
      human_interface_device_connections_.push_back(c);
    }

    // closed
    {
      auto c = human_interface_device->closed.connect([this] {
        queue_->push_back([this] {
          if (auto hid = human_interface_device_.lock()) {
            device_unobserved(hid);
          }
        });
      });
      human_interface_device_connections_.push_back(c);
    }

    // close_failed
    {
      auto c = human_interface_device->close_failed.connect([this](auto&& error) {
        queue_->push_back([this, error] {
          if (auto hid = human_interface_device_.lock()) {
            auto message = fmt::format("IOHIDDeviceClose error: {0} ({1}) {2}",
                                       iokit_utility::get_error_name(error),
                                       error,
                                       hid->get_name_for_log());
            logger_unique_filter_.error(message);

            device_unobserved(hid);
          }
        });
      });
      human_interface_device_connections_.push_back(c);
    }
  }

  ~hid_observer(void) {
    async_unobserve();

    // Disconnect `human_interface_device_connections_`

    if (auto hid = human_interface_device_.lock()) {
      hid->get_run_loop_thread()->enqueue(^{
        human_interface_device_connections_.disconnect_all_connections();
      });
    } else {
      human_interface_device_connections_.disconnect_all_connections();
    }

    human_interface_device_connections_.wait_disconnect_all_connections();

    // Release `queue_`

    queue_ = nullptr;
  }

  std::weak_ptr<human_interface_device> get_human_interface_device(void) {
    return human_interface_device_;
  }

  void async_observe(void) {
    std::lock_guard<std::mutex> lock(timer_mutex_);

    if (timer_) {
      return;
    }

    logger_unique_filter_.reset();

    timer_ = std::make_unique<thread_utility::timer>(
        [](auto&& count) {
          if (count == 0) {
            return std::chrono::milliseconds(0);
          } else {
            return std::chrono::milliseconds(3000);
          }
        },
        true,
        [this] {
          queue_->push_back([this] {
            if (!observed_) {
              if (auto hid = human_interface_device_.lock()) {
                if (!hid->get_removed()) {
                  hid->async_open();
                  return;
                }
              }
            }

            timer_->unset_repeats();
          });
        });
  }

  void async_unobserve(void) {
    {
      std::lock_guard<std::mutex> lock(timer_mutex_);

      if (!timer_) {
        return;
      }

      timer_ = nullptr;
    }

    queue_->push_back([this] {
      if (observed_) {
        if (auto hid = human_interface_device_.lock()) {
          hid->async_unschedule();
          hid->async_queue_stop();
          hid->async_close();
        }

        observed_ = false;
      }
    });
  }

private:
  std::shared_ptr<thread_utility::queue> queue_;
  std::weak_ptr<human_interface_device> human_interface_device_;
  boost_utility::signals2_connections human_interface_device_connections_;
  bool observed_;
  logger::unique_filter logger_unique_filter_;

  std::unique_ptr<thread_utility::timer> timer_;
  mutable std::mutex timer_mutex_;
};
} // namespace krbn
<commit_msg>use unique_ptr for queue_<commit_after>#pragma once

// `krbn::hid_observer` can be used safely in a multi-threaded environment.

#include "boost_utility.hpp"
#include "human_interface_device.hpp"
#include "logger.hpp"
#include "thread_utility.hpp"

namespace krbn {
class hid_observer final {
public:
  // Signals

  boost::signals2::signal<void(std::shared_ptr<human_interface_device>)> device_observed;
  boost::signals2::signal<void(std::shared_ptr<human_interface_device>)> device_unobserved;

  // Methods

  hid_observer(const hid_observer&) = delete;

  hid_observer(std::shared_ptr<human_interface_device> human_interface_device) : human_interface_device_(human_interface_device),
                                                                                observed_(false) {
    queue_ = std::make_unique<thread_utility::queue>();

    // opened
    {
      auto c = human_interface_device->opened.connect([this] {
        queue_->push_back([this] {
          if (auto hid = human_interface_device_.lock()) {
            observed_ = true;

            device_observed(hid);

            hid->async_queue_start();
            hid->async_schedule();
          }
        });
      });
      human_interface_device_connections_.push_back(c);
    }

    // open_failed
    {
      auto c = human_interface_device->open_failed.connect([this](auto&& error) {
        queue_->push_back([this, error] {
          if (auto hid = human_interface_device_.lock()) {
            auto message = fmt::format("IOHIDDeviceOpen error: {0} ({1}) {2}",
                                       iokit_utility::get_error_name(error),
                                       error,
                                       hid->get_name_for_log());
            logger_unique_filter_.error(message);
          }
        });
      });
      human_interface_device_connections_.push_back(c);
    }

    // closed
    {
      auto c = human_interface_device->closed.connect([this] {
        queue_->push_back([this] {
          if (auto hid = human_interface_device_.lock()) {
            device_unobserved(hid);
          }
        });
      });
      human_interface_device_connections_.push_back(c);
    }

    // close_failed
    {
      auto c = human_interface_device->close_failed.connect([this](auto&& error) {
        queue_->push_back([this, error] {
          if (auto hid = human_interface_device_.lock()) {
            auto message = fmt::format("IOHIDDeviceClose error: {0} ({1}) {2}",
                                       iokit_utility::get_error_name(error),
                                       error,
                                       hid->get_name_for_log());
            logger_unique_filter_.error(message);

            device_unobserved(hid);
          }
        });
      });
      human_interface_device_connections_.push_back(c);
    }
  }

  ~hid_observer(void) {
    async_unobserve();

    // Disconnect `human_interface_device_connections_`

    if (auto hid = human_interface_device_.lock()) {
      hid->get_run_loop_thread()->enqueue(^{
        human_interface_device_connections_.disconnect_all_connections();
      });
    } else {
      human_interface_device_connections_.disconnect_all_connections();
    }

    human_interface_device_connections_.wait_disconnect_all_connections();

    // Release `queue_`

    queue_ = nullptr;
  }

  std::weak_ptr<human_interface_device> get_human_interface_device(void) {
    return human_interface_device_;
  }

  void async_observe(void) {
    std::lock_guard<std::mutex> lock(timer_mutex_);

    if (timer_) {
      return;
    }

    logger_unique_filter_.reset();

    timer_ = std::make_unique<thread_utility::timer>(
        [](auto&& count) {
          if (count == 0) {
            return std::chrono::milliseconds(0);
          } else {
            return std::chrono::milliseconds(3000);
          }
        },
        true,
        [this] {
          queue_->push_back([this] {
            if (!observed_) {
              if (auto hid = human_interface_device_.lock()) {
                if (!hid->get_removed()) {
                  hid->async_open();
                  return;
                }
              }
            }

            timer_->unset_repeats();
          });
        });
  }

  void async_unobserve(void) {
    {
      std::lock_guard<std::mutex> lock(timer_mutex_);

      if (!timer_) {
        return;
      }

      timer_ = nullptr;
    }

    queue_->push_back([this] {
      if (observed_) {
        if (auto hid = human_interface_device_.lock()) {
          hid->async_unschedule();
          hid->async_queue_stop();
          hid->async_close();
        }

        observed_ = false;
      }
    });
  }

private:
  std::unique_ptr<thread_utility::queue> queue_;
  std::weak_ptr<human_interface_device> human_interface_device_;
  boost_utility::signals2_connections human_interface_device_connections_;
  bool observed_;
  logger::unique_filter logger_unique_filter_;

  std::unique_ptr<thread_utility::timer> timer_;
  mutable std::mutex timer_mutex_;
};
} // namespace krbn
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2006, 2007 Apple Computer, Inc.
 * Copyright (c) 2006, 2007, 2008, 2009, 2012 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:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * 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.
 *     * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "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 COPYRIGHT
 * OWNER OR CONTRIBUTORS 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 "config.h"
#include "core/platform/graphics/FontCache.h"

#include "SkFontMgr.h"
#include "SkTypeface_win.h"
#include "core/platform/NotImplemented.h"
#include "core/platform/graphics/Font.h"
#include "core/platform/graphics/SimpleFontData.h"
#include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
#include "core/platform/graphics/chromium/FontUtilsChromiumWin.h"

namespace WebCore {

FontCache::FontCache()
    : m_purgePreventCount(0)
{
    m_fontManager = adoptPtr(SkFontMgr_New_GDI());
}

static bool fontContainsCharacter(const FontPlatformData* fontData, const wchar_t* family, UChar32 character)
{
    SkPaint paint;
    fontData->setupPaint(&paint);
    paint.setTextEncoding(SkPaint::kUTF32_TextEncoding);

    uint16_t glyph;
    paint.textToGlyphs(&character, sizeof(character), &glyph);
    return glyph != 0;
}

// Given the desired base font, this will create a SimpleFontData for a specific
// font that can be used to render the given range of characters.
PassRefPtr<SimpleFontData> FontCache::getFontDataForCharacter(const Font& font, UChar32 inputC)
{
    // FIXME: We should fix getFallbackFamily to take a UChar32
    // and remove this split-to-UChar16 code.
    UChar codeUnits[2];
    int codeUnitsLength;
    if (inputC <= 0xFFFF) {
        codeUnits[0] = inputC;
        codeUnitsLength = 1;
    } else {
        codeUnits[0] = U16_LEAD(inputC);
        codeUnits[1] = U16_TRAIL(inputC);
        codeUnitsLength = 2;
    }

    // FIXME: Consider passing fontDescription.dominantScript()
    // to GetFallbackFamily here.
    FontDescription fontDescription = font.fontDescription();
    UChar32 c;
    UScriptCode script;
    const wchar_t* family = getFallbackFamily(codeUnits, codeUnitsLength, fontDescription.genericFamily(), &c, &script);
    FontPlatformData* data = 0;
    if (family)
        data = getFontResourcePlatformData(font.fontDescription(),  AtomicString(family, wcslen(family)), false);

    // Last resort font list : PanUnicode. CJK fonts have a pretty
    // large repertoire. Eventually, we need to scan all the fonts
    // on the system to have a Firefox-like coverage.
    // Make sure that all of them are lowercased.
    const static wchar_t* const cjkFonts[] = {
        L"arial unicode ms",
        L"ms pgothic",
        L"simsun",
        L"gulim",
        L"pmingliu",
        L"wenquanyi zen hei", // Partial CJK Ext. A coverage but more widely known to Chinese users.
        L"ar pl shanheisun uni",
        L"ar pl zenkai uni",
        L"han nom a", // Complete CJK Ext. A coverage.
        L"code2000" // Complete CJK Ext. A coverage.
        // CJK Ext. B fonts are not listed here because it's of no use
        // with our current non-BMP character handling because we use
        // Uniscribe for it and that code path does not go through here.
    };

    const static wchar_t* const commonFonts[] = {
        L"tahoma",
        L"arial unicode ms",
        L"lucida sans unicode",
        L"microsoft sans serif",
        L"palatino linotype",
        // Six fonts below (and code2000 at the end) are not from MS, but
        // once installed, cover a very wide range of characters.
        L"dejavu serif",
        L"dejavu sasns",
        L"freeserif",
        L"freesans",
        L"gentium",
        L"gentiumalt",
        L"ms pgothic",
        L"simsun",
        L"gulim",
        L"pmingliu",
        L"code2000"
    };

    const wchar_t* const* panUniFonts = 0;
    int numFonts = 0;
    if (script == USCRIPT_HAN) {
        panUniFonts = cjkFonts;
        numFonts = WTF_ARRAY_LENGTH(cjkFonts);
    } else {
        panUniFonts = commonFonts;
        numFonts = WTF_ARRAY_LENGTH(commonFonts);
    }
    // Font returned from GetFallbackFamily may not cover |characters|
    // because it's based on script to font mapping. This problem is
    // critical enough for non-Latin scripts (especially Han) to
    // warrant an additional (real coverage) check with fontCotainsCharacter.
    int i;
    for (i = 0; (!data || !fontContainsCharacter(data, family, c)) && i < numFonts; ++i) {
        family = panUniFonts[i];
        data = getFontResourcePlatformData(font.fontDescription(), AtomicString(family, wcslen(family)));
    }
    // When i-th font (0-base) in |panUniFonts| contains a character and
    // we get out of the loop, |i| will be |i + 1|. That is, if only the
    // last font in the array covers the character, |i| will be numFonts.
    // So, we have to use '<=" rather than '<' to see if we found a font
    // covering the character.
    if (i <= numFonts)
        return getFontResourceData(data, DoNotRetain);

    return 0;
}

static bool typefacesMatchesFamily(const SkTypeface* tf, const AtomicString& family)
{
    SkTypeface::LocalizedStrings* actualFamilies = tf->createFamilyNameIterator();
    bool matchesRequestedFamily = false;
    SkTypeface::LocalizedString actualFamily;

    while (actualFamilies->next(&actualFamily)) {
        if (equalIgnoringCase(family, actualFamily.fString.c_str())) {
            matchesRequestedFamily = true;
            break;
        }
    }
    actualFamilies->unref();

    return matchesRequestedFamily;
}

FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const AtomicString& family)
{
    CString name;
    SkTypeface* tf = createTypeface(fontDescription, family, name);
    if (!tf)
        return 0;

    // Windows will always give us a valid pointer here, even if the face name
    // is non-existent. We have to double-check and see if the family name was
    // really used.
    // FIXME: Do we need to use predefined fonts "guaranteed" to exist
    // when we're running in layout-test mode?
    if (!typefacesMatchesFamily(tf, family)) {
        tf->unref();
        return 0;
    }

    FontPlatformData* result = new FontPlatformData(tf,
        name.data(),
        fontDescription.computedSize(),
        fontDescription.weight() >= FontWeightBold && !tf->isBold(),
        fontDescription.italic() && !tf->isItalic(),
        fontDescription.orientation());
    tf->unref();
    return result;
}

}
<commit_msg>Fix typefacesMatchesFamily to treat family string as UTF8<commit_after>/*
 * Copyright (C) 2006, 2007 Apple Computer, Inc.
 * Copyright (c) 2006, 2007, 2008, 2009, 2012 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:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * 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.
 *     * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "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 COPYRIGHT
 * OWNER OR CONTRIBUTORS 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 "config.h"
#include "core/platform/graphics/FontCache.h"

#include "SkFontMgr.h"
#include "SkTypeface_win.h"
#include "core/platform/NotImplemented.h"
#include "core/platform/graphics/Font.h"
#include "core/platform/graphics/SimpleFontData.h"
#include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
#include "core/platform/graphics/chromium/FontUtilsChromiumWin.h"

namespace WebCore {

FontCache::FontCache()
    : m_purgePreventCount(0)
{
    m_fontManager = adoptPtr(SkFontMgr_New_GDI());
}

static bool fontContainsCharacter(const FontPlatformData* fontData, const wchar_t* family, UChar32 character)
{
    SkPaint paint;
    fontData->setupPaint(&paint);
    paint.setTextEncoding(SkPaint::kUTF32_TextEncoding);

    uint16_t glyph;
    paint.textToGlyphs(&character, sizeof(character), &glyph);
    return glyph != 0;
}

// Given the desired base font, this will create a SimpleFontData for a specific
// font that can be used to render the given range of characters.
PassRefPtr<SimpleFontData> FontCache::getFontDataForCharacter(const Font& font, UChar32 inputC)
{
    // FIXME: We should fix getFallbackFamily to take a UChar32
    // and remove this split-to-UChar16 code.
    UChar codeUnits[2];
    int codeUnitsLength;
    if (inputC <= 0xFFFF) {
        codeUnits[0] = inputC;
        codeUnitsLength = 1;
    } else {
        codeUnits[0] = U16_LEAD(inputC);
        codeUnits[1] = U16_TRAIL(inputC);
        codeUnitsLength = 2;
    }

    // FIXME: Consider passing fontDescription.dominantScript()
    // to GetFallbackFamily here.
    FontDescription fontDescription = font.fontDescription();
    UChar32 c;
    UScriptCode script;
    const wchar_t* family = getFallbackFamily(codeUnits, codeUnitsLength, fontDescription.genericFamily(), &c, &script);
    FontPlatformData* data = 0;
    if (family)
        data = getFontResourcePlatformData(font.fontDescription(),  AtomicString(family, wcslen(family)), false);

    // Last resort font list : PanUnicode. CJK fonts have a pretty
    // large repertoire. Eventually, we need to scan all the fonts
    // on the system to have a Firefox-like coverage.
    // Make sure that all of them are lowercased.
    const static wchar_t* const cjkFonts[] = {
        L"arial unicode ms",
        L"ms pgothic",
        L"simsun",
        L"gulim",
        L"pmingliu",
        L"wenquanyi zen hei", // Partial CJK Ext. A coverage but more widely known to Chinese users.
        L"ar pl shanheisun uni",
        L"ar pl zenkai uni",
        L"han nom a", // Complete CJK Ext. A coverage.
        L"code2000" // Complete CJK Ext. A coverage.
        // CJK Ext. B fonts are not listed here because it's of no use
        // with our current non-BMP character handling because we use
        // Uniscribe for it and that code path does not go through here.
    };

    const static wchar_t* const commonFonts[] = {
        L"tahoma",
        L"arial unicode ms",
        L"lucida sans unicode",
        L"microsoft sans serif",
        L"palatino linotype",
        // Six fonts below (and code2000 at the end) are not from MS, but
        // once installed, cover a very wide range of characters.
        L"dejavu serif",
        L"dejavu sasns",
        L"freeserif",
        L"freesans",
        L"gentium",
        L"gentiumalt",
        L"ms pgothic",
        L"simsun",
        L"gulim",
        L"pmingliu",
        L"code2000"
    };

    const wchar_t* const* panUniFonts = 0;
    int numFonts = 0;
    if (script == USCRIPT_HAN) {
        panUniFonts = cjkFonts;
        numFonts = WTF_ARRAY_LENGTH(cjkFonts);
    } else {
        panUniFonts = commonFonts;
        numFonts = WTF_ARRAY_LENGTH(commonFonts);
    }
    // Font returned from GetFallbackFamily may not cover |characters|
    // because it's based on script to font mapping. This problem is
    // critical enough for non-Latin scripts (especially Han) to
    // warrant an additional (real coverage) check with fontCotainsCharacter.
    int i;
    for (i = 0; (!data || !fontContainsCharacter(data, family, c)) && i < numFonts; ++i) {
        family = panUniFonts[i];
        data = getFontResourcePlatformData(font.fontDescription(), AtomicString(family, wcslen(family)));
    }
    // When i-th font (0-base) in |panUniFonts| contains a character and
    // we get out of the loop, |i| will be |i + 1|. That is, if only the
    // last font in the array covers the character, |i| will be numFonts.
    // So, we have to use '<=" rather than '<' to see if we found a font
    // covering the character.
    if (i <= numFonts)
        return getFontResourceData(data, DoNotRetain);

    return 0;
}

static bool typefacesMatchesFamily(const SkTypeface* tf, const AtomicString& family)
{
    SkTypeface::LocalizedStrings* actualFamilies = tf->createFamilyNameIterator();
    bool matchesRequestedFamily = false;
    SkTypeface::LocalizedString actualFamily;

    while (actualFamilies->next(&actualFamily)) {
        if (equalIgnoringCase(family, AtomicString::fromUTF8(actualFamily.fString.c_str()))) {
            matchesRequestedFamily = true;
            break;
        }
    }
    actualFamilies->unref();

    return matchesRequestedFamily;
}

FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const AtomicString& family)
{
    CString name;
    SkTypeface* tf = createTypeface(fontDescription, family, name);
    if (!tf)
        return 0;

    // Windows will always give us a valid pointer here, even if the face name
    // is non-existent. We have to double-check and see if the family name was
    // really used.
    // FIXME: Do we need to use predefined fonts "guaranteed" to exist
    // when we're running in layout-test mode?
    if (!typefacesMatchesFamily(tf, family)) {
        tf->unref();
        return 0;
    }

    FontPlatformData* result = new FontPlatformData(tf,
        name.data(),
        fontDescription.computedSize(),
        fontDescription.weight() >= FontWeightBold && !tf->isBold(),
        fontDescription.italic() && !tf->isItalic(),
        fontDescription.orientation());
    tf->unref();
    return result;
}

}
<|endoftext|>


<commit_before>/*
    MIT License

    Copyright (c) 2018 namreeb http://github.com/namreeb legal@namreeb.org

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.

*/

#include "NotifyIconMgr.hpp"
#include "NotifyIcon.hpp"

#include <Windows.h>
#include <stdexcept>
#include <tchar.h>
#include <thread>
#include <mutex>
#include <memory>

namespace
{
static constexpr TCHAR className[] = _T("WowreebWindowClass");
static NotifyIconMgr *singleton = nullptr;

LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    // first offer the message to our handler
    if (!!singleton)
    {
        if (msg == WM_COMMAND && wParam >= WM_APP)
        {
            auto iconId = (wParam & ~WM_APP) >> NotifyIcon::MenuBits;
            auto menuId = (wParam & ((1 << NotifyIcon::MenuBits) - 1));

            if (singleton->Command(hWnd, iconId, menuId))
                return TRUE;
        }
        else if (msg >= WM_APP)
        {
            if (singleton->WindowProc(hWnd, msg - WM_APP, wParam, lParam))
                return TRUE;
        }
    }

    return DefWindowProc(hWnd, msg, wParam, lParam);
}
}

NotifyIconMgr::NotifyIconMgr(HINSTANCE hInstance) : _shutdown(false), _messageThread(&NotifyIconMgr::MessageLoop, this, hInstance)
{
    if (!!singleton)
        throw std::runtime_error("Cannot instantiate more than one NotifyIconMgr");

    WNDCLASS wc;

    ZeroMemory(&wc, sizeof(wc));

    wc.lpfnWndProc = ::WindowProc;
    wc.hInstance = hInstance;
    wc.lpszClassName = className;

    if (!RegisterClass(&wc))
        throw std::runtime_error("Failed to register window class");

    singleton = this;
}

void NotifyIconMgr::MessageLoop(HINSTANCE hInstance)
{
    auto window = ::CreateWindow(className, nullptr, 0, 0, 0, 0, 0, nullptr, nullptr, hInstance, nullptr);

    if (!window)
        throw std::runtime_error("CreateWindow failed");

    do
    {
        MSG msg;

        if (PeekMessage(&msg, window, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        // only lock the mutex for as long as necessary
        {
            std::lock_guard<std::mutex> guard(_mutex);

            for (auto const &i : _pending)
                _icons.emplace_back(std::make_shared<NotifyIcon>(window, static_cast<unsigned int>(_icons.size()), i.first, i.second));

            _pending.clear();
        }

        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    } while (!_shutdown);

    {
        std::lock_guard<std::mutex> guard(_mutex);
        _icons.clear();
    }
}

bool NotifyIconMgr::Command(HWND hWnd, unsigned int iconId, unsigned int menuId)
{
    std::shared_ptr<NotifyIcon> icon;

    // this function can recursively call itself so we need to unlock the mutex as soon as possible
    {
        std::lock_guard<std::mutex> guard(_mutex);

        if (iconId >= _icons.size() || !_icons[iconId])
            return false;

        icon = _icons[iconId];
    }

    icon->ClickMenu(menuId);

    return false;
}

bool NotifyIconMgr::WindowProc(HWND hWnd, unsigned int iconId, WPARAM wParam, LPARAM lParam)
{
    std::shared_ptr<NotifyIcon> icon;

    // this function can recursively call itself so we need to unlock the mutex as soon as possible
    {
        std::lock_guard<std::mutex> guard(_mutex);

        if (iconId >= _icons.size() || !_icons[iconId])
            return false;

        icon = _icons[iconId];
    }

    switch (lParam)
    {
        case WM_RBUTTONDOWN:
        case WM_LBUTTONDOWN:
        {
            icon->ToggleMenu();
            return true;
        }
    }

    return false;
}

std::shared_ptr<NotifyIcon> NotifyIconMgr::Create(HICON icon, const TCHAR *tip)
{
    size_t idx;

    {
        // these must be created in the same thread which owns the window, which is the event processing thread
        std::lock_guard<std::mutex> guard(_mutex);

        _pending.emplace_back(icon, tip);

        idx = _icons.size() + _pending.size() - 1;
    }

    // monitor for the creation of this icon so we can return it
    do
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(5));

        std::lock_guard<std::mutex> guard(_mutex);

        if (_icons.size() > idx)
            return _icons[idx];
    } while (true);
}<commit_msg>Fixed race condition on window creation<commit_after>/*
    MIT License

    Copyright (c) 2018 namreeb http://github.com/namreeb legal@namreeb.org

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.

*/

#include "NotifyIconMgr.hpp"
#include "NotifyIcon.hpp"

#include <Windows.h>
#include <stdexcept>
#include <tchar.h>
#include <thread>
#include <mutex>
#include <memory>
#include <sstream>

namespace
{
static constexpr TCHAR className[] = _T("WowreebWindowClass");
static NotifyIconMgr *singleton = nullptr;

LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    // first offer the message to our handler
    if (!!singleton)
    {
        if (msg == WM_COMMAND && wParam >= WM_APP)
        {
            auto iconId = (wParam & ~WM_APP) >> NotifyIcon::MenuBits;
            auto menuId = (wParam & ((1 << NotifyIcon::MenuBits) - 1));

            if (singleton->Command(hWnd, iconId, menuId))
                return TRUE;
        }
        else if (msg >= WM_APP)
        {
            if (singleton->WindowProc(hWnd, msg - WM_APP, wParam, lParam))
                return TRUE;
        }
    }

    return DefWindowProc(hWnd, msg, wParam, lParam);
}
}

NotifyIconMgr::NotifyIconMgr(HINSTANCE hInstance) : _shutdown(false), _messageThread(&NotifyIconMgr::MessageLoop, this, hInstance)
{
    if (!!singleton)
        throw std::runtime_error("Cannot instantiate more than one NotifyIconMgr");

    singleton = this;
}

void NotifyIconMgr::MessageLoop(HINSTANCE hInstance)
{
    WNDCLASS wc;

    ZeroMemory(&wc, sizeof(wc));

    wc.lpfnWndProc = ::WindowProc;
    wc.hInstance = hInstance;
    wc.lpszClassName = className;

    if (!RegisterClass(&wc))
        throw std::runtime_error("Failed to register window class");

    auto window = ::CreateWindow(className, nullptr, 0, 0, 0, 0, 0, nullptr, nullptr, hInstance, nullptr);

    if (!window)
    {
        std::stringstream str;

        str << "Error number = " << ::GetLastError();
        MessageBoxA(nullptr, str.str().c_str(), "CreateWindow() failed", MB_ICONERROR);
        return;
    }

    do
    {
        MSG msg;

        if (PeekMessage(&msg, window, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        // only lock the mutex for as long as necessary
        {
            std::lock_guard<std::mutex> guard(_mutex);

            for (auto const &i : _pending)
                _icons.emplace_back(std::make_shared<NotifyIcon>(window, static_cast<unsigned int>(_icons.size()), i.first, i.second));

            _pending.clear();
        }

        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    } while (!_shutdown);

    {
        std::lock_guard<std::mutex> guard(_mutex);
        _icons.clear();
    }
}

bool NotifyIconMgr::Command(HWND hWnd, unsigned int iconId, unsigned int menuId)
{
    std::shared_ptr<NotifyIcon> icon;

    // this function can recursively call itself so we need to unlock the mutex as soon as possible
    {
        std::lock_guard<std::mutex> guard(_mutex);

        if (iconId >= _icons.size() || !_icons[iconId])
            return false;

        icon = _icons[iconId];
    }

    icon->ClickMenu(menuId);

    return false;
}

bool NotifyIconMgr::WindowProc(HWND hWnd, unsigned int iconId, WPARAM wParam, LPARAM lParam)
{
    std::shared_ptr<NotifyIcon> icon;

    // this function can recursively call itself so we need to unlock the mutex as soon as possible
    {
        std::lock_guard<std::mutex> guard(_mutex);

        if (iconId >= _icons.size() || !_icons[iconId])
            return false;

        icon = _icons[iconId];
    }

    switch (lParam)
    {
        case WM_RBUTTONDOWN:
        case WM_LBUTTONDOWN:
        {
            icon->ToggleMenu();
            return true;
        }
    }

    return false;
}

std::shared_ptr<NotifyIcon> NotifyIconMgr::Create(HICON icon, const TCHAR *tip)
{
    size_t idx;

    {
        // these must be created in the same thread which owns the window, which is the event processing thread
        std::lock_guard<std::mutex> guard(_mutex);

        _pending.emplace_back(icon, tip);

        idx = _icons.size() + _pending.size() - 1;
    }

    // monitor for the creation of this icon so we can return it
    do
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(5));

        std::lock_guard<std::mutex> guard(_mutex);

        if (_icons.size() > idx)
            return _icons[idx];
    } while (true);
}<|endoftext|>


<commit_before>
#include <QtCore>
#include <QtQml>
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQuickImageProvider>
#include <QScreen>

#ifdef Q_OS_ANDROID
#include <QAndroidJniObject>
#endif

#include "src/website_backend/gumboparserimpl.h"
#include "src/qml_backend/useravatarimageprovider.h"
#include "src/qml_backend/forumreader.h"

// FIXME: save full post history to the LOCAL database
// FIXME: add sorting by user/post reputation option
// FIXME: add abitity to assign a note string to each forum user (e.g. "useless one")

int getDpi(float& textScaleFactor)
{
    QScreen* screen = qApp->primaryScreen();

    qreal dpi = 0;
#if defined(Q_OS_WIN)
    dpi = screen->logicalDotsPerInch() * qApp->devicePixelRatio();
#elif defined(Q_OS_ANDROID)
    QAndroidJniObject qtActivity = QAndroidJniObject::callStaticObjectMethod(
                "org/qtproject/qt5/android/QtNative",
                "activity",
                "()Landroid/app/Activity;");
    QAndroidJniObject resources = qtActivity.callObjectMethod(
                "getResources",
                "()Landroid/content/res/Resources;");
    QAndroidJniObject displayMetrics = resources.callObjectMethod(
                "getDisplayMetrics",
                "()Landroid/util/DisplayMetrics;");
    int density = displayMetrics.getField<int>("densityDpi");
    dpi = density;

    float scaledDensity = displayMetrics.getField<float>("scaledDensity");
    textScaleFactor = scaledDensity;
#else
    dpi = screen->physicalDotsPerInch() * qApp->devicePixelRatio();
#endif
    return dpi;
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    qmlRegisterType<ForumReader>("ru.banki.reader", 1, 0, "ForumReader");

    QQmlApplicationEngine engine;

    float textScaleFactor = 0.0f;
    int displayDpi = getDpi(textScaleFactor);
    engine.rootContext()->setContextProperty("displayDpi", displayDpi);
    engine.rootContext()->setContextProperty("textScaleFactor", textScaleFactor);

	engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}
<commit_msg>Compilation warning fixed<commit_after>
#include <QtCore>
#include <QtQml>
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQuickImageProvider>
#include <QScreen>

#ifdef Q_OS_ANDROID
#include <QAndroidJniObject>
#endif

#include "src/website_backend/gumboparserimpl.h"
#include "src/qml_backend/useravatarimageprovider.h"
#include "src/qml_backend/forumreader.h"

// FIXME: save full post history to the LOCAL database
// FIXME: add sorting by user/post reputation option
// FIXME: add abitity to assign a note string to each forum user (e.g. "useless one")

int getDpi(float& textScaleFactor)
{
    QScreen* screen = qApp->primaryScreen();

    qreal dpi = 0;
#if defined(Q_OS_WIN)
    dpi = screen->logicalDotsPerInch() * qApp->devicePixelRatio();
#elif defined(Q_OS_ANDROID)
    Q_UNUSED(screen);

    QAndroidJniObject qtActivity = QAndroidJniObject::callStaticObjectMethod(
                "org/qtproject/qt5/android/QtNative",
                "activity",
                "()Landroid/app/Activity;");
    QAndroidJniObject resources = qtActivity.callObjectMethod(
                "getResources",
                "()Landroid/content/res/Resources;");
    QAndroidJniObject displayMetrics = resources.callObjectMethod(
                "getDisplayMetrics",
                "()Landroid/util/DisplayMetrics;");
    int density = displayMetrics.getField<int>("densityDpi");
    dpi = density;

    float scaledDensity = displayMetrics.getField<float>("scaledDensity");
    textScaleFactor = scaledDensity;
#else
    dpi = screen->physicalDotsPerInch() * qApp->devicePixelRatio();
#endif
    return dpi;
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    qmlRegisterType<ForumReader>("ru.banki.reader", 1, 0, "ForumReader");

    QQmlApplicationEngine engine;

    float textScaleFactor = 0.0f;
    int displayDpi = getDpi(textScaleFactor);
    engine.rootContext()->setContextProperty("displayDpi", displayDpi);
    engine.rootContext()->setContextProperty("textScaleFactor", textScaleFactor);

	engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}
<|endoftext|>


<commit_before>a45836e3-2747-11e6-a0db-e0f84713e7b8<commit_msg>lets try again<commit_after>a46a9ae6-2747-11e6-8714-e0f84713e7b8<|endoftext|>


<commit_before>8ab45938-4b02-11e5-b9a5-28cfe9171a43<commit_msg>Put the thingie in the thingie<commit_after>8ac1f87d-4b02-11e5-9923-28cfe9171a43<|endoftext|>


<commit_before>7e5deb21-4b02-11e5-909c-28cfe9171a43<commit_msg>bug fix<commit_after>7e69b9c0-4b02-11e5-a4c9-28cfe9171a43<|endoftext|>


<commit_before>#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>

#define O_BINARY 0
const int RECORD_SIZE = 8 * 1024;

size_t get_file_size(const char *);

int main(int argc, char **argv)
{
	// required for argument parsing
	int fflag = 0;
	int c;
	const char * def_filename = "device-file";
	char * filename;
	extern char *optarg;
	extern int optind;
	static char usage[] = "usage: %s -f filename\n";

	// permanent values
	int num_records, file_size;

	while ((c = getopt(argc, argv, "f:")) != -1)
	{
		switch (c)
		{
			case 'f':
				filename = optarg;
				fflag = 1;
				break;
			default:
				// implement other options, such as help, etc.
				break;
		}
	}

	if (fflag == 0)
	{
		// need to implement default filename
	}

    file_size = (int) get_file_size(filename);
    num_records = file_size / RECORD_SIZE;

    std::cout << "File range is 0 to " << file_size << "." << std::endl;

    std::cout << "Number of possible records: " << num_records << std::endl;

    return 0;
}

// https://www.securecoding.cert.org/confluence/display/c/FIO19-C.+Do+not+use+fseek()+and+ftell()+to+compute+the+size+of+a+regular+file

size_t get_file_size(const char * filename)
{
	size_t file_size;
	char *buffer;
	struct stat stbuf;
	int fd;

	fd = open(filename, O_BINARY);
	if (fd == -1)
	{
  		/* Handle error */
	}

	if ((fstat(fd, &stbuf) != 0) || (!S_ISREG(stbuf.st_mode)))
	{
		/* Handle error */
	}

	file_size = stbuf.st_size;

	buffer = (char*)malloc(file_size);
	if (buffer == NULL) {
		/* Handle error */
	}

 	return file_size;
}<commit_msg>stupid line break<commit_after>#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>

#define O_BINARY 0
const int RECORD_SIZE = 8 * 1024;

size_t get_file_size(const char *);

int main(int argc, char **argv)
{
	// required for argument parsing
	int fflag = 0;
	int c;
	const char * def_filename = "device-file";
	char * filename;
	extern char *optarg;
	extern int optind;
	static char usage[] = "usage: %s -f filename\n";

	// permanent values
	int num_records, file_size;

	while ((c = getopt(argc, argv, "f:")) != -1)
	{
		switch (c)
		{
			case 'f':
				filename = optarg;
				fflag = 1;
				break;
			default:
				// implement other options, such as help, etc.
				break;
		}
	}

	if (fflag == 0)
	{
		// need to implement default filename
	}

    file_size = (int) get_file_size(filename);
    num_records = file_size / RECORD_SIZE;

    std::cout << "File range is 0 to " << file_size << "." << std::endl;

    std::cout << "Number of possible records: " << num_records << std::endl;

    return 0;
}

// https://www.securecoding.cert.org/confluence/display/c/FIO19-C.+Do+not+use+fseek()+and+ftell()+to+compute+the+size+of+a+regular+file

size_t get_file_size(const char * filename)
{
	size_t file_size;
	char *buffer;
	struct stat stbuf;
	int fd;

	fd = open(filename, O_BINARY);
	if (fd == -1)
	{
  		/* Handle error */
	}

	if ((fstat(fd, &stbuf) != 0) || (!S_ISREG(stbuf.st_mode)))
	{
		/* Handle error */
	}

	file_size = stbuf.st_size;

	buffer = (char*)malloc(file_size);
	if (buffer == NULL) {
		/* Handle error */
	}

 	return file_size;
}<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include <functional>

using namespace std;

vector<string> split(const string& str) {
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

using RoomID = int;

struct RoomObject
{
	vector<string> names;
	string description;
	bool visible;
};

struct Map
{
	static const int max_width = 100, max_height = 100;
	static const int player_start_x = 50, player_start_y = 50;
    enum Location
    {
		UNKNOWN,
		GRAVEYARD,
		GRAVEYARD_GATES,
		KHATHARRS_MOMS_HOUSE,
		GATES_OF_SHOGUN,
		HOUSE_OF_BLUES,
		FOGGY_FOREST
    };
	Location map_location[max_width][max_height];
	int x, y;
	Map()
	{
        memset(map_location, UNKNOWN, sizeof(map_location));
		x = 50;
		y = 50;
		map_location[50][50] = GRAVEYARD;
		map_location[50][51] = GRAVEYARD_GATES;
		map_location[50][52] = KHATHARRS_MOMS_HOUSE;
		map_location[50][52] = GATES_OF_SHOGUN;
		map_location[50][53] = HOUSE_OF_BLUES;
		map_location[50][54] = FOGGY_FOREST;
	}
};

struct Entity
{
    Entity(string name, int maxHealth) : name(name), health(maxHealth) {}

    void heal(int points)
    {
        health = min(100, health + points);
        cout << name << " healed to " << health << " health" << endl;
    }

    void damage(int points)
    {
        health = max(0, health - points);
        cout << name << " damaged to " << health << "health" << endl;
    }

    int getHealth() const { return health; }

    // Return false if the entity didn't know the command
    virtual bool act(vector<string> commands) = 0;

    string name;
    Map map;

private:
    int health;
};

struct Shogun : public Entity {
  Shogun() : Entity("Shogibear", 100) {}
};

struct Item
{
    virtual void apply(Entity* entity) = 0;
    virtual string identify() const = 0;
};

struct HealthItem : public Item
{
    HealthItem(int healPower) : healPower(healPower) {}

    void apply(Entity* entity) override
    {
        entity->heal(healPower);
    }

    string identify() const override
    {
        stringstream ss;
        ss << "Health Potion (" << healPower << ")";
        return ss.str();
    }

private:
    int healPower;
};
struct BlessedSword : public Item
{
    BlessedSword(int Weapon) : Weapon(Weapon){}
void apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";}
private: int Weapon;};//will add this to entity on my next commit. <.<

/*
struct ReallyFastSword : public Item
struct TheFastcall : public Entity
{
    TheFastcall() : Entity("The Fastcall", 22) {}
    virtual bool act(vector<string> commands) override
    {
    }
};
*/

typedef bool (*actionHandlerBYEBYENAMECOLLISION)(vector<string> commands); // unused, but we can't technically delete this, and commenting it out is just cheating.

struct Player : public Entity
{
    Player(string name, int health) : Entity(name, health) {}

    virtual bool act(vector<string> commands) override
    {
        auto cmd = commands[0];
        if(cmd == "n") { commands = vector<string>{"go","north"}; }
        if(cmd == "s") { commands = vector<string>{"go","south"}; }
        if(cmd == "e") { commands = vector<string>{"go","east"}; }
        if(cmd == "w") { commands = vector<string>{"go","west"}; }

        if (commands.size() >= 1 && commands[0] == "look")
        {
            look();
            return true;
        }
        else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
        {
        }
        else if (commands.size() >= 2 && commands[0] == "go")
        {
            if (travel(commands[1]) == true)
            {
                look();
            } else {
                cout << "Can't travel " << commands[1] << endl;
            }
            return true;
        }
        else if (commands.size() >= 1 && commands[0] == "items")
        {
            showItems();
            return true;
        }
        else if (commands.size() >= 2 && commands[0] == "use")
        {
            int index = stoi(commands[1]);
            useItem(index);
            return true;
        }

        return false;
    }

    bool travel(string direction)
    {
		if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
			return false;
		if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
			return false;
		if ((direction == "north"&&map.map_location[map.x][map.y + 1] == Map::UNKNOWN) || (direction == "south"&&map.map_location[map.x][map.y - 1] == Map::UNKNOWN) || (direction == "east"&&map.map_location[map.x + 1][map.y] == Map::UNKNOWN)||(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN))return false;
		if (direction == "north")map.y++; if (direction == "south")map.y--; if (direction == "east")map.x++; if (direction == "west")map.x--;
        return true;/*
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                if (direction == "north")
                {
					map.y++;
                    return true;
                }
                break;
            case Map::GRAVEYARD_GATES:
                if (direction == "south")
                {
					map.y--;
                    return true;
                }
                if (direction == "north")
                {
                    map.y++;
                    return true;
                }
                break;
        }

        cout << "Can't travel " << direction << endl;
        return false;*/
    }

    void look()
    {
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
                break;
            case Map::GRAVEYARD_GATES:
                cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
                break;
			case Map::GATES_OF_SHOGUN:
				cout << "Here lies the Gates of the Great Shogun. Creator of A1 weaponry; able to fork stakes by a mere glare. It is said that to look into his eyes is to see your future covered in darkness. As you notice the thick red stains which cover the gates, you are reminded of the villagers' tales of sacrifices hung from these very gates. The gate has no lock. Do you enter?" << endl;
				break;
			case Map::HOUSE_OF_BLUES:
				cout << "This is a place where men shed tears and pour out emotion! Of course, after 2 or 3 pints of the finest ale. The miscreants who frequent cavernous house know the warmth of beds not their own. Doors sing with laughter and a timely cry or two. Will you enter to find love?" << endl;
				break;
			case Map::FOGGY_FOREST:
				cout << "Not much is known about this forest. Only that a wolf howls 3 times in the night, every night. And those who enter have never been known to return. Do you risk your life for adventure?" << endl;
				break;
        }
    }

    void giveItem(shared_ptr<Item> item)
    {
        inventory.push_back(item);
    }

    void showItems()
    {
        if (inventory.size() == 0)
            cout << "You have no items." << endl;
        int i = 1;
        for (auto item : inventory)
        {
            cout << "  " << i++ << ". " << item->identify() << std::endl;
        }
    }

    void useItem(size_t index)
    {
        if (index > inventory.size())
        {
            cout << "Invalid index" << endl;
            return;
        }

        inventory[index-1]->apply(this);
        inventory.erase(inventory.begin() + index - 1);
    }

private:
    vector<shared_ptr<Item>> inventory;
    unordered_map<string, function<bool(vector<string>)>> actions;
};

struct Room {
	string describe() {
    stringstream ss;
    ss << description << "\n";
    ss << "Entities: "; for(auto& ent : entities) { ss << ent->name << ", "; }; ss << "\n"; //make this look nice later
    ss << "Items: "; for(auto& obj : objects) { ss << obj.names[0] << ", "; }; ss << "\n";  //make this look nice later
    ss << "Obvious exits: "; for(auto kv : exits) { ss << kv.first << ", "; } ss << "\n"; //...
		return ss.str();
	}
	string description;
	vector<unique_ptr<Entity>> entities;
	vector<RoomObject> objects;
	unordered_map<string, RoomID> exits;
};

class Adventure
{
public:
    void begin()
    {
        string command;
        cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
        cout << "> ";
        getline(cin, command);

        Player player(command, 100);
        player.giveItem(make_shared<HealthItem>(20));

        cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
        player.look();

        while (player.getHealth() > 0)
        {
            cout << "> ";
            getline(cin, command);
            if (player.act(split(command)) == false)
                cout << "Unknown command" << endl;
        }

        cout << "You died. Game over." << endl;
    }
};

int main()
{
    Adventure adventure;
    adventure.begin();
    return 0;
}
<commit_msg>Added dialogue to the new locations.<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include <functional>

using namespace std;

vector<string> split(const string& str) {
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

using RoomID = int;

struct RoomObject
{
	vector<string> names;
	string description;
	bool visible;
};

struct Map
{
	static const int max_width = 100, max_height = 100;
	static const int player_start_x = 50, player_start_y = 50;
        enum Location
        {
	UNKNOWN,
	GRAVEYARD,
	GRAVEYARD_GATES,
	KHATHARRS_MOMS_HOUSE,
	GATES_OF_SHOGUN,
	HOUSE_OF_BLUES,
	FOGGY_FOREST
        };
	Location map_location[max_width][max_height];
	int x, y;
	Map()
	{
        memset(map_location, UNKNOWN, sizeof(map_location));
	x = 50;
	y = 50;
	/*map_location[50][50] = GRAVEYARD;
	map_location[50][51] = GRAVEYARD_GATES;
	map_location[50][52] = KHATHARRS_MOMS_HOUSE;
	map_location[50][52] = GATES_OF_SHOGUN;
	map_location[50][53] = HOUSE_OF_BLUES;
	map_location[50][54] = FOGGY_FOREST;*/
	}
};

struct Entity
{
    Entity(string name, int maxHealth) : name(name), health(maxHealth) {}

    void heal(int points)
    {
        health = min(100, health + points);
        cout << name << " healed to " << health << " health" << endl;
    }

    void damage(int points)
    {
        health = max(0, health - points);
        cout << name << " damaged to " << health << "health" << endl;
    }

    int getHealth() const { return health; }

    // Return false if the entity didn't know the command
    virtual bool act(vector<string> commands) = 0;

    string name;
    Map map;

private:
    int health;
};

struct Shogun : public Entity {
  Shogun() : Entity("Shogibear", 100) {}
};

struct Item
{
    virtual void apply(Entity* entity) = 0;
    virtual string identify() const = 0;
};

struct HealthItem : public Item
{
    HealthItem(int healPower) : healPower(healPower) {}

    void apply(Entity* entity) override
    {
        entity->heal(healPower);
    }

    string identify() const override
    {
        stringstream ss;
        ss << "Health Potion (" << healPower << ")";
        return ss.str();
    }

private:
    int healPower;
};
struct BlessedSword : public Item
{
    BlessedSword(int Weapon) : Weapon(Weapon){}
void apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";}
private: int Weapon;};//will add this to entity on my next commit. <.<

/*
struct ReallyFastSword : public Item
struct TheFastcall : public Entity
{
    TheFastcall() : Entity("The Fastcall", 22) {}
    virtual bool act(vector<string> commands) override
    {
    }
};
*/

typedef bool (*actionHandlerBYEBYENAMECOLLISION)(vector<string> commands); // unused, but we can't technically delete this, and commenting it out is just cheating.

struct Player : public Entity
{
    Player(string name, int health) : Entity(name, health) {}

    virtual bool act(vector<string> commands) override
    {
        auto cmd = commands[0];
        if(cmd == "n") { commands = vector<string>{"go","north"}; }
        if(cmd == "s") { commands = vector<string>{"go","south"}; }
        if(cmd == "e") { commands = vector<string>{"go","east"}; }
        if(cmd == "w") { commands = vector<string>{"go","west"}; }

        if (commands.size() >= 1 && commands[0] == "look")
        {
            look();
            return true;
        }
        else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
        {
        }
        else if (commands.size() >= 2 && commands[0] == "go")
        {
            if (travel(commands[1]) == true)
            {
                look();
            } else {
                cout << "Can't travel " << commands[1] << endl;
            }
            return true;
        }
        else if (commands.size() >= 1 && commands[0] == "items")
        {
            showItems();
            return true;
        }
        else if (commands.size() >= 2 && commands[0] == "use")
        {
            int index = stoi(commands[1]);
            useItem(index);
            return true;
        }

        return false;
    }

    bool travel(string direction)
    {
		if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
			return false;
		if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
			return false;
		if ((direction == "north"&&map.map_location[map.x][map.y + 1] == Map::UNKNOWN) || (direction == "south"&&map.map_location[map.x][map.y - 1] == Map::UNKNOWN) || (direction == "east"&&map.map_location[map.x + 1][map.y] == Map::UNKNOWN)||(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN))return false;
		if (direction == "north")map.y++; if (direction == "south")map.y--; if (direction == "east")map.x++; if (direction == "west")map.x--;
        return true;/*
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                if (direction == "north")
                {
					map.y++;
                    return true;
                }
                break;
            case Map::GRAVEYARD_GATES:
                if (direction == "south")
                {
					map.y--;
                    return true;
                }
                if (direction == "north")
                {
                    map.y++;
                    return true;
                }
                break;
        }

        cout << "Can't travel " << direction << endl;
        return false;*/
    }

    void look()
    {
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
                break;
            case Map::GRAVEYARD_GATES:
                cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
                break;
        }
    }

    void giveItem(shared_ptr<Item> item)
    {
        inventory.push_back(item);
    }

    void showItems()
    {
        if (inventory.size() == 0)
            cout << "You have no items." << endl;
        int i = 1;
        for (auto item : inventory)
        {
            cout << "  " << i++ << ". " << item->identify() << std::endl;
        }
    }

    void useItem(size_t index)
    {
        if (index > inventory.size())
        {
            cout << "Invalid index" << endl;
            return;
        }

        inventory[index-1]->apply(this);
        inventory.erase(inventory.begin() + index - 1);
    }

private:
    vector<shared_ptr<Item>> inventory;
    unordered_map<string, function<bool(vector<string>)>> actions;
};

struct Room {
	Room(RoomID idnum, string i_description) : ID(idnum) {
		description = i_description;
	}
	string describe() {
    stringstream ss;
    ss << description << "\n";
    ss << "Entities: "; for(auto& ent : entities) { ss << ent->name << ", "; }; ss << "\n"; //make this look nice later
    ss << "Items: "; for(auto& obj : objects) { ss << obj.names[0] << ", "; }; ss << "\n";  //make this look nice later
    ss << "Obvious exits: "; for(auto kv : exits) { ss << kv.first << ", "; } ss << "\n"; //...
		return ss.str();
	}
  const RoomID ID;
	string description;
	vector<unique_ptr<Entity>> entities;
	vector<RoomObject> objects;
	unordered_map<string, RoomID> exits;
};

class Adventure
{
public:
    void begin()
    {
        string command;
        cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
        cout << "> ";
        getline(cin, command);

        Player player(command, 100);
        player.giveItem(make_shared<HealthItem>(20));

        cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
        player.look();

        while (player.getHealth() > 0)
        {
            cout << "> ";
            getline(cin, command);
            if (player.act(split(command)) == false)
                cout << "Unknown command" << endl;
        }

        cout << "You died. Game over." << endl;
    }
};

int main()
{
    Adventure adventure;
    adventure.begin();
    return 0;
}
<|endoftext|>


<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * Flacon - audio File Encoder
 * https://github.com/flacon/flacon
 *
 * Copyright: 2012-2013
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.

 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include <QApplication>
#include "mainwindow.h"
#include "settings.h"
#include "converter/converter.h"
#include "project.h"

#include <QString>
#include <QLocale>
#include <QTranslator>
#include <QLibraryInfo>
#include <QMessageBox>
#include <QTextStream>
#include <QDebug>

/************************************************
 *
 ************************************************/
void printHelp()
{
    QTextStream out(stdout);
    out << "Usage: flacon [options] [file]" << endl;
    out << endl;
    out << "Flacon extracts individual tracks from one big audio file" << endl;
    out << endl;

    out << "Generic options:" << endl;
    out << "  -s --start                Start to convert immediately." << endl;
    out << "  -c --config <file>        Specify an alternative configuration file." << endl;

    out << "  -h, --help                Show help about options" << endl;
    out << "  --version                 Show version information" << endl;

    out << endl;
    out << "Arguments:" << endl;
    out << "  file                      CUE or Audio file" << endl;

    out << endl;
    out << "ENVIRONMENT" << endl;
    out << "  FLACON_DEBUG_ENCODER      If variable is set, flacon print the encoder" << endl;
    out << "                            program arguments." << endl;
    out << "  FLACON_DEBUG_GAIN         If variable is set, flacon print the gain" << endl;
    out << "                            program arguments." << endl;

}

/************************************************
 *
 ************************************************/
void printVersion()
{
    QTextStream out(stdout);
    out << "flacon " << FLACON_VERSION << endl;
    out << "Copyright (c) 2013 Alexander Sokolov" << endl;
    out << "   https://github.com/flacon/flacon" << endl;
    out << endl;
    out << "License LGPLv2.1+: GNU GNU Lesser General Public License version 2.1" << endl;
    out << "or later <http://www.gnu.org/licenses/lgpl-2.1.html>." << endl;
    out << "This is free software: you are free to change and redistribute it." << endl;
    out << "There is NO WARRANTY, to the extent permitted by law." << endl;
}

/************************************************
 *
 ************************************************/
void consoleErroHandler(const QString &message)
{
    QString msg(message);
    msg.remove(QRegExp("<[^>]*>"));
    qWarning() << msg;
}

/************************************************
 *
 ************************************************/
void guiErrorHandler(const QString &message)
{
    consoleErroHandler(message);
    QMessageBox::critical(0, QObject::tr("Flacon", "Error"), message);
}

/************************************************
 *
 ************************************************/
void translate(QApplication *app)
{
    QString locale = QLocale::system().name();

    QTranslator *qtTranslator = new QTranslator(app);
    qtTranslator->load("qt_" + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    app->installTranslator(qtTranslator);

    QTranslator *appTranslator = new QTranslator(app);
    appTranslator->load(QString("flacon_%2.qm").arg(locale)) ||
            appTranslator->load(QString("%1/flacon_%2.qm").arg(TRANSLATIONS_DIR, locale));
    app->installTranslator(appTranslator);
}

/************************************************
 *
 ************************************************/
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    translate(&app);

    bool start = false;
    QStringList files;
    QStringList args = app.arguments();
    for (int i=1; i < args.count(); ++i)
    {
        QString arg = args.at(i);

        if (arg == "--help" || arg == "-h")
        {
            printHelp();
            return 0;
        }

        if (arg == "--version")
        {
            printVersion();
            return 0;
        }

        if (arg == "--start" || arg == "-s")
        {
            start = true;
            continue;
        }

        if (arg == "--config" || arg == "-c")
        {
            i++;
            if (i<args.count())
                Settings::setFileName(args.at(i));

            continue;
        }

        files << arg;

    }

    MainWindow window;

    foreach(QString file, files)
        window.addFileOrDir(file);

    if (start)
    {
        Project::installErrorHandler(consoleErroHandler);
        Converter converter;
        QEventLoop loop;
        loop.connect(&converter, SIGNAL(finished()), &loop, SLOT(quit()));

        converter.start();
        loop.exec();
        return 0;
    }
    else
    {
        Project::installErrorHandler(guiErrorHandler);
    }

    window.show();
    return app.exec();
}
<commit_msg>Console start of flacon do not require Xwindow<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * Flacon - audio File Encoder
 * https://github.com/flacon/flacon
 *
 * Copyright: 2012-2013
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.

 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include <QCommandLineParser>
#include <QApplication>
#include "mainwindow.h"
#include "settings.h"
#include "converter/converter.h"
#include "project.h"
#include "scanner.h"

#include <QString>
#include <QLocale>
#include <QTranslator>
#include <QLibraryInfo>
#include <QMessageBox>
#include <QTextStream>
#include <QDebug>
#include <QFileInfo>

/************************************************
 *
 ************************************************/
void printHelp()
{
    QTextStream out(stdout);
    out << "Usage: flacon [options] [file]" << endl;
    out << "Flacon extracts individual tracks from one big audio file" << endl;
    out << endl;

    out << "Generic options:" << endl;
    out << "  -s --start                Start to convert immediately." << endl;
    out << "  -c --config <file>        Specify an alternative configuration file." << endl;

    out << "  -h, --help                Show help about options" << endl;
    out << "  --version                 Show version information" << endl;

    out << endl;
    out << "Arguments:" << endl;
    out << "  file                      CUE or Audio file" << endl;

    out << endl;
    out << "ENVIRONMENT" << endl;
    out << "  FLACON_DEBUG_ENCODER      If variable is set, flacon print the encoder" << endl;
    out << "                            program arguments." << endl;
    out << "  FLACON_DEBUG_GAIN         If variable is set, flacon print the gain" << endl;
    out << "                            program arguments." << endl;

}

/************************************************
 *
 ************************************************/
void printVersion()
{
    QTextStream out(stdout);
    out << "flacon " << FLACON_VERSION << endl;
    out << "Copyright (c) 2013 Alexander Sokolov" << endl;
    out << "   https://github.com/flacon/flacon" << endl;
    out << endl;
    out << "License LGPLv2.1+: GNU GNU Lesser General Public License version 2.1" << endl;
    out << "or later <http://www.gnu.org/licenses/lgpl-2.1.html>." << endl;
    out << "This is free software: you are free to change and redistribute it." << endl;
    out << "There is NO WARRANTY, to the extent permitted by law." << endl;
}

/************************************************
 *
 ************************************************/
void consoleErroHandler(const QString &message)
{
    QString msg(message);
    msg.remove(QRegExp("<[^>]*>"));
    msg.replace("\\n", "\n");
    QTextStream(stderr) << msg.toLocal8Bit() << endl;
}

/************************************************
 *
 ************************************************/
void guiErrorHandler(const QString &message)
{
    consoleErroHandler(message);
    QMessageBox::critical(0, QObject::tr("Flacon", "Error"), message);
}

/************************************************
 *
 ************************************************/
void translate(QApplication *app)
{
    QString locale = QLocale::system().name();

    QTranslator *qtTranslator = new QTranslator(app);
    qtTranslator->load("qt_" + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    app->installTranslator(qtTranslator);

    QTranslator *appTranslator = new QTranslator(app);
    appTranslator->load(QString("flacon_%2.qm").arg(locale)) ||
            appTranslator->load(QString("%1/flacon_%2.qm").arg(TRANSLATIONS_DIR, locale));
    app->installTranslator(appTranslator);
}

/************************************************
 *
 ************************************************/
int runConsole(int argc, char *argv[], const QStringList &files)
{
    QCoreApplication app(argc, argv);
    Project::installErrorHandler(consoleErroHandler);

    foreach(QString file, files)
    {
        QFileInfo fi = QFileInfo(file);
        if (fi.isDir())
        {
            Scanner scanner;
            scanner.start(fi.absoluteFilePath());
        }
        else if (fi.size() > 102400)
        {
            project->addAudioFile(file, false);
        }
        else
        {
            project->addCueFile(file, false);
        }
    }

    if (project->count() == 0)
        return 10;

    Converter converter;
    app.connect(&converter, SIGNAL(finished()),
                &app, SLOT(quit()));

    converter.start();
    if (!converter.isRunning())
        return 11;

    return app.exec();
}

/************************************************
 *
 ************************************************/
int runGui(int argc, char *argv[], const QStringList &files)
{
    QApplication app(argc, argv);
    translate(&app);

    MainWindow window;

    foreach(QString file, files)
        window.addFileOrDir(file);

    Project::installErrorHandler(guiErrorHandler);

    window.show();
    return app.exec();
}

/************************************************
 *
 ************************************************/
int main(int argc, char *argv[])
{

    QCommandLineParser parser;

    parser.addPositionalArgument("file", QCoreApplication::translate("main", "CUE or Audio file."));
    parser.addOptions({
        {{"h", "help"   }, "Show help about options."},
        {      "version" , "Show version information."},

        {{"s", "start"  }, "Start to convert immediately."},
        {{"c", "config" }, "Specify an alternative configuration file.", "config file"}
    });

    QStringList args;
    for (int i=0; i<argc; ++i)
        args << QString::fromLocal8Bit(argv[i]);

    if (!parser.parse(args))
    {
        QTextStream(stderr) << parser.errorText() << endl << endl;
        printHelp();
        return 1;
    }

    if (parser.isSet("help"))
    {
        printHelp();
        return 0;
    }

    if (parser.isSet("version"))
    {
        printVersion();
        return 0;
    }

    if (!parser.value("config").isEmpty())
    {
        Settings::setFileName(parser.value("config"));
    }

    if (parser.isSet("start"))
        return runConsole(argc, argv, parser.positionalArguments());
    else
        return runGui(argc, argv, parser.positionalArguments());
}
<|endoftext|>


<commit_before>/*
 * Copyright 2010,
 * François Bleibel,
 * Olivier Stasse,
 *
 * CNRS/AIST
 *
 * This file is part of sot-core.
 * sot-core is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 * sot-core 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 sot-core.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <dynamic-graph/signal-caster.h>
#include <sot/core/pool.hh>
#include <iomanip>

#include <sot/core/feature-abstract.hh>
#include "sot/core/matrix-homogeneous.hh"
#include "sot/core/matrix-rotation.hh"
#include <sot/core/flags.hh>
#include <sot/core/multi-bound.hh>
#include <dynamic-graph/signal-caster.h>
#include <dynamic-graph/signal-cast-helper.h>

# ifdef WIN32
#  include <Windows.h>
# endif

/* Implements a set of caster/displayer for the main types of sot-core. */

namespace dynamicgraph
{
  using namespace std;
  using namespace dynamicgraph::sot;

  /* --- CASTER IMPLEMENTATION ------------------------------------------------ */
  /* --- CASTER IMPLEMENTATION ------------------------------------------------ */
  /* --- CASTER IMPLEMENTATION ------------------------------------------------ */

  DG_SIGNAL_CAST_DEFINITION(sot::Flags);
  DG_ADD_CASTER(sot::Flags,flags);

  template <>
  void
  DefaultCastRegisterer<MatrixHomogeneous>::
  trace(const boost::any& object, std::ostream& os)
  {
    const MatrixHomogeneous & M = boost::any_cast<MatrixHomogeneous>(object);
    for( unsigned int i=0;i<4;++i )
      for( unsigned int j=0;j<4;++j )
	{ os << "\t" << M(i,j); }
  }
  namespace {
    dynamicgraph::DefaultCastRegisterer <sot::MatrixHomogeneous>
    matrixHomegeneousCastRegisterer;

    dynamicgraph::DefaultCastRegisterer <sot::MatrixRotation>
    matrixRotationCastRegisterer;
  }
  /* --- FEATURE ABSTRACT ----------------------------------------------------- */
  /* --- FEATURE ABSTRACT ----------------------------------------------------- */
  /* --- FEATURE ABSTRACT ----------------------------------------------------- */

  DG_SIGNAL_CAST_DEFINITION_HPP(sot::FeatureAbstract*);

  FeatureAbstract* SignalCast<FeatureAbstract*>::
  cast( std::istringstream& iss )
  {
    FeatureAbstract* ref;
    std::string name; iss >> name;
    if( name.length())
      {
	ref = &dynamicgraph::sot::PoolStorage::getInstance()->getFeature(name);
      }
    else { ref = NULL; }
    return ref;
  }

  void SignalCast<FeatureAbstract*>::
  disp( FeatureAbstract* const& t,std::ostream& os )
  {
    if( t ) { t->display(os); os<<std::endl; }
    else { os << "NULL" << std::endl; }
  }

  DG_ADD_CASTER(FeatureAbstract*,FAptr);

  /* --- TIMEVAL -------------------------------------------------------------- */
  /* --- TIMEVAL -------------------------------------------------------------- */
  /* --- TIMEVAL -------------------------------------------------------------- */
  DG_SIGNAL_CAST_DEFINITION_HPP(struct timeval);

  struct timeval SignalCast<struct timeval>::
    cast( std::istringstream& iss )
  {
    int u,s; iss >> s >> u;
    struct timeval t; t.tv_sec = s; t.tv_usec = u;
    return t;
  }
  void SignalCast<struct timeval>::
  disp( const struct timeval& t,std::ostream& os )
  {
    os << t.tv_sec << "s "<< t.tv_usec << "ms";
  }

  DG_ADD_CASTER(struct timeval,tv);

  /* --- MULTI BOUND ---------------------------------------------------------- */
  /* --- MULTI BOUND ---------------------------------------------------------- */
  /* --- MULTI BOUND ---------------------------------------------------------- */

  DG_SIGNAL_CAST_DEFINITION_TRACE(sot::VectorMultiBound);

  void SignalCast<VectorMultiBound>::
  trace( const VectorMultiBound& t,std::ostream& os )
  {
    for( VectorMultiBound::const_iterator iter=t.begin();t.end()!=iter;++iter )
      {
	switch( iter->mode )
	  {
	  case MultiBound::MODE_SINGLE:
	    os << iter->getSingleBound() << "\t";
	    break;
	  case MultiBound::MODE_DOUBLE:
	    if( iter->getDoubleBoundSetup(MultiBound::BOUND_INF) )
	      os << iter->getDoubleBound(MultiBound::BOUND_INF)<<"\t";
	    else os <<"-inf\t";
	    if( iter->getDoubleBoundSetup(MultiBound::BOUND_SUP) )
	      os << iter->getDoubleBound(MultiBound::BOUND_SUP)<<"\t";
	    else os <<"+inf\t";
	    break;
	  }
      }
  }
  DG_ADD_CASTER(sot::VectorMultiBound,sotVMB);

}// namespace dynamicgraph
<commit_msg>Add signal cast registerer for types VectorUTheta and VectorRollPitchYaw.<commit_after>/*
 * Copyright 2010,
 * François Bleibel,
 * Olivier Stasse,
 *
 * CNRS/AIST
 *
 * This file is part of sot-core.
 * sot-core is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 * sot-core 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 sot-core.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <dynamic-graph/signal-caster.h>
#include <sot/core/pool.hh>
#include <iomanip>

#include <sot/core/feature-abstract.hh>
#include "sot/core/matrix-homogeneous.hh"
#include "sot/core/matrix-rotation.hh"
#include <sot/core/flags.hh>
#include <sot/core/multi-bound.hh>
#include <sot/core/vector-utheta.hh>
#include <sot/core/vector-roll-pitch-yaw.hh>
#include <dynamic-graph/signal-caster.h>
#include <dynamic-graph/signal-cast-helper.h>

# ifdef WIN32
#  include <Windows.h>
# endif

/* Implements a set of caster/displayer for the main types of sot-core. */

namespace dynamicgraph
{
  using namespace std;
  using namespace dynamicgraph::sot;

  /* --- CASTER IMPLEMENTATION ------------------------------------------------ */
  /* --- CASTER IMPLEMENTATION ------------------------------------------------ */
  /* --- CASTER IMPLEMENTATION ------------------------------------------------ */

  DG_SIGNAL_CAST_DEFINITION(sot::Flags);
  DG_ADD_CASTER(sot::Flags,flags);

  template <>
  void
  DefaultCastRegisterer<MatrixHomogeneous>::
  trace(const boost::any& object, std::ostream& os)
  {
    const MatrixHomogeneous & M = boost::any_cast<MatrixHomogeneous>(object);
    for( unsigned int i=0;i<4;++i )
      for( unsigned int j=0;j<4;++j )
	{ os << "\t" << M(i,j); }
  }
  namespace {
    dynamicgraph::DefaultCastRegisterer <sot::MatrixHomogeneous>
    matrixHomegeneousCastRegisterer;

    dynamicgraph::DefaultCastRegisterer <sot::MatrixRotation>
    matrixRotationCastRegisterer;
  }
  /* --- FEATURE ABSTRACT ----------------------------------------------------- */
  /* --- FEATURE ABSTRACT ----------------------------------------------------- */
  /* --- FEATURE ABSTRACT ----------------------------------------------------- */

  DG_SIGNAL_CAST_DEFINITION_HPP(sot::FeatureAbstract*);

  FeatureAbstract* SignalCast<FeatureAbstract*>::
  cast( std::istringstream& iss )
  {
    FeatureAbstract* ref;
    std::string name; iss >> name;
    if( name.length())
      {
	ref = &dynamicgraph::sot::PoolStorage::getInstance()->getFeature(name);
      }
    else { ref = NULL; }
    return ref;
  }

  void SignalCast<FeatureAbstract*>::
  disp( FeatureAbstract* const& t,std::ostream& os )
  {
    if( t ) { t->display(os); os<<std::endl; }
    else { os << "NULL" << std::endl; }
  }

  DG_ADD_CASTER(FeatureAbstract*,FAptr);

  /* --- TIMEVAL -------------------------------------------------------------- */
  /* --- TIMEVAL -------------------------------------------------------------- */
  /* --- TIMEVAL -------------------------------------------------------------- */
  DG_SIGNAL_CAST_DEFINITION_HPP(struct timeval);

  struct timeval SignalCast<struct timeval>::
    cast( std::istringstream& iss )
  {
    int u,s; iss >> s >> u;
    struct timeval t; t.tv_sec = s; t.tv_usec = u;
    return t;
  }
  void SignalCast<struct timeval>::
  disp( const struct timeval& t,std::ostream& os )
  {
    os << t.tv_sec << "s "<< t.tv_usec << "ms";
  }

  DG_ADD_CASTER(struct timeval,tv);

  ///
  /// VectorUTheta and VectorRollPitchYaw
  ///
  namespace {
    dynamicgraph::DefaultCastRegisterer <VectorUTheta>
    vectorUThetaCastRegisterer;

    dynamicgraph::DefaultCastRegisterer <VectorRollPitchYaw>
    vectorRollPitchYawCastRegisterer;
  }

  /* --- MULTI BOUND ---------------------------------------------------------- */
  /* --- MULTI BOUND ---------------------------------------------------------- */
  /* --- MULTI BOUND ---------------------------------------------------------- */

  DG_SIGNAL_CAST_DEFINITION_TRACE(sot::VectorMultiBound);

  void SignalCast<VectorMultiBound>::
  trace( const VectorMultiBound& t,std::ostream& os )
  {
    for( VectorMultiBound::const_iterator iter=t.begin();t.end()!=iter;++iter )
      {
	switch( iter->mode )
	  {
	  case MultiBound::MODE_SINGLE:
	    os << iter->getSingleBound() << "\t";
	    break;
	  case MultiBound::MODE_DOUBLE:
	    if( iter->getDoubleBoundSetup(MultiBound::BOUND_INF) )
	      os << iter->getDoubleBound(MultiBound::BOUND_INF)<<"\t";
	    else os <<"-inf\t";
	    if( iter->getDoubleBoundSetup(MultiBound::BOUND_SUP) )
	      os << iter->getDoubleBound(MultiBound::BOUND_SUP)<<"\t";
	    else os <<"+inf\t";
	    break;
	  }
      }
  }
  DG_ADD_CASTER(sot::VectorMultiBound,sotVMB);

}// namespace dynamicgraph
<|endoftext|>


<commit_before>/*=========================================================================

  Programme :   OTB (ORFEO ToolBox)
  Auteurs   :   CS - C.Ruffel
  Language  :   C++
  Date      :   09 mars 2006
  Version   :
  Role      :   Test la classe du filtre de detection de contours
  $Id$

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#define MAIN

#include "itkExceptionObject.h"
#include "itkImage.h"
#include "itkImageFileWriter.h"
#include <iostream>

#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbTouziEdgeDetector.h"

int otbTouziEdgeDetector( int argc, char* argv[] )
{
  try
    {
        const char * inputFilename  = argv[1];
        const char * outputFilename = argv[2];
        const char * outputFilenameDir = argv[4];

        unsigned int  RadiusX((unsigned int)::atoi(argv[3]));

        typedef unsigned char                                   InputPixelType;
        typedef double		   	                        OutputPixelType;
        const   unsigned int        	                        Dimension = 2;

        typedef itk::Image< InputPixelType,  Dimension >        InputImageType;
        typedef itk::Image< OutputPixelType, Dimension >        OutputImageType;

        typedef otb::ImageFileReader< InputImageType  >         ReaderType;
        typedef otb::ImageFileWriter< OutputImageType >         WriterType;

        typedef otb::TouziEdgeDetector< InputImageType,OutputImageType >   FilterType;

	FilterType::SizeType Radius;
	Radius[0] = RadiusX;
	Radius[1] = RadiusX;

        FilterType::Pointer filtreTouzi = FilterType::New();

	filtreTouzi->SetRadius( Radius );

        ReaderType::Pointer reader = ReaderType::New();
        WriterType::Pointer writer = WriterType::New();
        WriterType::Pointer writer_dir = WriterType::New();

        reader->SetFileName( inputFilename  );
        writer->SetFileName( outputFilename );

        filtreTouzi->SetInput( reader->GetOutput() );
        writer->SetInput( filtreTouzi->GetOutput() );

        writer->Update();

        writer_dir->SetFileName( outputFilenameDir );
        writer_dir->SetInput( filtreTouzi->GetOutputDirection() );
        writer_dir->Update();

    }
  catch( itk::ExceptionObject & err )
    {
    std::cout << "Exception itk::ExceptionObject levee !" << std::endl;
    std::cout << err << std::endl;
    return EXIT_FAILURE;
    }
  catch( ... )
    {
    std::cout << "Exception levee inconnue !" << std::endl;
    return EXIT_FAILURE;
    }
  // Software Guide : EndCodeSnippet

//#endif
  return EXIT_SUCCESS;
}

<commit_msg>nomsg<commit_after>/*=========================================================================

  Programme :   OTB (ORFEO ToolBox)
  Auteurs   :   CS - C.Ruffel
  Language  :   C++
  Date      :   09 mars 2006
  Version   :
  Role      :   Test du filtre de detection de contours (image intensite)
  $Id$

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#define MAIN

#include "itkExceptionObject.h"
#include "itkImage.h"
#include "itkImageFileWriter.h"
#include <iostream>

#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbTouziEdgeDetector.h"

int otbTouziEdgeDetector( int argc, char* argv[] )
{
  try
    {
        const char * inputFilename  = argv[1];
        const char * outputFilename = argv[2];

        unsigned int  RadiusX((unsigned int)::atoi(argv[3]));

        typedef unsigned char                                   InputPixelType;
        typedef double		   	                        OutputPixelType;
        const   unsigned int        	                        Dimension = 2;

        typedef itk::Image< InputPixelType,  Dimension >        InputImageType;
        typedef itk::Image< OutputPixelType, Dimension >        OutputImageType;

        typedef otb::ImageFileReader< InputImageType  >         ReaderType;
        typedef otb::ImageFileWriter< OutputImageType >         WriterType;

        typedef otb::TouziEdgeDetector< InputImageType,OutputImageType >   FilterType;

	FilterType::SizeType Radius;
	Radius[0] = RadiusX;
	Radius[1] = RadiusX;

        FilterType::Pointer filtreTouzi = FilterType::New();

	filtreTouzi->SetRadius( Radius );

        ReaderType::Pointer reader = ReaderType::New();
        WriterType::Pointer writer = WriterType::New();

        reader->SetFileName( inputFilename  );
        writer->SetFileName( outputFilename );

        filtreTouzi->SetInput( reader->GetOutput() );
        writer->SetInput( filtreTouzi->GetOutput() );

        writer->Update();

    }
  catch( itk::ExceptionObject & err )
    {
    std::cout << "Exception itk::ExceptionObject levee !" << std::endl;
    std::cout << err << std::endl;
    return EXIT_FAILURE;
    }
  catch( ... )
    {
    std::cout << "Exception levee inconnue !" << std::endl;
    return EXIT_FAILURE;
    }
  // Software Guide : EndCodeSnippet

//#endif
  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>#ifndef LAYER_HPP_
#define LAYER_HPP_

#include "tensor.cu"
#include <vector>

// TODO: discuss and finalize interfaces: forward() & backward()

template <class Dtype>
class Layer {
public:
  virtual void Forward(const std::vector<Tensor<Dtype>*> &bottoms, const std::vector<Tensor<Dtype>*> &tops) = 0;

  virtual void Backward(const std::vector<Tensor<Dtype>*> &tops,
                const std::vector<Tensor<Dtype>*> &tops_diff,
                const std::vector<Tensor<Dtype>*> &bottoms,
                const std::vector<Tensor<Dtype>*> &bottoms_diff,) = 0;

  virtual void GetTopsDims(const std::vector<size_t*> &bottoms_dims, const std::vector<size_t*> &tops_dims) = 0;
};

#endif  // LAYER_HPP_
<commit_msg>layer interface<commit_after>#ifndef LAYER_HPP_
#define LAYER_HPP_

#include "tensor.cu"
#include <vector>

template <class Dtype>
class Layer {
public:
  virtual void Forward(const std::vector<Tensor<Dtype>*> &bottoms, const std::vector<Tensor<Dtype>*> &tops) = 0;

  virtual void Backward(const std::vector<Tensor<Dtype>*> &tops,
                        const std::vector<Tensor<Dtype>*> &tops_diff,
                        const std::vector<Tensor<Dtype>*> &bottoms,
                        const std::vector<Tensor<Dtype>*> &bottoms_diff) = 0;

  virtual void GetTopsDims(const std::vector<size_t*> &bottoms_dims, const std::vector<size_t*> &tops_dims) = 0;
};

#endif  // LAYER_HPP_
<|endoftext|>


<commit_before>#ifndef _DATA_TYPES
#define _DATA_TYPES

#include <iostream>

struct dimension {
  dimension(void);
  dimension(unsigned int w, unsigned int h);
  unsigned int width, height;
};

struct position {
  position(void);
  position(int x, int y);
  int x, y;
};

struct rectangle {
  rectangle(void);
  rectangle(position pos, dimension dim);
  rectangle(int x, int y, unsigned int width, unsigned int height);

  int & x(void);
  int const & x(void) const;
  int & y(void);
  int const & y(void) const;
  unsigned int & width(void);
  unsigned int const & width(void) const;
  unsigned int & height(void);
  unsigned int const & height(void) const;

  position _position;
  dimension _dimension;
};

std::ostream & operator<<(std::ostream & os, const rectangle & rect);

namespace x {

namespace type {

namespace generic {

class name {
  public:
    name(const std::string & name) : m_name(name) {}
    std::string & operator*(void) { return m_name; }
    const std::string & operator*(void) const { return m_name; }
    std::string * const operator->(void) { return &m_name; }
    const std::string * const operator->(void) const { return &m_name; }
  private:
    std::string m_name;
}; // class name

}; // namespace generic

class colorname : public generic::name {
  using generic::name::name;
};

class fontname : public generic::name {
  using generic::name::name;
};

}; // namespace type

}; // namespace x

#endif
<commit_msg>Add default c'tor to allow for empty objects<commit_after>#ifndef _DATA_TYPES
#define _DATA_TYPES

#include <iostream>

struct dimension {
  dimension(void);
  dimension(unsigned int w, unsigned int h);
  unsigned int width, height;
};

struct position {
  position(void);
  position(int x, int y);
  int x, y;
};

struct rectangle {
  rectangle(void);
  rectangle(position pos, dimension dim);
  rectangle(int x, int y, unsigned int width, unsigned int height);

  int & x(void);
  int const & x(void) const;
  int & y(void);
  int const & y(void) const;
  unsigned int & width(void);
  unsigned int const & width(void) const;
  unsigned int & height(void);
  unsigned int const & height(void) const;

  position _position;
  dimension _dimension;
};

std::ostream & operator<<(std::ostream & os, const rectangle & rect);

namespace x {

namespace type {

namespace generic {

class name {
  public:
    name(void) {}
    name(const std::string & name) : m_name(name) {}
    std::string & operator*(void) { return m_name; }
    const std::string & operator*(void) const { return m_name; }
    std::string * const operator->(void) { return &m_name; }
    const std::string * const operator->(void) const { return &m_name; }
  private:
    std::string m_name;
}; // class name

}; // namespace generic

class colorname : public generic::name {
  using generic::name::name;
};

class fontname : public generic::name {
  using generic::name::name;
};

}; // namespace type

}; // namespace x

#endif
<|endoftext|>