<commit_before>#pragma once

#include "backlog.hpp"
#include "detail/util.hpp"

namespace sts
{
  class scroller
  {
    public:
      scroller() = delete;
      scroller(backlog &bl)
        : backlog_{ bl }
      { }

      template <typename It>
      void write(It const &begin, It end)
      {
        auto const size(std::distance(begin, end));
        if(::write(STDOUT_FILENO, &*begin, size) != size)
        { throw std::runtime_error{ "partial/failed write (stdout)" }; }

        end = filter(begin, end);
        backlog_.write(begin, end);

        auto &impl(backlog_.get_impl());
        auto const line_markers_size(impl.line_markers_.size());
        auto const rows(impl.tty_.get().size.ws_row);
        if(following_ && line_markers_size > rows)
        { scroll_pos_ = line_markers_size - rows; }
      }

      void up()
      {
        if(!scroll_pos_)
        { return; }
        following_ = false;
        --scroll_pos_;
        redraw();
      }

      void down()
      {
        auto &impl(backlog_.get_impl());
        if(scroll_pos_ + impl.tty_.get().size.ws_row >= impl.line_markers_.size())
        {
          following_ = true;
          return;
        }
        ++scroll_pos_;
        redraw();
      }

      void follow()
      {
        auto &impl(backlog_.get_impl());
        if(following_)
        { return; }

        scroll_pos_ = impl.line_markers_.size() - impl.tty_.get().size.ws_row;
        following_ = true;
        redraw();
      }

      void clear()
      {
        static std::string const clear{ "\x1B[H\x1B[2J" };
        static ssize_t const clear_size(clear.size());
        if(::write(STDOUT_FILENO, clear.c_str(), clear.size()) != clear_size)
        { throw std::runtime_error{ "unable to clear screen" }; }
      }

    private:
      template <typename It>
      It filter(It const &begin, It end)
      {
        std::ofstream ofs{ ".filter", std::ios_base::app };
        auto distance(std::distance(begin, end));
        size_t d{};
        auto const predicates(detail::make_array<std::function<size_t (It)>>(
        [&](It const it)
        {
          d = detail::seq_eq<6>(distance, it, { 27, '[', '?', '4', '7', 'h' });
          if(d)
          { backlog_.impls_.emplace_back(backlog_.tty_, backlog_.limit_); }
          return d;
        },
        [&](It const it)
        {
          d = detail::seq_eq<6>(distance, it, { 27, '[', '?', '4', '7', 'l' });
          if(d && backlog_.impls_.size() > 1)
          { backlog_.impls_.erase(backlog_.impls_.end() - 1); }
          return d;
        },
        [&](It const it)
        { return d = detail::seq_eq<4>(distance, it, { 27, '[', '2', 'J' }); },
        [&](It const it)
        { return d = detail::seq_eq<2>(distance, it, { 27, '7' }); },
        [&](It const it)
        { return d = detail::seq_eq<2>(distance, it, { 27, '8' }); },
        [&](It const it)
        { return d = detail::seq_eq<3>(distance, it, { 27, '[', 'K' }); },
        [&](It const it)
        { return d = detail::seq_eq<4>(distance, it, { 27, '[', '?', '1' }); },
        [&](It const it)
        { return d = detail::seq_eq<2>(distance, it, { 27, '>' }); },
        [&](It const it)
        { return d = detail::seq_eq<6>(distance, it, { 27, '[', '?', '2', '5', 'h' }); },
        [&](It const it)
        { return d = detail::seq_eq<8>(distance, it, { 27, '[', '3', '0', ';', '1', 'H', 'l' }); },
        [&](It const it)
        { return d = detail::seq_eq<7>(distance, it, { 27, '[', '3', '0', ';', '1', 'H' }); }
        ));

        auto const pred_end(std::end(predicates));
        for(auto it(begin); it != end; ++it, --distance)
        {
          while(std::find_if(std::begin(predicates), pred_end,
            [&](std::function<size_t (It)> const &f)
            { return f(it); }) != pred_end)
          {
            std::copy(begin, end, std::ostream_iterator<int>(ofs, " "));
            ofs << std::endl;
            auto const sub_end(it + d);
            auto rit(begin);
            end = std::remove_if(begin, end, [&](char const)
            {
              auto const cur(rit++);
              return (cur >= it && cur < sub_end);
            });
            std::copy(begin, end, std::ostream_iterator<int>(ofs, " "));
            ofs << std::endl;

            if(it == end)
            { break; }
          }

          if(it == end)
          { break; }
        }

        return end;
      }

      void redraw()
      {
        clear();

        auto &impl(backlog_.get_impl());
        std::size_t const rows{ impl.tty_.get().size.ws_row };
        for(std::size_t i{ scroll_pos_ };
            i < scroll_pos_ + std::min(impl.line_markers_.size(), rows);
            ++i)
        {
          ssize_t size((impl.line_markers_[i].second -
                        impl.line_markers_[i].first) + 1);
          if(i == scroll_pos_ + std::min(impl.line_markers_.size() - 1,
                                         rows - 1))
          { --size; }
          if(::write(STDOUT_FILENO, &impl.buf_[impl.line_markers_[i].first],
                     size) != size)
          { throw std::runtime_error{ "partial/failed write (stdout)" }; }
        }
      }

      backlog &backlog_;
      std::size_t scroll_pos_{};
      bool following_{ true };
  };
}
<commit_msg>regex to the rescue<commit_after>#pragma once

#include "backlog.hpp"
#include "detail/util.hpp"

#include <regex>
#include <algorithm>

namespace sts
{
  class scroller
  {
    public:
      scroller() = delete;
      scroller(backlog &bl)
        : backlog_{ bl }
      { }

      template <typename It>
      void write(It const &begin, It end)
      {
        auto const size(std::distance(begin, end));
        if(::write(STDOUT_FILENO, &*begin, size) != size)
        { throw std::runtime_error{ "partial/failed write (stdout)" }; }

        end = filter(begin, end);
        backlog_.write(begin, end);

        auto &impl(backlog_.get_impl());
        auto const line_markers_size(impl.line_markers_.size());
        auto const rows(impl.tty_.get().size.ws_row);
        if(following_ && line_markers_size > rows)
        { scroll_pos_ = line_markers_size - rows; }
      }

      void up()
      {
        if(!scroll_pos_)
        { return; }
        following_ = false;
        --scroll_pos_;
        redraw();
      }

      void down()
      {
        auto &impl(backlog_.get_impl());
        if(scroll_pos_ + impl.tty_.get().size.ws_row >= impl.line_markers_.size())
        {
          following_ = true;
          return;
        }
        ++scroll_pos_;
        redraw();
      }

      void follow()
      {
        auto &impl(backlog_.get_impl());
        if(following_)
        { return; }

        scroll_pos_ = impl.line_markers_.size() - impl.tty_.get().size.ws_row;
        following_ = true;
        redraw();
      }

      void clear()
      {
        static std::string const clear{ "\x1B[H\x1B[2J" };
        static ssize_t const clear_size(clear.size());
        if(::write(STDOUT_FILENO, clear.c_str(), clear.size()) != clear_size)
        { throw std::runtime_error{ "unable to clear screen" }; }
      }

    private:
      template <typename It>
      It filter(It const &begin, It end)
      {
        std::ofstream ofs{ ".filter", std::ios_base::app };
        static auto const predicates(detail::make_array
        (
          std::regex{ "\x1B\\[\\?47(h|l)" }, /* smcup/rmcup */
          std::regex{ "\x1B\\[2J" }, /* clear */
          std::regex{ "\x1B\\[([[:digit:]])*(A|B|C|D|E|F|G|J|K|S|T)" }, /* move cursor/scroll */
          std::regex{ "\x1B\\[([[:digit:]])*;([[:digit:]])*(H|f)" }, /* move cursor */
          std::regex{ "\x1B\\[6n" }, /* report cursor */
          std::regex{ "\x1B\\[(s|u)" }, /* save/restore cursor */
          std::regex{ "\x1B\\[\\?25(h|l)" } /* show/hide cursor */
        ));

        std::smatch match;
        for(auto const &pred : predicates)
        {
          while(std::regex_search(std::string{begin, end}, match, pred))
          {
            std::copy(begin, end, std::ostream_iterator<int>(ofs, " "));
            ofs << std::endl;
            ofs << "filtering (" << match.position() << ")"
                << "[" << match.length() << "]: ";
            std::copy(begin, end, std::ostream_iterator<int>(ofs, " "));
            ofs << std::endl;

            auto const it(begin + match.position());
            auto const sub_end(it + match.length());
            auto rit(begin);
            end = std::remove_if(begin, end, [&](char const)
            {
              auto const cur(rit++);
              return (cur >= it && cur < sub_end);
            });

            std::copy(begin, end, std::ostream_iterator<int>(ofs, " "));
            ofs << std::endl;
          }
        }

        return end;
      }

      void redraw()
      {
        clear();

        auto &impl(backlog_.get_impl());
        std::size_t const rows{ impl.tty_.get().size.ws_row };
        for(std::size_t i{ scroll_pos_ };
            i < scroll_pos_ + std::min(impl.line_markers_.size(), rows);
            ++i)
        {
          ssize_t size((impl.line_markers_[i].second -
                        impl.line_markers_[i].first) + 1);
          if(i == scroll_pos_ + std::min(impl.line_markers_.size() - 1,
                                         rows - 1))
          { --size; }
          if(::write(STDOUT_FILENO, &impl.buf_[impl.line_markers_[i].first],
                     size) != size)
          { throw std::runtime_error{ "partial/failed write (stdout)" }; }
        }
      }

      backlog &backlog_;
      std::size_t scroll_pos_{};
      bool following_{ true };
  };
}
<|endoftext|>


<commit_before>#include <cstdlib>

#include <iostream>

extern "C" {

#include "lua/lualib.h"

}

#include "lualite/lualite.hpp"

struct point
{
  int x;
  int y;
};

inline int set_result(lua_State* const L, point p)
{
  using namespace ::lualite::detail;

  lua_createtable(L, 2, 0);

  lua_pushliteral(L, "x");
  set_result(L, const_cast<decltype(p.x) const&>(p.x));
  assert(lua_istable(L, -3));
  lua_rawset(L, -3);

  lua_pushliteral(L, "y");
  set_result(L, const_cast<decltype(p.y) const&>(p.y));
  assert(lua_istable(L, -3));
  lua_rawset(L, -3);

  return 1;
}

template <std::size_t I, typename T>
inline typename std::enable_if<
  std::is_same<T, point>::value, point>::type
get_arg(lua_State* const L)
{
  using namespace ::lualite::detail;

  assert(lua_istable(L, I));

  struct point p;

  lua_pushliteral(L, "x");
  lua_rawget(L, -2);
  p.x = lua_tointeger(L, -1);

  lua_pushliteral(L, "y");
  lua_rawget(L, -2);
  p.y = lua_tointeger(L, -1);

  return p;
}

point testfunc(int i)
{
  std::cout << "testfunc(): " << i << std::endl;

  return {-1, -222};
}

struct testbase
{
  std::string dummy(std::string msg)
  {
    return { "dummy() called: " + msg };
  }
};

struct testclass : testbase
{
  testclass()
    : a_(777)
  {
    std::cout << "testclass::testclass()" << std::endl;
  }

  testclass(int i)
    : a_(777)
  {
    std::cout << "testclass::testclass(int):" << i << std::endl;
  }

  std::vector<std::string> print(std::string msg) const
  {
    std::cout << "hello world!: " << msg << std::endl;

    return { 10, "bla!!!" };
  }

  std::tuple<int, std::string, char const*> print(int i)
  {
    std::cout << i << std::endl;

    return std::make_tuple(9, "huh?", "tralala");
  }

  int const& a()
  {
    std::cout << "getter called" << std::endl;

    return a_;
  }

  void set_a(int i)
  {
    std::cout << "setter called: " << i << std::endl;

    a_ = i;
  }

  std::string const& test_array(std::array<int, 10> const& a)
  {
    std::cout << a[0] << std::endl;

    s_ = "blablabla";

    return s_;
  }

  testclass* pointer()
  {
    return this;
  }

  testclass& reference()
  {
    return *this;
  }

private:
  int a_;
  std::string s_;
};

int main(int argc, char* argv[])
{
  lua_State* L(luaL_newstate());

  luaL_openlibs(L);

  lualite::module(L,
    lualite::class_<testbase>("testbase")
      .def("dummy", &testbase::dummy),
    lualite::class_<testclass>("testclass")
      .constructor("defaultNew")
      .constructor<int>()
      .inherits<testbase>()
      .enum_("smell", 9)
      .def("print", (std::tuple<int, std::string, char const*> (testclass::*)(int))&testclass::print)
      .def("print_", (std::vector<std::string> (testclass::*)(std::string) const)&testclass::print)
      .def("pointer", &testclass::pointer)
      .def("reference", &testclass::reference)
      .property("a", &testclass::a, &testclass::set_a)
      .def("test_array", &testclass::test_array),
    lualite::scope("subscope",
      lualite::class_<testclass>("testclass")
        .constructor<>("defaultNew")
        .constructor<int>()
        .enum_("smell", 10)
        .def("testfunc", &testfunc)
        .def("print", (std::tuple<int, std::string, char const*> (testclass::*)(int))&testclass::print)
        .def("print_", (std::vector<std::string> (testclass::*)(std::string) const)&testclass::print)
    )
  )
  .enum_("apple", 1)
  .def("testfunc", &testfunc);

  luaL_dostring(
    L,
    "local a = testfunc(3)\n"
    "print(a.y)\n"
    "print(apple)\n"
    "print(testclass.__classname)\n"
    "print(testclass.smell)\n"
    "local b = testclass.defaultNew()\n"
    "print(\"---\")\n"
    "print(b.a)\n"
    "b:reference().a = 888\n"
    "print(b.a .. \" \" .. b:dummy(\"test\"))\n"
    "local tmp1, tmp2, tmp3 = b:pointer():print(100)\n"
    "print(tmp1 .. \" \" .. tmp2 .. \" \" .. tmp3)\n"
    "b:reference():print_(\"msg1\")\n"
    "local a = subscope.testclass.new(1111)\n"
    "print(subscope.testclass.smell)\n"
    "subscope.testclass.testfunc(200)\n"
    "local c = a:reference():print_(\"msg2\")\n"
    "print(c[10])\n"
    "r = {}"
    "for i = 1, 10 do\n"
    "  r[i] = 7\n"
    "end\n"
    "print(a:test_array(r))\n"
  );

  lua_close(L);

  return EXIT_SUCCESS;
}
<commit_msg>test fix<commit_after>#include <cstdlib>

#include <iostream>

extern "C" {

#include "lua/lualib.h"

}

#include "lualite/lualite.hpp"

struct point
{
  int x;
  int y;
};

inline int set_result(lua_State* const L, point p)
{
  using namespace ::lualite::detail;

  lua_createtable(L, 2, 0);

  lua_pushliteral(L, "x");
  set_result(L, const_cast<decltype(p.x) const&>(p.x));
  assert(lua_istable(L, -3));
  lua_rawset(L, -3);

  lua_pushliteral(L, "y");
  set_result(L, const_cast<decltype(p.y) const&>(p.y));
  assert(lua_istable(L, -3));
  lua_rawset(L, -3);

  return 1;
}

template <std::size_t I, typename T>
inline typename std::enable_if<
  std::is_same<T, point>::value, point>::type
get_arg(lua_State* const L)
{
  using namespace ::lualite::detail;

  assert(lua_istable(L, I));

  struct point p;

  lua_pushliteral(L, "x");
  lua_rawget(L, -2);
  p.x = lua_tointeger(L, -1);

  lua_pushliteral(L, "y");
  lua_rawget(L, -2);
  p.y = lua_tointeger(L, -1);

  return p;
}

point testfunc(int i, int j, int k)
{
  std::cout << "testfunc(): " << i << " " << j << " " << k << std::endl;

  return {-1, -222};
}

struct testbase
{
  std::string dummy(std::string msg)
  {
    return { "dummy() called: " + msg };
  }
};

struct testclass : testbase
{
  testclass()
    : a_(777)
  {
    std::cout << "testclass::testclass()" << std::endl;
  }

  testclass(int i)
    : a_(777)
  {
    std::cout << "testclass::testclass(int):" << i << std::endl;
  }

  std::vector<std::string> print(std::string msg) const
  {
    std::cout << "hello world!: " << msg << std::endl;

    return { 10, "bla!!!" };
  }

  std::tuple<int, std::string, char const*> print(int i)
  {
    std::cout << i << std::endl;

    return std::make_tuple(9, "huh?", "tralala");
  }

  int const& a()
  {
    std::cout << "getter called" << std::endl;

    return a_;
  }

  void set_a(int i)
  {
    std::cout << "setter called: " << i << std::endl;

    a_ = i;
  }

  std::string const& test_array(std::array<int, 10> const& a)
  {
    std::cout << a[0] << std::endl;

    s_ = "blablabla";

    return s_;
  }

  testclass* pointer()
  {
    return this;
  }

  testclass& reference()
  {
    return *this;
  }

private:
  int a_;
  std::string s_;
};

int main(int argc, char* argv[])
{
  lua_State* L(luaL_newstate());

  luaL_openlibs(L);

  lualite::module(L,
    lualite::class_<testbase>("testbase")
      .def("dummy", &testbase::dummy),
    lualite::class_<testclass>("testclass")
      .constructor("defaultNew")
      .constructor<int>()
      .inherits<testbase>()
      .enum_("smell", 9)
      .def("print", (std::tuple<int, std::string, char const*> (testclass::*)(int))&testclass::print)
      .def("print_", (std::vector<std::string> (testclass::*)(std::string) const)&testclass::print)
      .def("pointer", &testclass::pointer)
      .def("reference", &testclass::reference)
      .property("a", &testclass::a, &testclass::set_a)
      .def("test_array", &testclass::test_array),
    lualite::scope("subscope",
      lualite::class_<testclass>("testclass")
        .constructor<>("defaultNew")
        .constructor<int>()
        .enum_("smell", 10)
        .def("testfunc", &testfunc)
        .def("print", (std::tuple<int, std::string, char const*> (testclass::*)(int))&testclass::print)
        .def("print_", (std::vector<std::string> (testclass::*)(std::string) const)&testclass::print)
    )
  )
  .enum_("apple", 1)
  .def("testfunc", &testfunc);

  luaL_dostring(
    L,
    "local a = testfunc(3, 2, 1)\n"
    "print(a.y)\n"
    "print(apple)\n"
    "print(testclass.__classname)\n"
    "print(testclass.smell)\n"
    "local b = testclass.defaultNew()\n"
    "print(\"---\")\n"
    "print(b.a)\n"
    "b:reference().a = 888\n"
    "print(b.a .. \" \" .. b:dummy(\"test\"))\n"
    "local tmp1, tmp2, tmp3 = b:pointer():print(100)\n"
    "print(tmp1 .. \" \" .. tmp2 .. \" \" .. tmp3)\n"
    "b:reference():print_(\"msg1\")\n"
    "local a = subscope.testclass.new(1111)\n"
    "print(subscope.testclass.smell)\n"
    "subscope.testclass.testfunc(200)\n"
    "local c = a:reference():print_(\"msg2\")\n"
    "print(c[10])\n"
    "r = {}"
    "for i = 1, 10 do\n"
    "  r[i] = 7\n"
    "end\n"
    "print(a:test_array(r))\n"
  );

  lua_close(L);

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012, British Broadcasting Corporation
 * All Rights Reserved.
 *
 * Author: Philip de Nier
 *
 * 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 the British Broadcasting Corporation 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.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <cstdlib>
#include <cstring>

#include <bmx/mxf_reader/MXFAPPInfo.h>
#include <mxf/mxf_app.h>
#include <bmx/BMXException.h>
#include <bmx/Logging.h>

using namespace std;
using namespace bmx;
using namespace mxfpp;

void MXFAPPInfo::RegisterExtensions(HeaderMetadata *header_metadata)
{
    BMX_CHECK(mxf_app_load_extensions(header_metadata->getDataModel()->getCDataModel()));
}

bool MXFAPPInfo::IsAPP(HeaderMetadata *header_metadata)
{
    return mxf_app_is_app_mxf(header_metadata->getCHeaderMetadata());
}

MXFAPPInfo::MXFAPPInfo()
{
    source_record = 0;
    lto_record = 0;
    pse_failures = 0;
    num_pse_failures = 0;
    vtr_errors = 0;
    num_vtr_errors = 0;
    digibeta_dropouts = 0;
    num_digibeta_dropouts = 0;
    timecode_breaks = 0;
    num_timecode_breaks = 0;
}

MXFAPPInfo::~MXFAPPInfo()
{
    ResetAll();
}

bool MXFAPPInfo::CheckIssues(mxfpp::HeaderMetadata *header_metadata)
{
    return mxf_app_check_issues(header_metadata->getCHeaderMetadata());

}

bool MXFAPPInfo::ReadAll(HeaderMetadata *header_metadata)
{
    ResetAll();

    if (!ReadInfo(header_metadata))
        return false;

    ReadPSEFailures(header_metadata);
    ReadVTRErrors(header_metadata);
    ReadDigiBetaDropouts(header_metadata);
    ReadTimecodeBreaks(header_metadata);

    return true;
}

bool MXFAPPInfo::ReadInfo(HeaderMetadata *header_metadata)
{
    ResetInfo();

    ArchiveMXFInfo info;
    if (!mxf_app_get_info(header_metadata->getCHeaderMetadata(), &info))
        return false;

    original_filename       = info.filename;
    if (info.haveSourceInfaxData) {
        source_record = new InfaxData;
        *source_record      = info.sourceInfaxData;
    }
    if (info.haveLTOInfaxData) {
        lto_record = new InfaxData;
        *lto_record         = info.ltoInfaxData;
    }
    vtr_error_count         = info.vtrErrorCount;
    pse_failure_count       = info.pseFailureCount;
    digibeta_dropout_count  = info.digibetaDropoutCount;
    timecode_break_count    = info.timecodeBreakCount;

    return true;
}

bool MXFAPPInfo::ReadPSEFailures(HeaderMetadata *header_metadata)
{
    ResetPSEFailures();

    return mxf_app_get_pse_failures(header_metadata->getCHeaderMetadata(), &pse_failures, &num_pse_failures);
}

bool MXFAPPInfo::ReadVTRErrors(HeaderMetadata *header_metadata)
{
    ResetVTRErrors();

    return mxf_app_get_vtr_errors(header_metadata->getCHeaderMetadata(), &vtr_errors, &num_vtr_errors);
}

bool MXFAPPInfo::ReadDigiBetaDropouts(HeaderMetadata *header_metadata)
{
    ResetDigiBetaDropouts();

    return mxf_app_get_digibeta_dropouts(header_metadata->getCHeaderMetadata(), &digibeta_dropouts, &num_digibeta_dropouts);
}

bool MXFAPPInfo::ReadTimecodeBreaks(HeaderMetadata *header_metadata)
{
    ResetTimecodeBreaks();

    return mxf_app_get_timecode_breaks(header_metadata->getCHeaderMetadata(), &timecode_breaks, &num_timecode_breaks);
}

void MXFAPPInfo::ResetAll()
{
    ResetInfo();
    ResetPSEFailures();
    ResetVTRErrors();
    ResetDigiBetaDropouts();
    ResetTimecodeBreaks();
}

void MXFAPPInfo::ResetInfo()
{
    original_filename.clear();
    delete source_record;
    source_record = 0;
    delete lto_record;
    lto_record = 0;
}

void MXFAPPInfo::ResetPSEFailures()
{
    free(pse_failures);
    pse_failures = 0;
    num_pse_failures = 0;
}

void MXFAPPInfo::ResetVTRErrors()
{
    free(vtr_errors);
    vtr_errors = 0;
    num_vtr_errors = 0;
}

void MXFAPPInfo::ResetDigiBetaDropouts()
{
    free(digibeta_dropouts);
    digibeta_dropouts = 0;
    num_digibeta_dropouts = 0;
}

void MXFAPPInfo::ResetTimecodeBreaks()
{
    free(timecode_breaks);
    timecode_breaks = 0;
    num_timecode_breaks = 0;
}

<commit_msg>mxf2raw: fix incomplete bbc archive data model<commit_after>/*
 * Copyright (C) 2012, British Broadcasting Corporation
 * All Rights Reserved.
 *
 * Author: Philip de Nier
 *
 * 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 the British Broadcasting Corporation 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.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <cstdlib>
#include <cstring>

#include <bmx/mxf_reader/MXFAPPInfo.h>
#include <mxf/mxf_app.h>
#include <bmx/BMXException.h>
#include <bmx/Logging.h>

using namespace std;
using namespace bmx;
using namespace mxfpp;

void MXFAPPInfo::RegisterExtensions(HeaderMetadata *header_metadata)
{
    BMX_CHECK(mxf_app_load_extensions(header_metadata->getDataModel()->getCDataModel()));
    header_metadata->getDataModel()->finalise();
}

bool MXFAPPInfo::IsAPP(HeaderMetadata *header_metadata)
{
    return mxf_app_is_app_mxf(header_metadata->getCHeaderMetadata());
}

MXFAPPInfo::MXFAPPInfo()
{
    source_record = 0;
    lto_record = 0;
    pse_failures = 0;
    num_pse_failures = 0;
    vtr_errors = 0;
    num_vtr_errors = 0;
    digibeta_dropouts = 0;
    num_digibeta_dropouts = 0;
    timecode_breaks = 0;
    num_timecode_breaks = 0;
}

MXFAPPInfo::~MXFAPPInfo()
{
    ResetAll();
}

bool MXFAPPInfo::CheckIssues(mxfpp::HeaderMetadata *header_metadata)
{
    return mxf_app_check_issues(header_metadata->getCHeaderMetadata());

}

bool MXFAPPInfo::ReadAll(HeaderMetadata *header_metadata)
{
    ResetAll();

    if (!ReadInfo(header_metadata))
        return false;

    ReadPSEFailures(header_metadata);
    ReadVTRErrors(header_metadata);
    ReadDigiBetaDropouts(header_metadata);
    ReadTimecodeBreaks(header_metadata);

    return true;
}

bool MXFAPPInfo::ReadInfo(HeaderMetadata *header_metadata)
{
    ResetInfo();

    ArchiveMXFInfo info;
    if (!mxf_app_get_info(header_metadata->getCHeaderMetadata(), &info))
        return false;

    original_filename       = info.filename;
    if (info.haveSourceInfaxData) {
        source_record = new InfaxData;
        *source_record      = info.sourceInfaxData;
    }
    if (info.haveLTOInfaxData) {
        lto_record = new InfaxData;
        *lto_record         = info.ltoInfaxData;
    }
    vtr_error_count         = info.vtrErrorCount;
    pse_failure_count       = info.pseFailureCount;
    digibeta_dropout_count  = info.digibetaDropoutCount;
    timecode_break_count    = info.timecodeBreakCount;

    return true;
}

bool MXFAPPInfo::ReadPSEFailures(HeaderMetadata *header_metadata)
{
    ResetPSEFailures();

    return mxf_app_get_pse_failures(header_metadata->getCHeaderMetadata(), &pse_failures, &num_pse_failures);
}

bool MXFAPPInfo::ReadVTRErrors(HeaderMetadata *header_metadata)
{
    ResetVTRErrors();

    return mxf_app_get_vtr_errors(header_metadata->getCHeaderMetadata(), &vtr_errors, &num_vtr_errors);
}

bool MXFAPPInfo::ReadDigiBetaDropouts(HeaderMetadata *header_metadata)
{
    ResetDigiBetaDropouts();

    return mxf_app_get_digibeta_dropouts(header_metadata->getCHeaderMetadata(), &digibeta_dropouts, &num_digibeta_dropouts);
}

bool MXFAPPInfo::ReadTimecodeBreaks(HeaderMetadata *header_metadata)
{
    ResetTimecodeBreaks();

    return mxf_app_get_timecode_breaks(header_metadata->getCHeaderMetadata(), &timecode_breaks, &num_timecode_breaks);
}

void MXFAPPInfo::ResetAll()
{
    ResetInfo();
    ResetPSEFailures();
    ResetVTRErrors();
    ResetDigiBetaDropouts();
    ResetTimecodeBreaks();
}

void MXFAPPInfo::ResetInfo()
{
    original_filename.clear();
    delete source_record;
    source_record = 0;
    delete lto_record;
    lto_record = 0;
}

void MXFAPPInfo::ResetPSEFailures()
{
    free(pse_failures);
    pse_failures = 0;
    num_pse_failures = 0;
}

void MXFAPPInfo::ResetVTRErrors()
{
    free(vtr_errors);
    vtr_errors = 0;
    num_vtr_errors = 0;
}

void MXFAPPInfo::ResetDigiBetaDropouts()
{
    free(digibeta_dropouts);
    digibeta_dropouts = 0;
    num_digibeta_dropouts = 0;
}

void MXFAPPInfo::ResetTimecodeBreaks()
{
    free(timecode_breaks);
    timecode_breaks = 0;
    num_timecode_breaks = 0;
}

<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright (C) 2017 Kitsune Ral <kitsune-ral@users.sf.net>
 *
 * 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
 */

#include "avatar.h"

#include "jobs/mediathumbnailjob.h"
#include "events/eventcontent.h"
#include "connection.h"

#include <QtGui/QPainter>
#include <QtCore/QPointer>

using namespace QMatrixClient;

class Avatar::Private
{
    public:
        explicit Private(QIcon di, QUrl url = {})
            : _defaultIcon(di), _url(url)
        { }
        QImage get(Connection* connection, QSize size,
                   get_callback_t callback) const;
        bool upload(UploadContentJob* job, upload_callback_t callback);

        bool checkUrl(QUrl url) const;

        const QIcon _defaultIcon;
        QUrl _url;

        // The below are related to image caching, hence mutable
        mutable QImage _originalImage;
        mutable std::vector<QPair<QSize, QImage>> _scaledImages;
        mutable QSize _requestedSize;
        mutable bool _bannedUrl = false;
        mutable bool _fetched = false;
        mutable QPointer<MediaThumbnailJob> _thumbnailRequest = nullptr;
        mutable QPointer<BaseJob> _uploadRequest = nullptr;
        mutable std::vector<get_callback_t> callbacks;
        mutable get_callback_t uploadCallback;
};

Avatar::Avatar(QIcon defaultIcon)
    : d(std::make_unique<Private>(std::move(defaultIcon)))
{ }

Avatar::Avatar(QUrl url, QIcon defaultIcon)
    : d(std::make_unique<Private>(std::move(defaultIcon), std::move(url)))
{ }

Avatar::Avatar(Avatar&&) = default;

Avatar::~Avatar() = default;

Avatar& Avatar::operator=(Avatar&&) = default;

QImage Avatar::get(Connection* connection, int dimension,
                   get_callback_t callback) const
{
    return d->get(connection, {dimension, dimension}, callback);
}

QImage Avatar::get(Connection* connection, int width, int height,
                   get_callback_t callback) const
{
    return d->get(connection, {width, height}, callback);
}

bool Avatar::upload(Connection* connection, const QString& fileName,
                    upload_callback_t callback) const
{
    if (isJobRunning(d->_uploadRequest))
        return false;
    return d->upload(connection->uploadFile(fileName), callback);
}

bool Avatar::upload(Connection* connection, QIODevice* source,
                    upload_callback_t callback) const
{
    if (isJobRunning(d->_uploadRequest) || !source->isReadable())
        return false;
    return d->upload(connection->uploadContent(source), callback);
}

QString Avatar::mediaId() const
{
    return d->_url.authority() + d->_url.path();
}

QImage Avatar::Private::get(Connection* connection, QSize size,
                            get_callback_t callback) const
{
    // FIXME: Alternating between longer-width and longer-height requests
    // is a sure way to trick the below code into constantly getting another
    // image from the server because the existing one is alleged unsatisfactory.
    // This is plain abuse by the client, though; so not critical for now.
    if( ( !(_fetched || _thumbnailRequest)
          || size.width() > _requestedSize.width()
          || size.height() > _requestedSize.height() ) && checkUrl(_url) )
    {
        qCDebug(MAIN) << "Getting avatar from" << _url.toString();
        _requestedSize = size;
        if (isJobRunning(_thumbnailRequest))
            _thumbnailRequest->abandon();
        callbacks.emplace_back(std::move(callback));
        _thumbnailRequest = connection->getThumbnail(_url, size);
        QObject::connect( _thumbnailRequest, &MediaThumbnailJob::success, [this]
        {
            _fetched = true;
            _originalImage = _thumbnailRequest->scaledThumbnail(_requestedSize);
            _scaledImages.clear();
            for (auto n: callbacks)
                n();
        });
    }

    if( _originalImage.isNull() )
    {
        if (_defaultIcon.isNull())
            return _originalImage;

        QPainter p { &_originalImage };
        _defaultIcon.paint(&p, { QPoint(), _defaultIcon.actualSize(size) });
    }

    for (auto p: _scaledImages)
        if (p.first == size)
            return p.second;
    auto result = _originalImage.scaled(size,
                    Qt::KeepAspectRatio, Qt::SmoothTransformation);
    _scaledImages.emplace_back(size, result);
    return result;
}

bool Avatar::Private::upload(UploadContentJob* job, upload_callback_t callback)
{
    _uploadRequest = job;
    if (!isJobRunning(_uploadRequest))
        return false;
    _uploadRequest->connect(_uploadRequest, &BaseJob::success,
                            [job,callback] { callback(job->contentUri()); });
    return true;
}

bool Avatar::Private::checkUrl(QUrl url) const
{
    if (_bannedUrl || url.isEmpty())
        return false;

    // FIXME: Make "mxc" a library-wide constant and maybe even make
    // the URL checker a Connection(?) method.
    _bannedUrl = !(url.isValid() &&
            url.scheme() == "mxc" && url.path().count('/') == 1);
    if (_bannedUrl)
        qCWarning(MAIN) << "Avatar URL is invalid or not mxc-based:"
                        << url.toDisplayString();
    return !_bannedUrl;
}

QUrl Avatar::url() const { return d->_url; }

bool Avatar::updateUrl(const QUrl& newUrl)
{
    if (newUrl == d->_url)
        return false;

    d->_url = newUrl;
    d->_fetched = false;
    if (isJobRunning(d->_thumbnailRequest))
        d->_thumbnailRequest->abandon();
    return true;
}

<commit_msg>Avatar: clear the list of callbacks after completion + general code cleanup<commit_after>#include <utility>

/******************************************************************************
 * Copyright (C) 2017 Kitsune Ral <kitsune-ral@users.sf.net>
 *
 * 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
 */

#include "avatar.h"

#include "jobs/mediathumbnailjob.h"
#include "events/eventcontent.h"
#include "connection.h"

#include <QtGui/QPainter>
#include <QtCore/QPointer>

using namespace QMatrixClient;
using std::move;

class Avatar::Private
{
    public:
        explicit Private(QIcon di, QUrl url = {})
            : _defaultIcon(move(di)), _url(move(url))
        { }
        QImage get(Connection* connection, QSize size,
                   get_callback_t callback) const;
        bool upload(UploadContentJob* job, upload_callback_t callback);

        bool checkUrl(QUrl url) const;

        const QIcon _defaultIcon;
        QUrl _url;

        // The below are related to image caching, hence mutable
        mutable QImage _originalImage;
        mutable std::vector<QPair<QSize, QImage>> _scaledImages;
        mutable QSize _requestedSize;
        mutable bool _bannedUrl = false;
        mutable bool _fetched = false;
        mutable QPointer<MediaThumbnailJob> _thumbnailRequest = nullptr;
        mutable QPointer<BaseJob> _uploadRequest = nullptr;
        mutable std::vector<get_callback_t> callbacks;
};

Avatar::Avatar(QIcon defaultIcon)
    : d(std::make_unique<Private>(std::move(defaultIcon)))
{ }

Avatar::Avatar(QUrl url, QIcon defaultIcon)
    : d(std::make_unique<Private>(std::move(defaultIcon), std::move(url)))
{ }

Avatar::Avatar(Avatar&&) = default;

Avatar::~Avatar() = default;

Avatar& Avatar::operator=(Avatar&&) = default;

QImage Avatar::get(Connection* connection, int dimension,
                   get_callback_t callback) const
{
    return d->get(connection, {dimension, dimension}, move(callback));
}

QImage Avatar::get(Connection* connection, int width, int height,
                   get_callback_t callback) const
{
    return d->get(connection, {width, height}, move(callback));
}

bool Avatar::upload(Connection* connection, const QString& fileName,
                    upload_callback_t callback) const
{
    if (isJobRunning(d->_uploadRequest))
        return false;
    return d->upload(connection->uploadFile(fileName), move(callback));
}

bool Avatar::upload(Connection* connection, QIODevice* source,
                    upload_callback_t callback) const
{
    if (isJobRunning(d->_uploadRequest) || !source->isReadable())
        return false;
    return d->upload(connection->uploadContent(source), move(callback));
}

QString Avatar::mediaId() const
{
    return d->_url.authority() + d->_url.path();
}

QImage Avatar::Private::get(Connection* connection, QSize size,
                            get_callback_t callback) const
{
    // FIXME: Alternating between longer-width and longer-height requests
    // is a sure way to trick the below code into constantly getting another
    // image from the server because the existing one is alleged unsatisfactory.
    // This is plain abuse by the client, though; so not critical for now.
    if( ( !(_fetched || _thumbnailRequest)
          || size.width() > _requestedSize.width()
          || size.height() > _requestedSize.height() ) && checkUrl(_url) )
    {
        qCDebug(MAIN) << "Getting avatar from" << _url.toString();
        _requestedSize = size;
        if (isJobRunning(_thumbnailRequest))
            _thumbnailRequest->abandon();
        callbacks.emplace_back(move(callback));
        _thumbnailRequest = connection->getThumbnail(_url, size);
        QObject::connect( _thumbnailRequest, &MediaThumbnailJob::success,
            _thumbnailRequest, [this] {
                _fetched = true;
                _originalImage =
                        _thumbnailRequest->scaledThumbnail(_requestedSize);
                _scaledImages.clear();
                for (const auto& n: callbacks)
                    n();
                callbacks.clear();
            });
    }

    if( _originalImage.isNull() )
    {
        if (_defaultIcon.isNull())
            return _originalImage;

        QPainter p { &_originalImage };
        _defaultIcon.paint(&p, { QPoint(), _defaultIcon.actualSize(size) });
    }

    for (const auto& p: _scaledImages)
        if (p.first == size)
            return p.second;
    auto result = _originalImage.scaled(size,
                    Qt::KeepAspectRatio, Qt::SmoothTransformation);
    _scaledImages.emplace_back(size, result);
    return result;
}

bool Avatar::Private::upload(UploadContentJob* job, upload_callback_t callback)
{
    _uploadRequest = job;
    if (!isJobRunning(_uploadRequest))
        return false;
    _uploadRequest->connect(_uploadRequest, &BaseJob::success, _uploadRequest,
                            [job,callback] { callback(job->contentUri()); });
    return true;
}

bool Avatar::Private::checkUrl(QUrl url) const
{
    if (_bannedUrl || url.isEmpty())
        return false;

    // FIXME: Make "mxc" a library-wide constant and maybe even make
    // the URL checker a Connection(?) method.
    _bannedUrl = !(url.isValid() &&
            url.scheme() == "mxc" && url.path().count('/') == 1);
    if (_bannedUrl)
        qCWarning(MAIN) << "Avatar URL is invalid or not mxc-based:"
                        << url.toDisplayString();
    return !_bannedUrl;
}

QUrl Avatar::url() const { return d->_url; }

bool Avatar::updateUrl(const QUrl& newUrl)
{
    if (newUrl == d->_url)
        return false;

    d->_url = newUrl;
    d->_fetched = false;
    if (isJobRunning(d->_thumbnailRequest))
        d->_thumbnailRequest->abandon();
    return true;
}

<|endoftext|>


<commit_before>// .each(...any boundValues, function callback) -> undefined

NAN_METHOD(Statement::Each) {
	Statement* stmt = Nan::ObjectWrap::Unwrap<Statement>(info.This());
	if (!(stmt->state & RETURNS_DATA)) {
		return Nan::ThrowTypeError("This statement does not return data. Use run() instead");
	}
	REQUIRE_LAST_ARGUMENT_FUNCTION(func_index, callback);
	QUERY_START(stmt, statement, STATEMENT_BIND, info, func_index);
	const bool safe_integers = (stmt->state & SAFE_INTS) != 0;
	const bool pluck = (stmt->state & PLUCK_COLUMN) != 0;
	v8::Isolate* const isolate = v8::Isolate::GetCurrent();

	stmt->db->busy = true;

	// Retrieve and feed rows.
	while (sqlite3_step(stmt->st_handle) == SQLITE_ROW) {
		v8::HandleScope scope(isolate);

		v8::Local<v8::Value> args[1];
		args[0] = pluck ? Data::GetValueJS(stmt->st_handle, 0, safe_integers)
		                : Data::GetRowJS(stmt->st_handle, safe_integers);
		v8::MaybeLocal<v8::Value> callback_return_value = callback->Call(Nan::GetCurrentContext(), Nan::Null(), 1, args);

		// If an exception was thrown in the callback, clean up and stop.
		if (callback_return_value.IsEmpty()) {
			sqlite3_reset(stmt->st_handle);
			stmt->db->busy = false;
			stmt->db->was_js_error = true;
			QUERY_THROW(stmt, STATEMENT_CLEAR_BINDINGS);
			return;
		}
	}

	stmt->db->busy = false;

	if (sqlite3_reset(stmt->st_handle) == SQLITE_OK) {
		QUERY_RETURN(stmt, STATEMENT_CLEAR_BINDINGS, Nan::Undefined());
	}
	QUERY_THROW(stmt, STATEMENT_CLEAR_BINDINGS);
}
<commit_msg>perf tweak<commit_after>// .each(...any boundValues, function callback) -> undefined

NAN_METHOD(Statement::Each) {
	Statement* stmt = Nan::ObjectWrap::Unwrap<Statement>(info.This());
	if (!(stmt->state & RETURNS_DATA)) {
		return Nan::ThrowTypeError("This statement does not return data. Use run() instead");
	}
	REQUIRE_LAST_ARGUMENT_FUNCTION(func_index, callback);
	QUERY_START(stmt, statement, STATEMENT_BIND, info, func_index);
	const bool safe_integers = (stmt->state & SAFE_INTS) != 0;
	const bool pluck = (stmt->state & PLUCK_COLUMN) != 0;
	v8::Isolate* const isolate = info.GetIsolate();

	stmt->db->busy = true;

	// Retrieve and feed rows.
	while (sqlite3_step(stmt->st_handle) == SQLITE_ROW) {
		v8::HandleScope scope(isolate);

		v8::Local<v8::Value> args[1];
		args[0] = pluck ? Data::GetValueJS(stmt->st_handle, 0, safe_integers)
		                : Data::GetRowJS(stmt->st_handle, safe_integers);
		v8::MaybeLocal<v8::Value> callback_return_value = callback->Call(Nan::GetCurrentContext(), Nan::Null(), 1, args);

		// If an exception was thrown in the callback, clean up and stop.
		if (callback_return_value.IsEmpty()) {
			sqlite3_reset(stmt->st_handle);
			stmt->db->busy = false;
			stmt->db->was_js_error = true;
			QUERY_THROW(stmt, STATEMENT_CLEAR_BINDINGS);
			return;
		}
	}

	stmt->db->busy = false;

	if (sqlite3_reset(stmt->st_handle) == SQLITE_OK) {
		QUERY_RETURN(stmt, STATEMENT_CLEAR_BINDINGS, Nan::Undefined());
	}
	QUERY_THROW(stmt, STATEMENT_CLEAR_BINDINGS);
}
<|endoftext|>


<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

// 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#include "libmesh/petsc_macro.h"

// This only works with petsc-3.3 and above.
#if !PETSC_VERSION_LESS_THAN(3,3,0)

// Local Includes
#include "libmesh/libmesh_common.h"
#include "libmesh/nonlinear_implicit_system.h"
#include "libmesh/petsc_dm_nonlinear_solver.h"
#include "libmesh/petsc_linear_solver.h"
#include "libmesh/petsc_vector.h"
#include "libmesh/petsc_matrix.h"
#include "libmesh/dof_map.h"
#include "libmesh/preconditioner.h"

// PETSc extern definition
EXTERN_C_BEGIN
PetscErrorCode DMCreate_libMesh(DM);
EXTERN_C_END

#include <libmesh/petscdmlibmesh.h>

namespace libMesh {
  PetscBool PetscDMRegistered = PETSC_FALSE;
  void PetscDMRegister()
  {
    if (PetscDMRegistered)
      return;

    PetscErrorCode ierr;
    ierr = DMRegister(DMLIBMESH, PETSC_NULL, "DMCreate_libMesh", DMCreate_libMesh); CHKERRABORT(libMesh::COMM_WORLD, ierr);
    PetscDMRegistered = PETSC_TRUE;
  }

  template <typename T>
  PetscDMNonlinearSolver<T>::PetscDMNonlinearSolver(sys_type& system) :
    PetscNonlinearSolver<T>(system)
  {
    PetscDMRegister();
  }

  template <typename T>
  inline
  PetscDMNonlinearSolver<T>::~PetscDMNonlinearSolver ()
  {
    this->clear ();
  }

  template <typename T>
  void PetscDMNonlinearSolver<T>::init()
  {
    PetscErrorCode ierr;
    DM dm;
    this->PetscNonlinearSolver<T>::init();

    // Attaching a DM with the function and Jacobian callbacks to SNES.
    ierr = DMCreateLibMesh(libMesh::COMM_WORLD, this->system(), &dm); CHKERRABORT(libMesh::COMM_WORLD, ierr);
    ierr = DMSetFromOptions(dm);               CHKERRABORT(libMesh::COMM_WORLD, ierr);
    ierr = DMSetUp(dm);                        CHKERRABORT(libMesh::COMM_WORLD, ierr);
    ierr = SNESSetDM(this->_snes, dm);         CHKERRABORT(libMesh::COMM_WORLD, ierr);
    // SNES now owns the reference to dm.
    ierr = DMDestroy(&dm);                     CHKERRABORT(libMesh::COMM_WORLD, ierr);
    KSP ksp;
    ierr = SNESGetKSP (this->_snes, &ksp);     CHKERRABORT(libMesh::COMM_WORLD,ierr);

    // Set the tolerances for the iterative solver.  Use the user-supplied
    // tolerance for the relative residual & leave the others at default values
    ierr = KSPSetTolerances (ksp, this->initial_linear_tolerance, PETSC_DEFAULT,PETSC_DEFAULT, this->max_linear_iterations); CHKERRABORT(libMesh::COMM_WORLD,ierr);

    // Set the tolerances for the non-linear solver.
    ierr = SNESSetTolerances(this->_snes,
			     this->absolute_residual_tolerance,
			     this->relative_residual_tolerance,
			     this->absolute_step_tolerance,
			     this->max_nonlinear_iterations,
			     this->max_function_evaluations);
    CHKERRABORT(libMesh::COMM_WORLD,ierr);

    //Pull in command-line options
    KSPSetFromOptions(ksp);
    SNESSetFromOptions(this->_snes);
  }

  template <typename T>
  std::pair<unsigned int, Real>
  PetscDMNonlinearSolver<T>::solve (SparseMatrix<T>& jac_in,  // System Jacobian Matrix
				    NumericVector<T>& x_in,   // Solution vector
				    NumericVector<T>& r_in,   // Residual vector
				    const double,             // Stopping tolerance
				    const unsigned int)
  {
    START_LOG("solve()", "PetscNonlinearSolver");
    this->init ();

    // Make sure the data passed in are really of Petsc types
    libmesh_cast_ptr<PetscMatrix<T>*>(&jac_in);
    libmesh_cast_ptr<PetscVector<T>*>(&r_in);

    // Extract solution vector
    PetscVector<T>* x = libmesh_cast_ptr<PetscVector<T>*>(&x_in);

    int ierr=0;
    int n_iterations =0;

    // Should actually be a PetscReal, but I don't know which version of PETSc first introduced PetscReal
    Real final_residual_norm=0.;

    if (this->user_presolve)
      this->user_presolve(this->system());

    //Set the preconditioning matrix
    if (this->_preconditioner)
      this->_preconditioner->set_matrix(jac_in);

    ierr = SNESSolve (this->_snes, PETSC_NULL, x->vec());
    CHKERRABORT(libMesh::COMM_WORLD,ierr);

    ierr = SNESGetIterationNumber(this->_snes,&n_iterations);
    CHKERRABORT(libMesh::COMM_WORLD,ierr);

    ierr = SNESGetLinearSolveIterations(this->_snes, &this->_n_linear_iterations);
    CHKERRABORT(libMesh::COMM_WORLD,ierr);

    ierr = SNESGetFunctionNorm(this->_snes,&final_residual_norm);
    CHKERRABORT(libMesh::COMM_WORLD,ierr);

    // Get and store the reason for convergence
    SNESGetConvergedReason(this->_snes, &this->_reason);

    //Based on Petsc 2.3.3 documentation all diverged reasons are negative
    this->converged = (this->_reason >= 0);

    this->clear();

    STOP_LOG("solve()", "PetscNonlinearSolver");

    // return the # of its. and the final residual norm.
    return std::make_pair(n_iterations, final_residual_norm);
  }

  //------------------------------------------------------------------
  // Explicit instantiations
  template class PetscDMNonlinearSolver<Number>;

} // namespace libMesh

#endif // #if !PETSC_VERSION_LESS_THAN(3,3,0)
<commit_msg>Changes in petsc_dm_nonlinear_solver.C for -Wshadow.<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

// 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#include "libmesh/petsc_macro.h"

// This only works with petsc-3.3 and above.
#if !PETSC_VERSION_LESS_THAN(3,3,0)

// Local Includes
#include "libmesh/libmesh_common.h"
#include "libmesh/nonlinear_implicit_system.h"
#include "libmesh/petsc_dm_nonlinear_solver.h"
#include "libmesh/petsc_linear_solver.h"
#include "libmesh/petsc_vector.h"
#include "libmesh/petsc_matrix.h"
#include "libmesh/dof_map.h"
#include "libmesh/preconditioner.h"

// PETSc extern definition
EXTERN_C_BEGIN
PetscErrorCode DMCreate_libMesh(DM);
EXTERN_C_END

#include <libmesh/petscdmlibmesh.h>

namespace libMesh {
  PetscBool PetscDMRegistered = PETSC_FALSE;
  void PetscDMRegister()
  {
    if (PetscDMRegistered)
      return;

    PetscErrorCode ierr;
    ierr = DMRegister(DMLIBMESH, PETSC_NULL, "DMCreate_libMesh", DMCreate_libMesh); CHKERRABORT(libMesh::COMM_WORLD, ierr);
    PetscDMRegistered = PETSC_TRUE;
  }

  template <typename T>
  PetscDMNonlinearSolver<T>::PetscDMNonlinearSolver(sys_type& system_in) :
    PetscNonlinearSolver<T>(system_in)
  {
    PetscDMRegister();
  }

  template <typename T>
  inline
  PetscDMNonlinearSolver<T>::~PetscDMNonlinearSolver ()
  {
    this->clear ();
  }

  template <typename T>
  void PetscDMNonlinearSolver<T>::init()
  {
    PetscErrorCode ierr;
    DM dm;
    this->PetscNonlinearSolver<T>::init();

    // Attaching a DM with the function and Jacobian callbacks to SNES.
    ierr = DMCreateLibMesh(libMesh::COMM_WORLD, this->system(), &dm); CHKERRABORT(libMesh::COMM_WORLD, ierr);
    ierr = DMSetFromOptions(dm);               CHKERRABORT(libMesh::COMM_WORLD, ierr);
    ierr = DMSetUp(dm);                        CHKERRABORT(libMesh::COMM_WORLD, ierr);
    ierr = SNESSetDM(this->_snes, dm);         CHKERRABORT(libMesh::COMM_WORLD, ierr);
    // SNES now owns the reference to dm.
    ierr = DMDestroy(&dm);                     CHKERRABORT(libMesh::COMM_WORLD, ierr);
    KSP ksp;
    ierr = SNESGetKSP (this->_snes, &ksp);     CHKERRABORT(libMesh::COMM_WORLD,ierr);

    // Set the tolerances for the iterative solver.  Use the user-supplied
    // tolerance for the relative residual & leave the others at default values
    ierr = KSPSetTolerances (ksp, this->initial_linear_tolerance, PETSC_DEFAULT,PETSC_DEFAULT, this->max_linear_iterations); CHKERRABORT(libMesh::COMM_WORLD,ierr);

    // Set the tolerances for the non-linear solver.
    ierr = SNESSetTolerances(this->_snes,
			     this->absolute_residual_tolerance,
			     this->relative_residual_tolerance,
			     this->absolute_step_tolerance,
			     this->max_nonlinear_iterations,
			     this->max_function_evaluations);
    CHKERRABORT(libMesh::COMM_WORLD,ierr);

    //Pull in command-line options
    KSPSetFromOptions(ksp);
    SNESSetFromOptions(this->_snes);
  }

  template <typename T>
  std::pair<unsigned int, Real>
  PetscDMNonlinearSolver<T>::solve (SparseMatrix<T>& jac_in,  // System Jacobian Matrix
				    NumericVector<T>& x_in,   // Solution vector
				    NumericVector<T>& r_in,   // Residual vector
				    const double,             // Stopping tolerance
				    const unsigned int)
  {
    START_LOG("solve()", "PetscNonlinearSolver");
    this->init ();

    // Make sure the data passed in are really of Petsc types
    libmesh_cast_ptr<PetscMatrix<T>*>(&jac_in);
    libmesh_cast_ptr<PetscVector<T>*>(&r_in);

    // Extract solution vector
    PetscVector<T>* x = libmesh_cast_ptr<PetscVector<T>*>(&x_in);

    int ierr=0;
    int n_iterations =0;

    // Should actually be a PetscReal, but I don't know which version of PETSc first introduced PetscReal
    Real final_residual_norm=0.;

    if (this->user_presolve)
      this->user_presolve(this->system());

    //Set the preconditioning matrix
    if (this->_preconditioner)
      this->_preconditioner->set_matrix(jac_in);

    ierr = SNESSolve (this->_snes, PETSC_NULL, x->vec());
    CHKERRABORT(libMesh::COMM_WORLD,ierr);

    ierr = SNESGetIterationNumber(this->_snes,&n_iterations);
    CHKERRABORT(libMesh::COMM_WORLD,ierr);

    ierr = SNESGetLinearSolveIterations(this->_snes, &this->_n_linear_iterations);
    CHKERRABORT(libMesh::COMM_WORLD,ierr);

    ierr = SNESGetFunctionNorm(this->_snes,&final_residual_norm);
    CHKERRABORT(libMesh::COMM_WORLD,ierr);

    // Get and store the reason for convergence
    SNESGetConvergedReason(this->_snes, &this->_reason);

    //Based on Petsc 2.3.3 documentation all diverged reasons are negative
    this->converged = (this->_reason >= 0);

    this->clear();

    STOP_LOG("solve()", "PetscNonlinearSolver");

    // return the # of its. and the final residual norm.
    return std::make_pair(n_iterations, final_residual_norm);
  }

  //------------------------------------------------------------------
  // Explicit instantiations
  template class PetscDMNonlinearSolver<Number>;

} // namespace libMesh

#endif // #if !PETSC_VERSION_LESS_THAN(3,3,0)
<|endoftext|>


<commit_before>/*      _______   __   __   __   ______   __   __   _______   __   __
 *     / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___  /\ /  |\/ /\
 *    / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
 *   / / /__   / / // / // / // / /    / ___  / // ___  / // /| ' / /
 *  / /_// /\ / /_// / // / // /_/_   / / // / // /\_/ / // / |  / /
 * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
 * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
 *
 * Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson
 *
 *                                                         Js_./
 * Per Larsson a.k.a finalman                          _RqZ{a<^_aa
 * Olof Naessn a.k.a jansem/yakslem                _asww7!uY`>  )\a//
 *                                                 _Qhm`] _f "'c  1!5m
 * Visit: http://guichan.darkbits.org             )Qk<P ` _: :+' .'  "{[
 *                                               .)j(] .d_/ '-(  P .   S
 * License: (BSD)                                <Td/Z <fP"5(\"??"\a.  .L
 * Redistribution and use in source and          _dV>ws?a-?'      ._/L  #'
 * binary forms, with or without                 )4d[#7r, .   '     )d`)[
 * modification, are permitted provided         _Q-5'5W..j/?'   -?!\)cam'
 * that the following conditions are met:       j<<WP+k/);.        _W=j f
 * 1. Redistributions of source code must       .$%w\/]Q  . ."'  .  mj$
 *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\
 *    this list of conditions and the           j(]1u<sE"L,. .   ./^ ]{a
 *    following disclaimer.                     4'_uomm\.  )L);-4     (3=
 * 2. Redistributions in binary form must        )_]X{Z('a_"a7'<a"a,  ]"[
 *    reproduce the above copyright notice,       #}<]m7`Za??4,P-"'7. ).m
 *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ/
 *    following disclaimer in the                <B!</]C)d_, '(<' .f. =C+m
 *    documentation and/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'
 *    provided with the distribution.          .w[5]' _[ /.)_-"+?   _/ <W"
 * 3. Neither the name of Guichan nor the      :$we` _! + _/ .        j?
 *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    "
 *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..
 *    from this software without specific        (js, \[QQW$QWW#?!V"".
 *    prior written permission.                    ]y:.<\..          .
 *                                                 -]n w/ '         [.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )/ )/           !
 * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY         <  (; sac    ,    '
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P"_(\?d'.,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f/<[]/  ?"
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%"'  " -'.a_ _,
 * 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.
 */

/*
 * For comments regarding functions please see the header file.
 */

#include "guichan/opengl/openglgraphics.hpp"

#if defined (_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif

#if defined (__amigaos4__)
#include <mgl/gl.h>
#define glVertex3i glVertex3f
#elif defined(__APPLE__)
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif

#include "guichan/exception.hpp"
#include "guichan/image.hpp"
#include "guichan/opengl/openglimage.hpp"

namespace gcn
{
    OpenGLGraphics::OpenGLGraphics()
    {
        setTargetPlane(640, 480);
        mAlpha = false;
    }

    OpenGLGraphics::OpenGLGraphics(int width, int height)
    {
        setTargetPlane(width, height);
    }

    OpenGLGraphics::~OpenGLGraphics()
    {

    }

    void OpenGLGraphics::_beginDraw()
    {
        glPushAttrib(
            GL_COLOR_BUFFER_BIT |
            GL_CURRENT_BIT |
            GL_DEPTH_BUFFER_BIT |
            GL_ENABLE_BIT |
            GL_FOG_BIT |
            GL_LIGHTING_BIT |
            GL_LINE_BIT |
            GL_POINT_BIT |
            GL_POLYGON_BIT |
            GL_SCISSOR_BIT |
            GL_STENCIL_BUFFER_BIT |
            GL_TEXTURE_BIT |
            GL_TRANSFORM_BIT |
            GL_POINT_BIT |
            GL_LINE_BIT
            );

        glMatrixMode(GL_MODELVIEW);
        glPushMatrix();
        glLoadIdentity();

        glMatrixMode(GL_TEXTURE);
        glPushMatrix();
        glLoadIdentity();

        glMatrixMode(GL_PROJECTION);
        glPushMatrix();
        glLoadIdentity();

        glOrtho(0.0,
                (double)mWidth,
                (double)mHeight,
                0.0,
                -1.0,
                1.0);

        glDisable(GL_LIGHTING);
        glDisable(GL_CULL_FACE);
        glDisable(GL_DEPTH_TEST);
        glDisable(GL_TEXTURE_2D);

        glEnable(GL_SCISSOR_TEST);
        glPointSize(1.0);
        glLineWidth(1.0);

        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

        glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

        pushClipArea(Rectangle(0, 0, mWidth, mHeight));
    }

    void OpenGLGraphics::_endDraw()
    {
        glMatrixMode(GL_MODELVIEW);
        glPopMatrix();

        glMatrixMode(GL_TEXTURE);
        glPopMatrix();

        glMatrixMode(GL_PROJECTION);
        glPopMatrix();

        glPopAttrib();

        popClipArea();
    }

    bool OpenGLGraphics::pushClipArea(Rectangle area)
    {
        bool result = Graphics::pushClipArea(area);

        glScissor(mClipStack.top().x,
                  mHeight - mClipStack.top().y - mClipStack.top().height,
                  mClipStack.top().width,
                  mClipStack.top().height);

        return result;
    }

    void OpenGLGraphics::popClipArea()
    {
        Graphics::popClipArea();

        if (mClipStack.empty())
        {
            return;
        }

        glScissor(mClipStack.top().x,
                  mHeight - mClipStack.top().y - mClipStack.top().height,
                  mClipStack.top().width,
                  mClipStack.top().height);
    }

    void OpenGLGraphics::setTargetPlane(int width, int height)
    {
        mWidth = width;
        mHeight = height;
    }

    void OpenGLGraphics::drawImage(const Image* image,
                                   int srcX,
                                   int srcY,
                                   int dstX,
                                   int dstY,
                                   int width,
                                   int height)
    {
		const OpenGLImage* srcImage = dynamic_cast<const OpenGLImage*>(image);

        if (srcImage == NULL)
        {
            throw GCN_EXCEPTION("Trying to draw an image of unknown format, must be an OpenGLImage.");
        }

        if (mClipStack.empty())
        {
            throw GCN_EXCEPTION("Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?");
        }

        const ClipRectangle& top = mClipStack.top();

        dstX += top.xOffset;
        dstY += top.yOffset;

        // Find OpenGL texture coordinates
        float texX1 = srcX / (float)srcImage->getTextureWidth();
        float texY1 = srcY / (float)srcImage->getTextureHeight();
        float texX2 = (srcX+width) / (float)srcImage->getTextureWidth();
        float texY2 = (srcY+height) / (float)srcImage->getTextureHeight();

        glBindTexture(GL_TEXTURE_2D, srcImage->getTextureHandle());

        glEnable(GL_TEXTURE_2D);

        // Check if blending already is enabled
        if (!mAlpha)
        {
            glEnable(GL_BLEND);
        }

        // Draw a textured quad -- the image
        glBegin(GL_QUADS);
        glTexCoord2f(texX1, texY1);
        glVertex3i(dstX, dstY, 0);

        glTexCoord2f(texX1, texY2);
        glVertex3i(dstX, dstY + height, 0);

        glTexCoord2f(texX2, texY2);
        glVertex3i(dstX + width, dstY + height, 0);

        glTexCoord2f(texX2, texY1);
        glVertex3i(dstX + width, dstY, 0);
        glEnd();
        glDisable(GL_TEXTURE_2D);

        // Don't disable blending if the color has alpha
        if (!mAlpha)
        {
            glDisable(GL_BLEND);
        }
    }

    void OpenGLGraphics::drawPoint(int x, int y)
    {
        if (mClipStack.empty())
        {
            throw GCN_EXCEPTION("Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?");
        }

        const ClipRectangle& top = mClipStack.top();

        x += top.xOffset;
        y += top.yOffset;

        glBegin(GL_POINTS);
        glVertex3i(x, y, 0);
        glEnd();
    }

    void OpenGLGraphics::drawLine(int x1, int y1, int x2, int y2)
    {
        if (mClipStack.empty())
        {
            throw GCN_EXCEPTION("Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?");
        }

        const ClipRectangle& top = mClipStack.top();

        x1 += top.xOffset;
        y1 += top.yOffset;
        x2 += top.xOffset;
        y2 += top.yOffset;

        glBegin(GL_LINES);
        glVertex3f(x1 + 0.5f - 1, y1 + 0.5f, 0.0f);
        glVertex3f(x2 + 0.5f + 1, y2 + 0.5f, 0.0f);
        glEnd();

        glBegin(GL_POINTS);
        glVertex3f(x1 + 0.5f, y1 + 0.5f, 0.0f);
        glEnd();

        glBegin(GL_POINTS);
        glVertex3f(x2 + 0.5f, y2 + 0.5f, 0.0f);
        glEnd();
    }

    void OpenGLGraphics::drawRectangle(const Rectangle& rectangle)
    {
        if (mClipStack.empty())
        {
            throw GCN_EXCEPTION("Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?");
        }

        const ClipRectangle& top = mClipStack.top();

        glBegin(GL_LINE_LOOP);
        glVertex3f(rectangle.x + top.xOffset + 0.5f,
                   rectangle.y + top.yOffset + 0.5f,
                   0);
        glVertex3f(rectangle.x + rectangle.width - 0.5f + top.xOffset,
                   rectangle.y + top.yOffset + 0.5f,
                   0);
        glVertex3f(rectangle.x + rectangle.width - 0.5f + top.xOffset,
                   rectangle.y + rectangle.height + top.yOffset - 0.5f,
                   0);
        glVertex3f(rectangle.x + top.xOffset + 0.5f,
                   rectangle.y + rectangle.height + top.yOffset - 0.5f,
                   0);
        glEnd();
    }

    void OpenGLGraphics::fillRectangle(const Rectangle& rectangle)
    {
        if (mClipStack.empty())
        {
            throw GCN_EXCEPTION("Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?");
        }

        const ClipRectangle& top = mClipStack.top();

        glBegin(GL_QUADS);
        glVertex3i(rectangle.x + top.xOffset,
                   rectangle.y + top.yOffset,
                   0);
        glVertex3i(rectangle.x + rectangle.width + top.xOffset,
                   rectangle.y + top.yOffset,
                   0);
        glVertex3i(rectangle.x + rectangle.width + top.xOffset,
                   rectangle.y + rectangle.height + top.yOffset,
                   0);
        glVertex3i(rectangle.x + top.xOffset,
                   rectangle.y + rectangle.height + top.yOffset,
                   0);
        glEnd();
    }

    void OpenGLGraphics::setColor(const Color& color)
    {
        mColor = color;
        glColor4ub(color.r, color.g, color.b, color.a);

        mAlpha = color.a != 255;

        if (mAlpha)
        {
            glEnable(GL_BLEND);
        }
    }

    const Color& OpenGLGraphics::getColor() const
    {
        return mColor;
    }
}
<commit_msg>Issue 6 has been fixed.<commit_after>/*      _______   __   __   __   ______   __   __   _______   __   __
 *     / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___  /\ /  |\/ /\
 *    / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
 *   / / /__   / / // / // / // / /    / ___  / // ___  / // /| ' / /
 *  / /_// /\ / /_// / // / // /_/_   / / // / // /\_/ / // / |  / /
 * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
 * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
 *
 * Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson
 *
 *                                                         Js_./
 * Per Larsson a.k.a finalman                          _RqZ{a<^_aa
 * Olof Naessn a.k.a jansem/yakslem                _asww7!uY`>  )\a//
 *                                                 _Qhm`] _f "'c  1!5m
 * Visit: http://guichan.darkbits.org             )Qk<P ` _: :+' .'  "{[
 *                                               .)j(] .d_/ '-(  P .   S
 * License: (BSD)                                <Td/Z <fP"5(\"??"\a.  .L
 * Redistribution and use in source and          _dV>ws?a-?'      ._/L  #'
 * binary forms, with or without                 )4d[#7r, .   '     )d`)[
 * modification, are permitted provided         _Q-5'5W..j/?'   -?!\)cam'
 * that the following conditions are met:       j<<WP+k/);.        _W=j f
 * 1. Redistributions of source code must       .$%w\/]Q  . ."'  .  mj$
 *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\
 *    this list of conditions and the           j(]1u<sE"L,. .   ./^ ]{a
 *    following disclaimer.                     4'_uomm\.  )L);-4     (3=
 * 2. Redistributions in binary form must        )_]X{Z('a_"a7'<a"a,  ]"[
 *    reproduce the above copyright notice,       #}<]m7`Za??4,P-"'7. ).m
 *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ/
 *    following disclaimer in the                <B!</]C)d_, '(<' .f. =C+m
 *    documentation and/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'
 *    provided with the distribution.          .w[5]' _[ /.)_-"+?   _/ <W"
 * 3. Neither the name of Guichan nor the      :$we` _! + _/ .        j?
 *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    "
 *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..
 *    from this software without specific        (js, \[QQW$QWW#?!V"".
 *    prior written permission.                    ]y:.<\..          .
 *                                                 -]n w/ '         [.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )/ )/           !
 * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY         <  (; sac    ,    '
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P"_(\?d'.,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f/<[]/  ?"
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%"'  " -'.a_ _,
 * 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.
 */

/*
 * For comments regarding functions please see the header file.
 */

#include "guichan/opengl/openglgraphics.hpp"

#if defined (_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif

#if defined (__amigaos4__)
#include <mgl/gl.h>
#define glVertex3i glVertex3f
#elif defined(__APPLE__)
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif

#include "guichan/exception.hpp"
#include "guichan/image.hpp"
#include "guichan/opengl/openglimage.hpp"

namespace gcn
{
    OpenGLGraphics::OpenGLGraphics()
    {
        setTargetPlane(640, 480);
        mAlpha = false;
    }

    OpenGLGraphics::OpenGLGraphics(int width, int height)
    {
        setTargetPlane(width, height);
    }

    OpenGLGraphics::~OpenGLGraphics()
    {

    }

    void OpenGLGraphics::_beginDraw()
    {
        glPushAttrib(
            GL_COLOR_BUFFER_BIT |
            GL_CURRENT_BIT |
            GL_DEPTH_BUFFER_BIT |
            GL_ENABLE_BIT |
            GL_FOG_BIT |
            GL_LIGHTING_BIT |
            GL_LINE_BIT |
            GL_POINT_BIT |
            GL_POLYGON_BIT |
            GL_SCISSOR_BIT |
            GL_STENCIL_BUFFER_BIT |
            GL_TEXTURE_BIT |
            GL_TRANSFORM_BIT |
            GL_POINT_BIT |
            GL_LINE_BIT
            );

        glMatrixMode(GL_MODELVIEW);
        glPushMatrix();
        glLoadIdentity();

        glMatrixMode(GL_TEXTURE);
        glPushMatrix();
        glLoadIdentity();

        glMatrixMode(GL_PROJECTION);
        glPushMatrix();
        glLoadIdentity();

        glOrtho(0.0,
                (double)mWidth,
                (double)mHeight,
                0.0,
                -1.0,
                1.0);

        glDisable(GL_LIGHTING);
        glDisable(GL_CULL_FACE);
        glDisable(GL_DEPTH_TEST);
        glDisable(GL_TEXTURE_2D);

        glEnable(GL_SCISSOR_TEST);
        glPointSize(1.0);
        glLineWidth(1.0);

        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

        glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

        pushClipArea(Rectangle(0, 0, mWidth, mHeight));
    }

    void OpenGLGraphics::_endDraw()
    {
        glMatrixMode(GL_MODELVIEW);
        glPopMatrix();

        glMatrixMode(GL_TEXTURE);
        glPopMatrix();

        glMatrixMode(GL_PROJECTION);
        glPopMatrix();

        glPopAttrib();

        popClipArea();
    }

    bool OpenGLGraphics::pushClipArea(Rectangle area)
    {
        bool result = Graphics::pushClipArea(area);

        glScissor(mClipStack.top().x,
                  mHeight - mClipStack.top().y - mClipStack.top().height,
                  mClipStack.top().width,
                  mClipStack.top().height);

        return result;
    }

    void OpenGLGraphics::popClipArea()
    {
        Graphics::popClipArea();

        if (mClipStack.empty())
        {
            return;
        }

        glScissor(mClipStack.top().x,
                  mHeight - mClipStack.top().y - mClipStack.top().height,
                  mClipStack.top().width,
                  mClipStack.top().height);
    }

    void OpenGLGraphics::setTargetPlane(int width, int height)
    {
        mWidth = width;
        mHeight = height;
    }

    void OpenGLGraphics::drawImage(const Image* image,
                                   int srcX,
                                   int srcY,
                                   int dstX,
                                   int dstY,
                                   int width,
                                   int height)
    {
		const OpenGLImage* srcImage = dynamic_cast<const OpenGLImage*>(image);

        if (srcImage == NULL)
        {
            throw GCN_EXCEPTION("Trying to draw an image of unknown format, must be an OpenGLImage.");
        }

        if (mClipStack.empty())
        {
            throw GCN_EXCEPTION("Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?");
        }

        const ClipRectangle& top = mClipStack.top();

        dstX += top.xOffset;
        dstY += top.yOffset;

        // Find OpenGL texture coordinates
        float texX1 = srcX / (float)srcImage->getTextureWidth();
        float texY1 = srcY / (float)srcImage->getTextureHeight();
        float texX2 = (srcX+width) / (float)srcImage->getTextureWidth();
        float texY2 = (srcY+height) / (float)srcImage->getTextureHeight();

        glBindTexture(GL_TEXTURE_2D, srcImage->getTextureHandle());

        glEnable(GL_TEXTURE_2D);

        // Check if blending already is enabled
        if (!mAlpha)
        {
            glEnable(GL_BLEND);
        }

        // Draw a textured quad -- the image
        glBegin(GL_QUADS);
        glTexCoord2f(texX1, texY1);
        glVertex3i(dstX, dstY, 0);

        glTexCoord2f(texX1, texY2);
        glVertex3i(dstX, dstY + height, 0);

        glTexCoord2f(texX2, texY2);
        glVertex3i(dstX + width, dstY + height, 0);

        glTexCoord2f(texX2, texY1);
        glVertex3i(dstX + width, dstY, 0);
        glEnd();
        glDisable(GL_TEXTURE_2D);

        // Don't disable blending if the color has alpha
        if (!mAlpha)
        {
            glDisable(GL_BLEND);
        }
    }

    void OpenGLGraphics::drawPoint(int x, int y)
    {
        if (mClipStack.empty())
        {
            throw GCN_EXCEPTION("Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?");
        }

        const ClipRectangle& top = mClipStack.top();

        x += top.xOffset;
        y += top.yOffset;

        glBegin(GL_POINTS);
        glVertex3i(x, y, 0);
        glEnd();
    }

    void OpenGLGraphics::drawLine(int x1, int y1, int x2, int y2)
    {
        if (mClipStack.empty())
        {
            throw GCN_EXCEPTION("Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?");
        }

        const ClipRectangle& top = mClipStack.top();

        x1 += top.xOffset;
        y1 += top.yOffset;
        x2 += top.xOffset;
        y2 += top.yOffset;

        glBegin(GL_LINES);
        glVertex2f(x1 + 0.375,
                   y1 + 0.375);
        glVertex2f(x2 + 1.0f - 0.375f,
                   y2 + 1.0f - 0.375f);
        glEnd();
    }

    void OpenGLGraphics::drawRectangle(const Rectangle& rectangle)
    {
        if (mClipStack.empty())
        {
            throw GCN_EXCEPTION("Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?");
        }

        const ClipRectangle& top = mClipStack.top();

        glBegin(GL_LINE_LOOP);
        glVertex2f(rectangle.x + top.xOffset,
                   rectangle.y + top.yOffset);
        glVertex2f(rectangle.x + rectangle.width + top.xOffset - 1.0f,
                   rectangle.y + top.yOffset + 0.375f);
        glVertex2f(rectangle.x + rectangle.width + top.xOffset - 1.0f,
                   rectangle.y + rectangle.height + top.yOffset);
        glVertex2f(rectangle.x + top.xOffset,
                   rectangle.y + rectangle.height + top.yOffset);
        glEnd();
    }

    void OpenGLGraphics::fillRectangle(const Rectangle& rectangle)
    {
        if (mClipStack.empty())
        {
            throw GCN_EXCEPTION("Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?");
        }

        const ClipRectangle& top = mClipStack.top();

        glBegin(GL_QUADS);
        glVertex2i(rectangle.x + top.xOffset,
                   rectangle.y + top.yOffset);
        glVertex2i(rectangle.x + rectangle.width + top.xOffset,
                   rectangle.y + top.yOffset);
        glVertex2i(rectangle.x + rectangle.width + top.xOffset,
                   rectangle.y + rectangle.height + top.yOffset);
        glVertex2i(rectangle.x + top.xOffset,
                   rectangle.y + rectangle.height + top.yOffset);
        glEnd();
    }

    void OpenGLGraphics::setColor(const Color& color)
    {
        mColor = color;
        glColor4ub(color.r, color.g, color.b, color.a);

        mAlpha = color.a != 255;

        if (mAlpha)
        {
            glEnable(GL_BLEND);
        }
    }

    const Color& OpenGLGraphics::getColor() const
    {
        return mColor;
    }
}
<|endoftext|>


<commit_before>#include "Matrix.h"
#include <osg/Notify>

bool readMatrix(osg::Matrix& matrix, osgDB::Input& fr, const char* keyword)
{
    bool iteratorAdvanced = false;

    if (fr[0].matchWord(keyword) && fr[1].isOpenBracket())
    {

         osg::notify(osg::NOTICE)<<"found keyword "<<fr[0].getStr()<<" looking for "<<keyword<<std::endl;

        int entry = fr[0].getNoNestedBrackets();

        fr += 2;

        int row=0;
        int col=0;
        double v;
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            if (fr[0].getFloat(v))
            {
                matrix(row,col)=v;
                ++col;
                if (col>=4)
                {
                    col = 0;
                    ++row;
                }
                ++fr;
            }
            else fr.advanceOverCurrentFieldOrBlock();
        }
        iteratorAdvanced = true;
    }

    return iteratorAdvanced;
}

bool writeMatrix(const osg::Matrix& matrix, osgDB::Output& fw, const char* keyword)
{
    fw.indent() << keyword <<" {" << std::endl;
    fw.moveIn();
    fw.indent() << matrix(0,0) << " " << matrix(0,1) << " " << matrix(0,2) << " " << matrix(0,3) << std::endl;
    fw.indent() << matrix(1,0) << " " << matrix(1,1) << " " << matrix(1,2) << " " << matrix(1,3) << std::endl;
    fw.indent() << matrix(2,0) << " " << matrix(2,1) << " " << matrix(2,2) << " " << matrix(2,3) << std::endl;
    fw.indent() << matrix(3,0) << " " << matrix(3,1) << " " << matrix(3,2) << " " << matrix(3,3) << std::endl;
    fw.moveOut();
    fw.indent() << "}"<< std::endl;
    return true;
}

<commit_msg>Removed debugging message<commit_after>#include "Matrix.h"

bool readMatrix(osg::Matrix& matrix, osgDB::Input& fr, const char* keyword)
{
    bool iteratorAdvanced = false;

    if (fr[0].matchWord(keyword) && fr[1].isOpenBracket())
    {
        int entry = fr[0].getNoNestedBrackets();

        fr += 2;

        int row=0;
        int col=0;
        double v;
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            if (fr[0].getFloat(v))
            {
                matrix(row,col)=v;
                ++col;
                if (col>=4)
                {
                    col = 0;
                    ++row;
                }
                ++fr;
            }
            else fr.advanceOverCurrentFieldOrBlock();
        }
        iteratorAdvanced = true;
    }

    return iteratorAdvanced;
}

bool writeMatrix(const osg::Matrix& matrix, osgDB::Output& fw, const char* keyword)
{
    fw.indent() << keyword <<" {" << std::endl;
    fw.moveIn();
    fw.indent() << matrix(0,0) << " " << matrix(0,1) << " " << matrix(0,2) << " " << matrix(0,3) << std::endl;
    fw.indent() << matrix(1,0) << " " << matrix(1,1) << " " << matrix(1,2) << " " << matrix(1,3) << std::endl;
    fw.indent() << matrix(2,0) << " " << matrix(2,1) << " " << matrix(2,2) << " " << matrix(2,3) << std::endl;
    fw.indent() << matrix(3,0) << " " << matrix(3,1) << " " << matrix(3,2) << " " << matrix(3,3) << std::endl;
    fw.moveOut();
    fw.indent() << "}"<< std::endl;
    return true;
}

<|endoftext|>


<commit_before>#include <iostream>

#include "camera/cameraPerspective.hpp"

int main(void)
{
    Vec3f origin = Vec3f(0,0,0);
    Vec3f view = Vec3f(1,0,0);
    Vec3f up = Vec3f(0,1,0);
    CameraPerspective* cp = new CameraPerspective(1920, 1080, origin, view, up, 0.035, 0.035);

    std::cout << cp << std::endl;
    delete cp;

    return 0;

}<commit_msg>added some tests for perspective camera<commit_after>#include <iostream>

#include "camera/cameraPerspective.hpp"

int main(void)
{
    Vec3f origin = Vec3f(0,0,0);
    Vec3f view = Vec3f(1,0,0);
    Vec3f up = Vec3f(0,1,0);
    CameraPerspective* cp = new CameraPerspective(1920, 1080, origin, view, up, 0.035, 0.035);

    std::cout << cp << std::endl;

    std::cout << "ray to 0,0 " << cp->getRay(0, 0) << std::endl;
    std::cout << "ray to 960, 540 " << cp->getRay(960, 540) << std::endl;
    std::cout << "ray to 1920, 1080 " << cp->getRay(1920, 1080) << std::endl;

    delete cp;

    return 0;

}<|endoftext|>


<commit_before>#include "explorerpage.h"
#include "ui_explorerpage.h"

#include "clientmodel.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "optionsmodel.h"
#include "transactiontablemodel.h"
#include "transactionfilterproxy.h"
#include "guiutil.h"
#include "guiconstants.h"

#include <QAbstractItemDelegate>
#include <QPainter>

#define DECORATION_SIZE 64

class ExplorerViewDelegate : public QAbstractItemDelegate
{
    Q_OBJECT
public:
    ExplorerViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC) { }

    inline void paint(QPainter *painter, const QStyleOptionViewItem &option,
                      const QModelIndex &index ) const
    {
        painter->save();

        QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
        QRect mainRect = option.rect;
        QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));
        icon.paint(painter, decorationRect);

        QColor foreground = option.palette.color(QPalette::Text);
        painter->setPen(foreground);
        painter->setPen(foreground);
        painter->setPen(option.palette.color(QPalette::Text));

        painter->restore();
    }

    inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        return QSize(DECORATION_SIZE, DECORATION_SIZE);
    }

    int unit;

};
#include "explorerpage.moc"

ExplorerPage::ExplorerPage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ExplorerPage),
    clientModel(0),
    walletModel(0),
    explorerdelegate(new ExplorerViewDelegate())
{
    ui->setupUi(this);
    nam = new QNetworkAccessManager(this);
    connect(nam,SIGNAL(finished(QNetworkReply*)),this,SLOT(finished(QNetworkReply*)));
    connect(ui->submitButton,SIGNAL(clicked()),this,SLOT(DoHttpGet()));
}

ExplorerPage::~ExplorerPage()
{
    delete ui;
}

void ExplorerPage::setClientModel(ClientModel *model)
{
    this->clientModel = model;
    if(model)
    {
    }
}

void ExplorerPage::setWalletModel(WalletModel *model)
{
    this->walletModel = model;
}

void ExplorerPage::finished(QNetworkReply *reply) {
  if(reply->error() == QNetworkReply::NoError) {
    ui->textBrowser->setText(reply->readAll());
  } else {
    ui->textBrowser->setText(reply->errorString());
  }
}

void ExplorerPage::DoHttpGet() {
  QString urltn = "http://qt.canadaecoin.net/v1.0.0.1/txn.php?";
  QString urlti = "http://qt.canadaecoin.net/v1.0.0.1/txi.php?";
  QString urla = "http://qt.canadaecoin.net/v1.0.0.1/addr.php?";
  QString urlb = "http://qt.canadaecoin.net/v1.0.0.1/block.php?";
  QString urle = "http://qt.canadaecoin.net/v1.0.0.1/error.php";
  QString data = ui->dataLine->text();
  QString final;
  int size = data.size();
  if(size == 64){
      final = urltxn + data;
  } else if(size == 68){
      final = urltxi + data;
  } else if(size == 34){
      final = urla + data;
  } else if(size >= 7){
      final = urlb + data;
  }else {
      final = urle;
  }
  QNetworkRequest req;
  QByteArray postData;
  postData.append(data.toLocal8Bit());
  req.setUrl(QUrl(final));
  req.setRawHeader("User-Agent", "CanadaeCoin QT v1.0.0.1");
  nam->get(req);
}
<commit_msg>fine tuning of UI<commit_after>#include "explorerpage.h"
#include "ui_explorerpage.h"

#include "clientmodel.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "optionsmodel.h"
#include "transactiontablemodel.h"
#include "transactionfilterproxy.h"
#include "guiutil.h"
#include "guiconstants.h"

#include <QAbstractItemDelegate>
#include <QPainter>

#define DECORATION_SIZE 64

class ExplorerViewDelegate : public QAbstractItemDelegate
{
    Q_OBJECT
public:
    ExplorerViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC) { }

    inline void paint(QPainter *painter, const QStyleOptionViewItem &option,
                      const QModelIndex &index ) const
    {
        painter->save();

        QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
        QRect mainRect = option.rect;
        QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));
        icon.paint(painter, decorationRect);

        QColor foreground = option.palette.color(QPalette::Text);
        painter->setPen(foreground);
        painter->setPen(foreground);
        painter->setPen(option.palette.color(QPalette::Text));

        painter->restore();
    }

    inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        return QSize(DECORATION_SIZE, DECORATION_SIZE);
    }

    int unit;

};
#include "explorerpage.moc"

ExplorerPage::ExplorerPage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ExplorerPage),
    clientModel(0),
    walletModel(0),
    explorerdelegate(new ExplorerViewDelegate())
{
    ui->setupUi(this);
    nam = new QNetworkAccessManager(this);
    connect(nam,SIGNAL(finished(QNetworkReply*)),this,SLOT(finished(QNetworkReply*)));
    connect(ui->submitButton,SIGNAL(clicked()),this,SLOT(DoHttpGet()));
}

ExplorerPage::~ExplorerPage()
{
    delete ui;
}

void ExplorerPage::setClientModel(ClientModel *model)
{
    this->clientModel = model;
    if(model)
    {
    }
}

void ExplorerPage::setWalletModel(WalletModel *model)
{
    this->walletModel = model;
}

void ExplorerPage::finished(QNetworkReply *reply) {
  if(reply->error() == QNetworkReply::NoError) {
    ui->textBrowser->setText(reply->readAll());
  } else {
    ui->textBrowser->setText(reply->errorString());
  }
}

void ExplorerPage::DoHttpGet() {
  QString urltxn = "http://qt.canadaecoin.net/v1.0.0.1/txn.php?";
  QString urltxi = "http://qt.canadaecoin.net/v1.0.0.1/txi.php?";
  QString urla = "http://qt.canadaecoin.net/v1.0.0.1/addr.php?";
  QString urlb = "http://qt.canadaecoin.net/v1.0.0.1/block.php?";
  QString urle = "http://qt.canadaecoin.net/v1.0.0.1/error.php";
  QString data = ui->dataLine->text();
  QString final;
  int size = data.size();
  if(size == 64){
      final = urltxn + data;
  } else if(size == 68){
      final = urltxi + data;
  } else if(size == 34){
      final = urla + data;
  } else if(size >= 7){
      final = urlb + data;
  }else {
      final = urle;
  }
  QNetworkRequest req;
  QByteArray postData;
  postData.append(data.toLocal8Bit());
  req.setUrl(QUrl(final));
  req.setRawHeader("User-Agent", "CanadaeCoin QT v1.0.0.1");
  nam->get(req);
}
<|endoftext|>