<commit_before>/*
 * Copyright 2014 Cloudius Systems
 */

#include "database.hh"
#include "core/app-template.hh"
#include "core/distributed.hh"
#include "thrift/server.hh"
#include "transport/server.hh"
#include "http/httpd.hh"
#include "api/api.hh"
#include "db/config.hh"
#include "message/messaging_service.hh"
#include "gms/failure_detector.hh"
#include "gms/gossiper.hh"

namespace bpo = boost::program_options;

static future<>
read_config(bpo::variables_map& opts, db::config& cfg) {
    if (opts.count("options-file") == 0) {
        return make_ready_future<>();
    }
    return cfg.read_from_file(opts["options-file"].as<sstring>());
}

int main(int ac, char** av) {
    app_template app;
    auto opt_add = app.add_options();

    auto cfg = make_lw_shared<db::config>();
    cfg->add_options(opt_add)
        ("api-port", bpo::value<uint16_t>()->default_value(10000), "Http Rest API port")
        // TODO : default, always read?
        ("options-file", bpo::value<sstring>(), "cassandra.yaml file to read options from")
        ;

    auto server = std::make_unique<distributed<thrift_server>>();
    distributed<database> db;
    distributed<cql3::query_processor> qp;
    service::storage_proxy proxy{db};
    api::http_context ctx;

    return app.run(ac, av, [&] {
        auto&& opts = app.configuration();
        uint16_t thrift_port = cfg->rpc_port();
        uint16_t cql_port = cfg->native_transport_port();
        uint16_t api_port = opts["api-port"].as<uint16_t>();
        sstring listen_address = cfg->listen_address();
        auto seed_provider= cfg->seed_provider();

        return read_config(opts, *cfg).then([cfg, &db]() {
            return db.start(std::move(*cfg));
        }).then([&db] {
            engine().at_exit([&db] { return db.stop(); });
            return db.invoke_on_all(&database::init_from_data_directory);
        }).then([&db, &proxy, &qp] {
            return qp.start(std::ref(proxy), std::ref(db)).then([&qp] {
                engine().at_exit([&qp] { return qp.stop(); });
            });
        }).then([&db, &proxy, &qp, cql_port, thrift_port] {
            auto cserver = new distributed<cql_server>;
            cserver->start(std::ref(proxy), std::ref(qp)).then([server = std::move(cserver), cql_port] () mutable {
                server->invoke_on_all(&cql_server::listen, ipv4_addr{cql_port});
            }).then([cql_port] {
                std::cout << "CQL server listening on port " << cql_port << " ...\n";
            });
            auto tserver = new distributed<thrift_server>;
            tserver->start(std::ref(db)).then([server = std::move(tserver), thrift_port] () mutable {
                server->invoke_on_all(&thrift_server::listen, ipv4_addr{thrift_port});
            }).then([thrift_port] {
                std::cout << "Thrift server listening on port " << thrift_port << " ...\n";
            });
        }).then([listen_address, seed_provider] {
            const gms::inet_address listen(listen_address);
            std::set<gms::inet_address> seeds;
            for (auto& x : seed_provider.parameters) {
                seeds.emplace(x.first);
            }
            net::get_messaging_service().start(listen).then([seeds] {
                auto& ms = net::get_local_messaging_service();
                print("Messaging server listening on ip %s port %d ...\n", ms.listen_address(), ms.port());
                gms::get_failure_detector().start_single().then([seeds] {
                    gms::get_gossiper().start_single().then([seeds] {
                        auto& gossiper = gms::get_local_gossiper();
                        gossiper.set_seeds(seeds);
                        using namespace std::chrono;
                        auto now = high_resolution_clock::now().time_since_epoch();
                        int generation_number = duration_cast<seconds>(now).count();
                        gossiper.start(generation_number).then([] {
                            print("Start gossiper service ...\n");
                        });
                    });
                });
            });
        }).then([&db, api_port, &ctx]{
            ctx.http_server.start().then([api_port, &ctx] {
                return set_server(ctx);
            }).then([&ctx, api_port] {
                ctx.http_server.listen(api_port);
            }).then([api_port] {
                std::cout << "Seastar HTTP server listening on port " << api_port << " ...\n";
            });
        }).or_terminate();
    });
}
<commit_msg>main: Move messaging_service init code into a helper function<commit_after>/*
 * Copyright 2014 Cloudius Systems
 */

#include "database.hh"
#include "core/app-template.hh"
#include "core/distributed.hh"
#include "thrift/server.hh"
#include "transport/server.hh"
#include "http/httpd.hh"
#include "api/api.hh"
#include "db/config.hh"
#include "message/messaging_service.hh"
#include "gms/failure_detector.hh"
#include "gms/gossiper.hh"

namespace bpo = boost::program_options;

static future<>
read_config(bpo::variables_map& opts, db::config& cfg) {
    if (opts.count("options-file") == 0) {
        return make_ready_future<>();
    }
    return cfg.read_from_file(opts["options-file"].as<sstring>());
}

void init_messaging_service(auto listen_address, auto seed_provider) {
    const gms::inet_address listen(listen_address);
    std::set<gms::inet_address> seeds;
    for (auto& x : seed_provider.parameters) {
        seeds.emplace(x.first);
    }
    net::get_messaging_service().start(listen).then([seeds] {
        auto& ms = net::get_local_messaging_service();
        print("Messaging server listening on ip %s port %d ...\n", ms.listen_address(), ms.port());
        gms::get_failure_detector().start_single().then([seeds] {
            gms::get_gossiper().start_single().then([seeds] {
                auto& gossiper = gms::get_local_gossiper();
                gossiper.set_seeds(seeds);
                using namespace std::chrono;
                auto now = high_resolution_clock::now().time_since_epoch();
                int generation_number = duration_cast<seconds>(now).count();
                gossiper.start(generation_number).then([] {
                    print("Start gossiper service ...\n");
                });
            });
        });
    });
}

int main(int ac, char** av) {
    app_template app;
    auto opt_add = app.add_options();

    auto cfg = make_lw_shared<db::config>();
    cfg->add_options(opt_add)
        ("api-port", bpo::value<uint16_t>()->default_value(10000), "Http Rest API port")
        // TODO : default, always read?
        ("options-file", bpo::value<sstring>(), "cassandra.yaml file to read options from")
        ;

    auto server = std::make_unique<distributed<thrift_server>>();
    distributed<database> db;
    distributed<cql3::query_processor> qp;
    service::storage_proxy proxy{db};
    api::http_context ctx;

    return app.run(ac, av, [&] {
        auto&& opts = app.configuration();
        uint16_t thrift_port = cfg->rpc_port();
        uint16_t cql_port = cfg->native_transport_port();
        uint16_t api_port = opts["api-port"].as<uint16_t>();
        sstring listen_address = cfg->listen_address();
        auto seed_provider= cfg->seed_provider();

        return read_config(opts, *cfg).then([cfg, &db]() {
            return db.start(std::move(*cfg));
        }).then([&db] {
            engine().at_exit([&db] { return db.stop(); });
            return db.invoke_on_all(&database::init_from_data_directory);
        }).then([&db, &proxy, &qp] {
            return qp.start(std::ref(proxy), std::ref(db)).then([&qp] {
                engine().at_exit([&qp] { return qp.stop(); });
            });
        }).then([&db, &proxy, &qp, cql_port, thrift_port] {
            auto cserver = new distributed<cql_server>;
            cserver->start(std::ref(proxy), std::ref(qp)).then([server = std::move(cserver), cql_port] () mutable {
                server->invoke_on_all(&cql_server::listen, ipv4_addr{cql_port});
            }).then([cql_port] {
                std::cout << "CQL server listening on port " << cql_port << " ...\n";
            });
            auto tserver = new distributed<thrift_server>;
            tserver->start(std::ref(db)).then([server = std::move(tserver), thrift_port] () mutable {
                server->invoke_on_all(&thrift_server::listen, ipv4_addr{thrift_port});
            }).then([thrift_port] {
                std::cout << "Thrift server listening on port " << thrift_port << " ...\n";
            });
        }).then([listen_address, seed_provider] {
            init_messaging_service(listen_address, seed_provider);
        }).then([&db, api_port, &ctx]{
            ctx.http_server.start().then([api_port, &ctx] {
                return set_server(ctx);
            }).then([&ctx, api_port] {
                ctx.http_server.listen(api_port);
            }).then([api_port] {
                std::cout << "Seastar HTTP server listening on port " << api_port << " ...\n";
            });
        }).or_terminate();
    });
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <type_traits>
#include "typestring.hh"

template<typename A, typename B>
void check() {
    printf("[%s] %s\n", std::is_same<A,B>::value ? "pass" : "fail", A::data());
}

using test1
    = irqus::typestring<'H', 'e', 'l', 'l', 'o'
                     , ' '
                     , 'w', 'o', 'r', 'l', 'd'
                     , ','
                     , ' '
                     , 'h', 'o', 'w'
                     , ' '
                     , 'i', 's'
                     , ' '
                     , 'i', 't'
                     , ' '
                     , 'g', 'o', 'i', 'n', 'g', '?'>;

using test2
    = irqus::typestring<'u', 'p', 'p', 'e', 'r', 'c', 'a', 's', 'e'
                       , ':'
                       , ' '
                       , 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'
                       , 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V'
                       , 'W', 'X', 'Y', 'Z' >;
using test3
    = irqus::typestring< 'l', 'o', 'w', 'e', 'r', 'c', 'a', 's', 'e'
                       , ':'
                       , ' '
                       , 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'
                       , 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v'
                       , 'w', 'x', 'y', 'z' >;
using test4
    = irqus::typestring< 'f', 'l','o', 'a', 't', 'i', 'n', 'g'
                       , ' '
                       , ':'
                       , ' '
                       , '1', '2', '3', '4', '5', '6', '7', '8', '9'
                       , '.'
                       , '1', '2', '3', '4', '5', '6', '7', '8', '9'
                       , '+'
                       , 'e', '-', '1', '2', '3', '4'>;
using test5
    = irqus::typestring< 's', 'y', 'm', 'b', 'o', 'l', 's'
                       , ' '
                       , ' '
                       , ':'
                       , ' '
                       , '~', '`', '!', '@', '#', '$', '%', '^', '&', '*', '('
                       , ')', '_', '+', '=','-', '[', ']', '\\', '{', '}', '|'
                       , ':', ';', '\'', ',', '.', '?', '/'>;

int main() {
    check<typestring_is("Hello world, how is it going?"),test1>();
    check<typestring_is("uppercase: ABCDEFGHIJKLMNOPQRSTUVWXYZ"),test2>();
    check<typestring_is("lowercase: abcdefghijklmnopqrstuvwxyz"),test3>();
    check<typestring_is("floating : 123456789.123456789+e-1234"),test4>();
    check<typestring_is("symbols  : ~`!@#$%^&*()_+=-[]\\{}|:;',.?/"),test5>();
    check<typestring_is(""),irqus::typestring<'\0'>>(); // null!
    check<irqus::tycat< typestring_is("ABC")
                      , typestring_is("DEF")
                      , typestring_is("1234")>
                      , typestring_is("ABCDEF1234") >();
    return {};
}
<commit_msg>More formatting stuff<commit_after>#include <cstdio>
#include <type_traits>
#include "typestring.hh"

template<typename A, typename B>
void check() {
    printf("[%s] %s\n", std::is_same<A,B>::value ? "pass" : "fail", A::data());
}

using test1
    = irqus::typestring<'H', 'e', 'l', 'l', 'o'
                     , ' '
                     , 'w', 'o', 'r', 'l', 'd'
                     , ','
                     , ' '
                     , 'h', 'o', 'w'
                     , ' '
                     , 'i', 's'
                     , ' '
                     , 'i', 't'
                     , ' '
                     , 'g', 'o', 'i', 'n', 'g', '?'>;

using test2
    = irqus::typestring<'u', 'p', 'p', 'e', 'r', 'c', 'a', 's', 'e'
                       , ':'
                       , ' '
                       , 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'
                       , 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V'
                       , 'W', 'X', 'Y', 'Z' >;
using test3
    = irqus::typestring< 'l', 'o', 'w', 'e', 'r', 'c', 'a', 's', 'e'
                       , ':'
                       , ' '
                       , 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'
                       , 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v'
                       , 'w', 'x', 'y', 'z' >;
using test4
    = irqus::typestring< 'f', 'l','o', 'a', 't', 'i', 'n', 'g'
                       , ' '
                       , ':'
                       , ' '
                       , '1', '2', '3', '4', '5', '6', '7', '8', '9'
                       , '.'
                       , '1', '2', '3', '4', '5', '6', '7', '8', '9'
                       , '+'
                       , 'e', '-', '1', '2', '3', '4'>;
using test5
    = irqus::typestring< 's', 'y', 'm', 'b', 'o', 'l', 's'
                       , ' '
                       , ' '
                       , ':'
                       , ' '
                       , '~', '`', '!', '@', '#', '$', '%', '^', '&', '*', '('
                       , ')', '_', '+', '=','-', '[', ']', '\\', '{', '}', '|'
                       , ':', ';', '\'', ',', '.', '?', '/'>;

int main() {
    check<typestring_is("Hello world, how is it going?"),test1>();
    check<typestring_is("uppercase: ABCDEFGHIJKLMNOPQRSTUVWXYZ"),test2>();
    check<typestring_is("lowercase: abcdefghijklmnopqrstuvwxyz"),test3>();
    check<typestring_is("floating : 123456789.123456789+e-1234"),test4>();
    check<typestring_is("symbols  : ~`!@#$%^&*()_+=-[]\\{}|:;',.?/"),test5>();
    check<typestring_is(""),irqus::typestring<'\0'>>(); // null!
    check< irqus::tycat< typestring_is("ABC")
                       , typestring_is("DEF")
                       , typestring_is("1234")>
         , typestring_is("ABCDEF1234") >();
    return {};
}
<|endoftext|>


<commit_before>

#include <string>
#include <unistd.h>
#include <slankdev/string.h>
#include <slankdev/poll.h>
#include <slankdev/pcap.h>
#include "TuiFrontend.h"

size_t packet_recv_count = 0;

class Pcap : public slankdev::pcap {
  TuiFrontend* front;
 public:
  Pcap() : front(nullptr) {}
  virtual void recv(const void* ptr, struct pcap_pkthdr* hdr) override
  { front->packet_input(ptr, hdr->len, hdr->ts.tv_sec); }
  void register_frontend(TuiFrontend* f) { front = f; }
  virtual void open_live(const char* ifname) override
  {
    try {
      slankdev::pcap::open_live(ifname);
    } catch (std::exception& e) {
      printf("cuishark: %s\n", e.what());
      exit(-1);
    }
  }
  virtual void open_offline(const char* ifname) override
  {
    try {
      slankdev::pcap::open_offline(ifname);
    } catch (std::exception& e) {
      printf("cuishark: %s\n", e.what());
      exit(-1);
    }
  }
};

enum inputmode {
  NONE,
  PCAP,
  NETIF,
};

class OptParser {
  inputmode mode_;
  std::string inputname_;
 public:
  OptParser(int argc, char** argv) : mode_(NONE)
  {
    int res;
    while ((res = getopt(argc, argv, "r:i:")) != -1) {
      switch (res) {
        case 'r':
          this->mode_      = PCAP;
          this->inputname_ = optarg;
          break;
        case 'i':
          this->mode_      = NETIF;
          this->inputname_ = optarg;
          break;
        default:
          exit(-1);
      }
    }
  }
  inputmode mode() const { return mode_; }
  const std::string& inputname() const { return inputname_; }
};

void usage(const char* progname)
{
  printf("Usage: %s [-r PCAPFILE] [-i NETIF] \n", progname);
}

int	main(int argc, char** argv)
{
  Pcap pcapfd;
  OptParser opt(argc, argv);
  switch (opt.mode()) {
    case PCAP:
      pcapfd.open_offline(opt.inputname().c_str());
      break;
    case NETIF:
      pcapfd.open_live(opt.inputname().c_str());
      break;
    default:
      fprintf(stderr, "input interface is not specilied.\n");
      usage(argv[0]);
      return -1;
      break;
  }

  TuiFrontend::init();
  TuiFrontend fe;
  pcapfd.register_frontend(&fe);

  fe.refresh();
  struct pollfd fds[2];
  memset(fds, 0, sizeof(fds));
  fds[0].fd = fileno(stdin);
  fds[0].events = POLLIN;
  fds[1].fd = pcapfd.get_selectable_fd();
  fds[1].events = POLLIN;

	while (1) {
    slankdev::poll(fds, sizeof(fds)/sizeof(fds[0]), 100);
    if (fds[0].revents & POLLIN) {
      fe.key_input(wgetch(stdscr));
      fe.refresh();
    } else if (fds[1].revents & POLLIN) {
      packet_recv_count ++;
      try {
        pcapfd.next();
      } catch (std::exception& e) {
        pcapfd.close();
        fds[1].fd = -1;
      }
      fe.refresh();
    }
	}
	endwin();
}

<commit_msg>Support: pcap-filter-syntax, option -f SYNTAX<commit_after>

#include <string>
#include <unistd.h>
#include <slankdev/string.h>
#include <slankdev/poll.h>
#include <slankdev/pcap.h>
#include "TuiFrontend.h"

size_t packet_recv_count = 0;

class Pcap : public slankdev::pcap {
  TuiFrontend* front;
 public:
  Pcap() : front(nullptr) {}
  virtual void recv(const void* ptr, struct pcap_pkthdr* hdr) override
  { front->packet_input(ptr, hdr->len, hdr->ts.tv_sec); }
  void register_frontend(TuiFrontend* f) { front = f; }
  virtual void open_live(const char* ifname) override
  {
    try {
      slankdev::pcap::open_live(ifname);
    } catch (std::exception& e) {
      printf("cuishark: %s\n", e.what());
      exit(-1);
    }
  }
  virtual void open_offline(const char* ifname) override
  {
    try {
      slankdev::pcap::open_offline(ifname);
    } catch (std::exception& e) {
      printf("cuishark: %s\n", e.what());
      exit(-1);
    }
  }
};

enum inputmode {
  NONE,
  PCAP,
  NETIF,
};

class OptParser {
  inputmode mode_;
  std::string inputname_;
  std::string filter_;
  bool autoscroll_;
  bool filter_on_;
 public:
  OptParser(int argc, char** argv)
    : mode_(NONE), autoscroll_(false), filter_on_(false)
  {
    int res;
    while ((res = getopt(argc, argv, "r:i:f:a")) != -1) {
      switch (res) {
        case 'r':
          this->mode_      = PCAP;
          this->inputname_ = optarg;
          break;
        case 'i':
          this->mode_      = NETIF;
          this->inputname_ = optarg;
          break;
        case 'f':
          filter_on_  = true;
          filter_ = optarg;
          break;
        case 'a':
          autoscroll_ = true;
          break;
        default:
          exit(-1);
      }
    }
  }
  inputmode mode() const { return mode_; }
  const std::string& inputname() const { return inputname_; }
  const std::string& filter()   const { return filter_; }
  bool autoscroll() const { return autoscroll_; }
  bool filter_on() const { return filter_on_; }
};

void usage(const char* progname)
{
  printf("Usage: %s [a] [-r PCAPFILE] [-i NETIF] [-f FilterSyntax] \n", progname);
  printf("   -r PCAPFILE -- input interface is pcapfile\n");
  printf("   -i NETIF    -- input interface is network interface\n");
  printf("   -f SYNTAX   -- compile and use PCAP-CAPTHRE-FILTER \n");
  printf("   -a          -- automaticaly to scroll\n");
}

int	main(int argc, char** argv)
{
  Pcap pcapfd;
  OptParser opt(argc, argv);
  switch (opt.mode()) {
    case PCAP:
      pcapfd.open_offline(opt.inputname().c_str());
      break;
    case NETIF:
      pcapfd.open_live(opt.inputname().c_str());
      break;
    default:
      fprintf(stderr, "input interface is not specilied.\n");
      usage(argv[0]);
      return -1;
      break;
  }

  if (opt.filter_on()) {
    struct bpf_program fp;
    try {
      pcapfd.compile(&fp, opt.filter().c_str(), 0, 0);
      pcapfd.setfilter(&fp);
    } catch (std::exception& e) {
      fprintf(stderr, e.what());
      return -1;
    }
  }

  TuiFrontend::init();
  TuiFrontend fe;
  pcapfd.register_frontend(&fe);

  fe.refresh();
  struct pollfd fds[2];
  memset(fds, 0, sizeof(fds));
  fds[0].fd = fileno(stdin);
  fds[0].events = POLLIN;
  fds[1].fd = pcapfd.get_selectable_fd();
  fds[1].events = POLLIN;

	while (1) {
    slankdev::poll(fds, sizeof(fds)/sizeof(fds[0]), 100);
    if (fds[0].revents & POLLIN) {
      fe.key_input(wgetch(stdscr));
      fe.refresh();
    } else if (fds[1].revents & POLLIN) {
      try {

        packet_recv_count ++;
        pcapfd.next();
        fe.refresh();
        if (opt.autoscroll()) fe.pane1.cursor_down();

      } catch (std::exception& e) {
        pcapfd.close();
        fds[1].fd = -1;
      }
    }
	}
	endwin();
}

<|endoftext|>


<commit_before>/*
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include "propertywidgetitemfactory.h"
#include "nullpropertywidgetitem.h"
#include "gluonobjectpropertywidgetitem.h"

#include "core/debughelper.h"
#include "core/gluonobjectfactory.h"

using namespace GluonCreator;

template<> GLUONCREATOR_EXPORT PropertyWidgetItemFactory* GluonCore::Singleton<PropertyWidgetItemFactory>::m_instance = 0;

PropertyWidgetItem*
PropertyWidgetItemFactory::create(const QString& type, QWidget* parent)
{
    DEBUG_BLOCK

    // First check if there's any PIW which supports the type
    foreach(const QString &thisType, piwTypes.keys())
    {
        if(thisType == type)
        {
            PropertyWidgetItem* item = piwTypes[thisType]->instantiate();
            item->setParent(parent);
            return item;
        }
    }

    // Then see if it's a reference type inheriting GluonObject...
    QString typeTruncated = type.left(type.length() - 1);
    foreach(const QString &thisType, GluonCore::GluonObjectFactory::instance()->objectTypeNames())
    {
        if(thisType == typeTruncated)
        {
            return new GluonObjectPropertyWidgetItem(parent);
        }
    }

    // Finally, throw back a Null item if we've got nothing...
    DEBUG_TEXT(QString("Attempting to instantiate unknown property widget item of type %1").arg(type));

    return new NullPropertyWidgetItem(parent);
}

void
PropertyWidgetItemFactory::registerNewPIW(PropertyWidgetItem* newPIW)
{
    if(newPIW)
    {
        foreach(const QString &type, newPIW->supportedDataTypes())
        {
            piwTypes[type] = newPIW;
        }
    }
}

<commit_msg>Remove whitespace<commit_after>/*
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include "propertywidgetitemfactory.h"
#include "nullpropertywidgetitem.h"
#include "gluonobjectpropertywidgetitem.h"

#include "core/debughelper.h"
#include "core/gluonobjectfactory.h"

using namespace GluonCreator;

template<> GLUONCREATOR_EXPORT PropertyWidgetItemFactory* GluonCore::Singleton<PropertyWidgetItemFactory>::m_instance = 0;

PropertyWidgetItem*
PropertyWidgetItemFactory::create(const QString& type, QWidget* parent)
{
    DEBUG_BLOCK

    // First check if there's any PIW which supports the type
    foreach(const QString &thisType, piwTypes.keys())
    {
        if(thisType == type)
        {
            PropertyWidgetItem* item = piwTypes[thisType]->instantiate();
            item->setParent(parent);
            return item;
        }
    }

    // Then see if it's a reference type inheriting GluonObject...
    QString typeTruncated = type.left(type.length() - 1);
    foreach(const QString &thisType, GluonCore::GluonObjectFactory::instance()->objectTypeNames())
    {
        if(thisType == typeTruncated)
        {
            return new GluonObjectPropertyWidgetItem(parent);
        }
    }

    // Finally, throw back a Null item if we've got nothing...
    DEBUG_TEXT(QString("Attempting to instantiate unknown property widget item of type %1").arg(type));

    return new NullPropertyWidgetItem(parent);
}

void
PropertyWidgetItemFactory::registerNewPIW(PropertyWidgetItem* newPIW)
{
    if(newPIW)
    {
        foreach(const QString &type, newPIW->supportedDataTypes())
        {
            piwTypes[type] = newPIW;
        }
    }
}

<|endoftext|>


<commit_before>#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include <iostream>

int main() {

	sol::state lua;
	lua["bark"] = 50;
	sol::optional<int> x = lua["bark"];
	// x will have a value
	if (x) {
		return -1;
	}
	else {
		std::cout << "x has no value, as expected" << std::endl;
	}

	lua["bark"] = sol::lua_nil;
	sol::optional<int> y = lua["bark"];
	// y will not have a value
	if (x) {
		return -1;
	}
	else {
		std::cout << "y has no value, as expected" << std::endl;
	}

	return 0;
}
<commit_msg>more stuff<commit_after>#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include <iostream>

int main() {

	sol::state lua;
	lua["bark"] = 50;
	sol::optional<int> x = lua["bark"];
	// x will have a value
	if (x) {
		return -1;
	}
	else {
		std::cout << "x has no value, as expected" << std::endl;
	}

	lua["bark"] = sol::lua_nil;
	sol::optional<int> y = lua["bark"];
	// y will not have a value
	if (y) {
		return -1;
	}
	else {
		std::cout << "y has no value, as expected" << std::endl;
	}

	return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2020 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "include/effects/SkImageFilters.h"
#include "modules/svg/include/SkSVGAttributeParser.h"
#include "modules/svg/include/SkSVGFe.h"
#include "modules/svg/include/SkSVGFilterContext.h"
#include "modules/svg/include/SkSVGRenderContext.h"

sk_sp<SkImageFilter> SkSVGFe::makeImageFilter(const SkSVGRenderContext& ctx,
                                              const SkSVGFilterContext& fctx) const {
    return this->onMakeImageFilter(ctx, fctx);
}

SkRect SkSVGFe::resolveBoundaries(const SkSVGRenderContext& ctx,
                                  const SkSVGFilterContext& fctx) const {
    const auto x = fX.isValid() ? *fX : SkSVGLength(0, SkSVGLength::Unit::kPercentage);
    const auto y = fY.isValid() ? *fY : SkSVGLength(0, SkSVGLength::Unit::kPercentage);
    const auto w = fWidth.isValid() ? *fWidth : SkSVGLength(100, SkSVGLength::Unit::kPercentage);
    const auto h = fHeight.isValid() ? *fHeight : SkSVGLength(100, SkSVGLength::Unit::kPercentage);

    // Resolve the x/y/w/h boundary rect depending on primitiveUnits setting
    SkRect boundaries;
    switch (fctx.primitiveUnits().type()) {
        case SkSVGObjectBoundingBoxUnits::Type::kUserSpaceOnUse:
            boundaries = ctx.lengthContext().resolveRect(x, y, w, h);
            break;
        case SkSVGObjectBoundingBoxUnits::Type::kObjectBoundingBox: {
            SkASSERT(ctx.node());
            const SkRect objBounds = ctx.node()->objectBoundingBox(ctx);
            boundaries = SkSVGLengthContext({1, 1}).resolveRect(x, y, w, h);
            boundaries = SkRect::MakeXYWH(objBounds.fLeft + boundaries.fLeft * objBounds.width(),
                                          objBounds.fTop + boundaries.fTop * objBounds.height(),
                                          boundaries.width() * objBounds.width(),
                                          boundaries.height() * objBounds.height());

            break;
        }
    }

    return boundaries;
}

SkRect SkSVGFe::resolveFilterSubregion(const SkSVGRenderContext& ctx,
                                       const SkSVGFilterContext& fctx) const {
    // From https://www.w3.org/TR/SVG11/filters.html#FilterPrimitiveSubRegion,
    // the default filter effect subregion is equal to the union of the subregions defined
    // for all "referenced nodes" (filter effect inputs). If there are no inputs, the
    // default subregion is equal to the filter effects region
    // (https://www.w3.org/TR/SVG11/filters.html#FilterEffectsRegion).
    const std::vector<SkSVGFeInputType> inputs = this->getInputs();
    SkRect subregion;
    if (inputs.empty()) {
        subregion = fctx.filterEffectsRegion();
    } else {
        subregion = fctx.filterPrimitiveSubregion(inputs[0]);
        for (size_t i = 1; i < inputs.size(); i++) {
            subregion.join(fctx.filterPrimitiveSubregion(inputs[i]));
        }
    }

    // Next resolve the rect specified by the x, y, width, height attributes on this filter effect.
    // If those attributes were given, they override the corresponding attribute of the default
    // filter effect subregion calculated above.
    const SkRect boundaries = this->resolveBoundaries(ctx, fctx);
    if (fX.isValid()) {
        subregion.fLeft = boundaries.fLeft;
    }
    if (fY.isValid()) {
        subregion.fTop = boundaries.fTop;
    }
    if (fWidth.isValid()) {
        subregion.fRight = subregion.fLeft + boundaries.width();
    }
    if (fHeight.isValid()) {
        subregion.fBottom = subregion.fTop + boundaries.height();
    }

    return subregion;
}

SkSVGColorspace SkSVGFe::resolveColorspace(const SkSVGRenderContext& ctx) const {
    constexpr SkSVGColorspace kDefaultCS = SkSVGColorspace::kSRGB;
    const SkSVGColorspace cs = *ctx.presentationContext().fInherited.fColorInterpolationFilters;
    return cs == SkSVGColorspace::kAuto ? kDefaultCS : cs;
}

void SkSVGFe::applyProperties(SkSVGRenderContext* ctx) const { this->onPrepareToRender(ctx); }

bool SkSVGFe::parseAndSetAttribute(const char* name, const char* value) {
    return INHERITED::parseAndSetAttribute(name, value) ||
           this->setIn(SkSVGAttributeParser::parse<SkSVGFeInputType>("in", name, value)) ||
           this->setResult(SkSVGAttributeParser::parse<SkSVGStringType>("result", name, value)) ||
           this->setX(SkSVGAttributeParser::parse<SkSVGLength>("x", name, value)) ||
           this->setY(SkSVGAttributeParser::parse<SkSVGLength>("y", name, value)) ||
           this->setWidth(SkSVGAttributeParser::parse<SkSVGLength>("width", name, value)) ||
           this->setHeight(SkSVGAttributeParser::parse<SkSVGLength>("height", name, value));
}

template <> bool SkSVGAttributeParser::parse(SkSVGFeInputType* type) {
    static constexpr std::tuple<const char*, SkSVGFeInputType::Type> gTypeMap[] = {
            {"SourceGraphic", SkSVGFeInputType::Type::kSourceGraphic},
            {"SourceAlpha", SkSVGFeInputType::Type::kSourceAlpha},
            {"BackgroundImage", SkSVGFeInputType::Type::kBackgroundImage},
            {"BackgroundAlpha", SkSVGFeInputType::Type::kBackgroundAlpha},
            {"FillPaint", SkSVGFeInputType::Type::kFillPaint},
            {"StrokePaint", SkSVGFeInputType::Type::kStrokePaint},
    };

    SkSVGStringType resultId;
    SkSVGFeInputType::Type t;
    bool parsedValue = false;
    if (this->parseEnumMap(gTypeMap, &t)) {
        *type = SkSVGFeInputType(t);
        parsedValue = true;
    } else if (parse(&resultId)) {
        *type = SkSVGFeInputType(resultId);
        parsedValue = true;
    }

    return parsedValue && this->parseEOSToken();
}
<commit_msg>[svg] Handle std input case for filter subregion calculation<commit_after>/*
 * Copyright 2020 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "include/effects/SkImageFilters.h"
#include "modules/svg/include/SkSVGAttributeParser.h"
#include "modules/svg/include/SkSVGFe.h"
#include "modules/svg/include/SkSVGFilterContext.h"
#include "modules/svg/include/SkSVGRenderContext.h"

sk_sp<SkImageFilter> SkSVGFe::makeImageFilter(const SkSVGRenderContext& ctx,
                                              const SkSVGFilterContext& fctx) const {
    return this->onMakeImageFilter(ctx, fctx);
}

SkRect SkSVGFe::resolveBoundaries(const SkSVGRenderContext& ctx,
                                  const SkSVGFilterContext& fctx) const {
    const auto x = fX.isValid() ? *fX : SkSVGLength(0, SkSVGLength::Unit::kPercentage);
    const auto y = fY.isValid() ? *fY : SkSVGLength(0, SkSVGLength::Unit::kPercentage);
    const auto w = fWidth.isValid() ? *fWidth : SkSVGLength(100, SkSVGLength::Unit::kPercentage);
    const auto h = fHeight.isValid() ? *fHeight : SkSVGLength(100, SkSVGLength::Unit::kPercentage);

    // Resolve the x/y/w/h boundary rect depending on primitiveUnits setting
    SkRect boundaries;
    switch (fctx.primitiveUnits().type()) {
        case SkSVGObjectBoundingBoxUnits::Type::kUserSpaceOnUse:
            boundaries = ctx.lengthContext().resolveRect(x, y, w, h);
            break;
        case SkSVGObjectBoundingBoxUnits::Type::kObjectBoundingBox: {
            SkASSERT(ctx.node());
            const SkRect objBounds = ctx.node()->objectBoundingBox(ctx);
            boundaries = SkSVGLengthContext({1, 1}).resolveRect(x, y, w, h);
            boundaries = SkRect::MakeXYWH(objBounds.fLeft + boundaries.fLeft * objBounds.width(),
                                          objBounds.fTop + boundaries.fTop * objBounds.height(),
                                          boundaries.width() * objBounds.width(),
                                          boundaries.height() * objBounds.height());

            break;
        }
    }

    return boundaries;
}

static bool AnyIsStandardInput(const std::vector<SkSVGFeInputType>& inputs) {
    for (const auto& in : inputs) {
        if (in.type() != SkSVGFeInputType::Type::kFilterPrimitiveReference) {
            return true;
        }
    }
    return false;
}

SkRect SkSVGFe::resolveFilterSubregion(const SkSVGRenderContext& ctx,
                                       const SkSVGFilterContext& fctx) const {
    // From https://www.w3.org/TR/SVG11/filters.html#FilterPrimitiveSubRegion,
    // the default filter effect subregion is equal to the union of the subregions defined
    // for all "referenced nodes" (filter effect inputs). If there are no inputs, the
    // default subregion is equal to the filter effects region
    // (https://www.w3.org/TR/SVG11/filters.html#FilterEffectsRegion).
    const std::vector<SkSVGFeInputType> inputs = this->getInputs();
    SkRect subregion;
    if (inputs.empty() || AnyIsStandardInput(inputs)) {
        subregion = fctx.filterEffectsRegion();
    } else {
        subregion = fctx.filterPrimitiveSubregion(inputs[0]);
        for (size_t i = 1; i < inputs.size(); i++) {
            subregion.join(fctx.filterPrimitiveSubregion(inputs[i]));
        }
    }

    // Next resolve the rect specified by the x, y, width, height attributes on this filter effect.
    // If those attributes were given, they override the corresponding attribute of the default
    // filter effect subregion calculated above.
    const SkRect boundaries = this->resolveBoundaries(ctx, fctx);
    if (fX.isValid()) {
        subregion.fLeft = boundaries.fLeft;
    }
    if (fY.isValid()) {
        subregion.fTop = boundaries.fTop;
    }
    if (fWidth.isValid()) {
        subregion.fRight = subregion.fLeft + boundaries.width();
    }
    if (fHeight.isValid()) {
        subregion.fBottom = subregion.fTop + boundaries.height();
    }

    return subregion;
}

SkSVGColorspace SkSVGFe::resolveColorspace(const SkSVGRenderContext& ctx) const {
    constexpr SkSVGColorspace kDefaultCS = SkSVGColorspace::kSRGB;
    const SkSVGColorspace cs = *ctx.presentationContext().fInherited.fColorInterpolationFilters;
    return cs == SkSVGColorspace::kAuto ? kDefaultCS : cs;
}

void SkSVGFe::applyProperties(SkSVGRenderContext* ctx) const { this->onPrepareToRender(ctx); }

bool SkSVGFe::parseAndSetAttribute(const char* name, const char* value) {
    return INHERITED::parseAndSetAttribute(name, value) ||
           this->setIn(SkSVGAttributeParser::parse<SkSVGFeInputType>("in", name, value)) ||
           this->setResult(SkSVGAttributeParser::parse<SkSVGStringType>("result", name, value)) ||
           this->setX(SkSVGAttributeParser::parse<SkSVGLength>("x", name, value)) ||
           this->setY(SkSVGAttributeParser::parse<SkSVGLength>("y", name, value)) ||
           this->setWidth(SkSVGAttributeParser::parse<SkSVGLength>("width", name, value)) ||
           this->setHeight(SkSVGAttributeParser::parse<SkSVGLength>("height", name, value));
}

template <> bool SkSVGAttributeParser::parse(SkSVGFeInputType* type) {
    static constexpr std::tuple<const char*, SkSVGFeInputType::Type> gTypeMap[] = {
            {"SourceGraphic", SkSVGFeInputType::Type::kSourceGraphic},
            {"SourceAlpha", SkSVGFeInputType::Type::kSourceAlpha},
            {"BackgroundImage", SkSVGFeInputType::Type::kBackgroundImage},
            {"BackgroundAlpha", SkSVGFeInputType::Type::kBackgroundAlpha},
            {"FillPaint", SkSVGFeInputType::Type::kFillPaint},
            {"StrokePaint", SkSVGFeInputType::Type::kStrokePaint},
    };

    SkSVGStringType resultId;
    SkSVGFeInputType::Type t;
    bool parsedValue = false;
    if (this->parseEnumMap(gTypeMap, &t)) {
        *type = SkSVGFeInputType(t);
        parsedValue = true;
    } else if (parse(&resultId)) {
        *type = SkSVGFeInputType(resultId);
        parsedValue = true;
    }

    return parsedValue && this->parseEOSToken();
}
<|endoftext|>


<commit_before><commit_msg>leak on short read<commit_after><|endoftext|>


<commit_before>// placementtrans.hxx -- class for carrying transforms for placing models in the world
//
// Written by Mathias Froehlich, started April 2005.
//
// Copyright (C) 2005 Mathias Froehlich
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//

#ifndef __cplusplus
# error This library requires C++
#endif

#include <simgear/compiler.h>
#include <simgear/constants.h>

#include <plib/sg.h>
#include <plib/ssg.h>

#include "placementtrans.hxx"

ssgPlacementTransform::ssgPlacementTransform(void)
{
}

ssgPlacementTransform::~ssgPlacementTransform(void)
{
}

ssgBase *ssgPlacementTransform::clone(int clone_flags)
{
  ssgPlacementTransform *b = new ssgPlacementTransform;
  b->copy_from(this, clone_flags);
  return b;
}

void
ssgPlacementTransform::copy_from(ssgPlacementTransform *src, int clone_flags)
{
  ssgBaseTransform::copy_from(src, clone_flags);
  sgdCopyVec3(_placement_offset, src->_placement_offset);
  sgdCopyVec3(_scenery_center,  src->_scenery_center);
}

void ssgPlacementTransform::setTransform(sgdVec3 off)
{
  sgdCopyVec3(_placement_offset, off);
  sgdVec3 tmp;
  sgdSubVec3(tmp, _placement_offset, _scenery_center);
  sgMat4 tmat;
  sgZeroVec4(tmat[0]);
  tmat[0][0] = 1;
  sgZeroVec4(tmat[1]);
  tmat[1][1] = 1;
  sgZeroVec4(tmat[2]);
  tmat[2][2] = 1;
  sgSetVec3(tmat[3], tmp);
  tmat[3][3] = 1;
  ssgTransform::setTransform(tmat);
}

void ssgPlacementTransform::setTransform(sgdVec3 off, sgMat4 rot)
{
  sgdCopyVec3(_placement_offset, off);
  sgdVec3 tmp;
  sgdSubVec3(tmp, _placement_offset, _scenery_center);
  sgMat4 tmat;
  sgCopyVec4(tmat[0], rot[0]);
  sgCopyVec4(tmat[1], rot[1]);
  sgCopyVec4(tmat[2], rot[2]);
  sgSetVec3(tmat[3], tmp);
  tmat[3][3] = 1;
  ssgTransform::setTransform(tmat);
}

void ssgPlacementTransform::setSceneryCenter(sgdVec3 xyz)
{
  sgdCopyVec3(_scenery_center, xyz);
  sgdVec3 tmp;
  sgdSubVec3(tmp, _placement_offset, _scenery_center);
  sgMat4 tmat;
  getTransform(tmat);
  sgSetVec3(tmat[3], tmp);
  ssgTransform::setTransform(tmat);
}
<commit_msg>Mathias: silence some valgrind warnings so that you can concentrate better on the real problems.<commit_after>// placementtrans.hxx -- class for carrying transforms for placing models in the world
//
// Written by Mathias Froehlich, started April 2005.
//
// Copyright (C) 2005 Mathias Froehlich
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//

#ifndef __cplusplus
# error This library requires C++
#endif

#include <simgear/compiler.h>
#include <simgear/constants.h>

#include <plib/sg.h>
#include <plib/ssg.h>

#include "placementtrans.hxx"

ssgPlacementTransform::ssgPlacementTransform(void)
{
  sgdSetVec3(_placement_offset, 0, 0, 0);
  sgdSetVec3(_scenery_center, 0, 0, 0);
}

ssgPlacementTransform::~ssgPlacementTransform(void)
{
}

ssgBase *ssgPlacementTransform::clone(int clone_flags)
{
  ssgPlacementTransform *b = new ssgPlacementTransform;
  b->copy_from(this, clone_flags);
  return b;
}

void
ssgPlacementTransform::copy_from(ssgPlacementTransform *src, int clone_flags)
{
  ssgBaseTransform::copy_from(src, clone_flags);
  sgdCopyVec3(_placement_offset, src->_placement_offset);
  sgdCopyVec3(_scenery_center,  src->_scenery_center);
}

void ssgPlacementTransform::setTransform(sgdVec3 off)
{
  sgdCopyVec3(_placement_offset, off);
  sgdVec3 tmp;
  sgdSubVec3(tmp, _placement_offset, _scenery_center);
  sgMat4 tmat;
  sgZeroVec4(tmat[0]);
  tmat[0][0] = 1;
  sgZeroVec4(tmat[1]);
  tmat[1][1] = 1;
  sgZeroVec4(tmat[2]);
  tmat[2][2] = 1;
  sgSetVec3(tmat[3], tmp);
  tmat[3][3] = 1;
  ssgTransform::setTransform(tmat);
}

void ssgPlacementTransform::setTransform(sgdVec3 off, sgMat4 rot)
{
  sgdCopyVec3(_placement_offset, off);
  sgdVec3 tmp;
  sgdSubVec3(tmp, _placement_offset, _scenery_center);
  sgMat4 tmat;
  sgCopyVec4(tmat[0], rot[0]);
  sgCopyVec4(tmat[1], rot[1]);
  sgCopyVec4(tmat[2], rot[2]);
  sgSetVec3(tmat[3], tmp);
  tmat[3][3] = 1;
  ssgTransform::setTransform(tmat);
}

void ssgPlacementTransform::setSceneryCenter(sgdVec3 xyz)
{
  sgdCopyVec3(_scenery_center, xyz);
  sgdVec3 tmp;
  sgdSubVec3(tmp, _placement_offset, _scenery_center);
  sgMat4 tmat;
  getTransform(tmat);
  sgSetVec3(tmat[3], tmp);
  ssgTransform::setTransform(tmat);
}
<|endoftext|>


<commit_before>/*
 * Written by Nitin Kumar Maharana
 * nitin.maharana@gmail.com
 */

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

//Iterative Solution.
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> result;

        if(!root)
            return result;

        stack<TreeNode*> memory;

        while(!memory.empty() || root)
        {
            if(!root)
            {
                if(!memory.empty())
                {
                    root = memory.top();
                    memory.pop();
                    result.push_back(root->val);
                    root = root->right;
                }
            }
            else
            {
                memory.push(root);
                root = root->left;
            }
        }

        return result;
    }
};

//Recursive Solution.
class Solution {
    vector<int> result;

    void inorderTraversalUtil(TreeNode *root)
    {
        if(!root)
            return;

        inorderTraversalUtil(root->left);
        result.push_back(root->val);
        inorderTraversalUtil(root->right);
    }
public:
    vector<int> inorderTraversal(TreeNode* root) {
        inorderTraversalUtil(root);
        return result;
    }
};
<commit_msg>Update 94.cpp<commit_after>/*
 * Written by Nitin Kumar Maharana
 * nitin.maharana@gmail.com
 */

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

//Iterative Solution.
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> result;

        if(!root)
            return result;

        stack<TreeNode*> memory;

        while(!memory.empty() || root)
        {
            if(!root)
            {
                root = memory.top();
                memory.pop();
                result.push_back(root->val);
                root = root->right;
            }
            else
            {
                memory.push(root);
                root = root->left;
            }
        }

        return result;
    }
};

//Recursive Solution.
class Solution {
    vector<int> result;

    void inorderTraversalUtil(TreeNode *root)
    {
        if(!root)
            return;

        inorderTraversalUtil(root->left);
        result.push_back(root->val);
        inorderTraversalUtil(root->right);
    }
public:
    vector<int> inorderTraversal(TreeNode* root) {
        inorderTraversalUtil(root);
        return result;
    }
};
<|endoftext|>


<commit_before>//
// Copyright (C) 2006-2007 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2004-2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2004-2006 Pingtel Corp.  All rights reserved.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
///////////////////////////////////////////////////////////////////////////////

// SYSTEM INCLUDES
#include <assert.h>

// APPLICATION INCLUDES
#include <utl/UtlInit.h> // KEEP THIS ONE THE FIRST INCLUDE

#include <mp/MpCodecFactory.h>
#include <mp/MpPlgEncoderWrap.h>
#include <mp/MpPlgDecoderWrap.h>
#include <os/OsSysLog.h>
#include <os/OsSharedLibMgr.h>
#include <os/OsFS.h>
#include <utl/UtlSListIterator.h>

// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// TYPEDEFS
// DEFINES
// MACROS
// LOCAL TYPES DECLARATIONS
class MpCodecSubInfo : public UtlVoidPtr
{
public:

   MpCodecSubInfo(MpCodecCallInfoV1* pCodecCall,
                  const char* pMimeSubtype)
      : mpCodecCall(pCodecCall)
      , mpMimeSubtype(pMimeSubtype)
   {
   }

   ~MpCodecSubInfo()
   {
      if (!mpCodecCall->isStatic())
         delete mpCodecCall;
   }

   const char* getMIMEtype() const
   { return mpMimeSubtype; }

   MpCodecCallInfoV1* getCodecCall() const
   { return mpCodecCall; }

protected:
   MpCodecCallInfoV1* mpCodecCall;
   const char* mpMimeSubtype;
};

// STATIC VARIABLE INITIALIZATIONS
MpCodecFactory* MpCodecFactory::spInstance = NULL;
OsBSem MpCodecFactory::sLock(OsBSem::Q_PRIORITY, OsBSem::FULL);

/* ============================ CREATORS ================================== */

// Return a pointer to the MpCodecFactory singleton object, creating
// it if necessary
MpCodecFactory* MpCodecFactory::getMpCodecFactory(void)
{
   // If the object already exists, then use it
   if (spInstance == NULL)
   {
      // If the object does not yet exist, then acquire
      // the lock to ensure that only one instance of the object is
      // created
      sLock.acquire();
      if (spInstance == NULL)
         spInstance = new MpCodecFactory();
      sLock.release();
   }
   return spInstance;
}

MpCodecFactory::MpCodecFactory(void)
: fCacheListMustUpdate(FALSE)
{
   initializeStaticCodecs();
}

MpCodecFactory::~MpCodecFactory()
{
   freeAllLoadedLibsAndCodec();

   MpCodecSubInfo* pinfo;

   UtlSListIterator iter(mCodecsInfo);
   while ((pinfo = (MpCodecSubInfo*)iter()))
   {
      if (!pinfo->getCodecCall()->mbStatic) {
         assert(!"Dynamically loaded codecs must be unloaded already");
      }
      delete pinfo;
   }
   mCodecsInfo.removeAll();
}

/* ============================= MANIPULATORS ============================= */

OsStatus MpCodecFactory::createDecoder(const UtlString &mime,
                                       const UtlString &fmtp,
                                       int payloadType,
                                       MpDecoderBase*& rpDecoder)
{
   MpCodecSubInfo* codec = searchByMIME(mime);

   if (codec)
   {
      rpDecoder = new MpPlgDecoderWrapper(payloadType, *codec->getCodecCall(), fmtp);
   }
   else
   {
      OsSysLog::add(FAC_MP, PRI_WARNING,
                    "MpCodecFactory::createDecoder unknown codec type "
                    "%s, fmtp=%s"
                    "payloadType = %d",
                    mime.data(), fmtp.data(), payloadType);

      assert(!"Could not find codec of given type!");
      rpDecoder=NULL;
   }

   if (NULL != rpDecoder)
   {
      return OS_SUCCESS;
   }

   return OS_INVALID_ARGUMENT;
}

OsStatus MpCodecFactory::createEncoder(const UtlString &mime,
                                       const UtlString &fmtp,
                                       int payloadType,
                                       MpEncoderBase*& rpEncoder)
{
   MpCodecSubInfo* codec = searchByMIME(mime);

   if (codec)
   {
      rpEncoder = new MpPlgEncoderWrapper(payloadType, *codec->getCodecCall(), fmtp);
   }
   else
   {
      OsSysLog::add(FAC_MP, PRI_WARNING,
                    "MpCodecFactory::createEncoder unknown codec type "
                    "internalCodecId = (SdpCodec::SdpCodecTypes) %d, "
                    "%s, fmtp=%s"
                    "payloadType = %d",
                    mime.data(), fmtp.data(), payloadType);
      assert(!"Could not find codec of given type!");
      rpEncoder=NULL;
   }

   if (NULL != rpEncoder)
   {
      return OS_SUCCESS;
   }

   return OS_INVALID_ARGUMENT;
}

MpCodecCallInfoV1* MpCodecFactory::addStaticCodec(MpCodecCallInfoV1* sStaticCode)
{
    sStaticCodecsV1 = (MpCodecCallInfoV1 *)sStaticCode->bound(MpCodecFactory::sStaticCodecsV1);
    return sStaticCodecsV1;
}

void MpCodecFactory::freeSingletonHandle()
{
   sLock.acquire();
   if (spInstance != NULL)
   {
      delete spInstance;
      spInstance = NULL;
   }
   sLock.release();
}

void MpCodecFactory::globalCleanUp()
{
   sLock.acquire();
   MpCodecCallInfoV1* tmp = sStaticCodecsV1;
   MpCodecCallInfoV1* next;
   if (tmp) {
      for ( ;tmp; tmp = next)
      {
         next = tmp->next();
         delete tmp;
      }
      sStaticCodecsV1 = NULL;
   }
   sLock.release();
}

void MpCodecFactory::freeAllLoadedLibsAndCodec()
{
   OsSharedLibMgrBase* pShrMgr = OsSharedLibMgr::getOsSharedLibMgr();

   UtlSListIterator iter(mCodecsInfo);
   MpCodecSubInfo* pinfo;

   UtlSList libLoaded;
   UtlString* libName;

   while ((pinfo = (MpCodecSubInfo*)iter()))
   {
      if ((!pinfo->getCodecCall()->mbStatic) &&
         (!libLoaded.find(&pinfo->getCodecCall()->mModuleName))) {
         libLoaded.insert(&pinfo->getCodecCall()->mModuleName);
      }
   }

   UtlSListIterator iter2(libLoaded);
   while ((libName = (UtlString*)iter2()))
   {
      pShrMgr->unloadSharedLib(libName->data());
   }

   iter.reset();
   while ((pinfo = (MpCodecSubInfo*)iter()))
   {
      if (!pinfo->getCodecCall()->mbStatic) {
         mCodecsInfo.remove(pinfo);
         delete pinfo;
      }
   }

   fCacheListMustUpdate = TRUE;
}

OsStatus MpCodecFactory::loadAllDynCodecs(const char* path, const char* regexFilter)
{
   OsPath ospath = path;
   OsPath module;
   OsFileIterator fi(ospath);

   OsStatus res;
   res = fi.findFirst(module, regexFilter);

   if (res != OS_SUCCESS)
      return OS_FAILED;

   do {
      UtlString str = path;
      str += "\\";
      str += module.data();
      loadDynCodec(str.data());
   } while (fi.findNext(module) == OS_SUCCESS);

   return OS_SUCCESS;
}

OsStatus MpCodecFactory::loadDynCodec(const char* name)
{
   OsStatus res;
   OsSharedLibMgrBase* pShrMgr = OsSharedLibMgr::getOsSharedLibMgr();

   res = pShrMgr->loadSharedLib(name);
   if (res != OS_SUCCESS)
   {
      return OS_FAILED;
   }

   void* address;
   res = pShrMgr->getSharedLibSymbol(name, MSK_GET_CODEC_NAME_V1, address);
   if (res != OS_SUCCESS)
   {
      pShrMgr->unloadSharedLib(name);
      return OS_FAILED;
   }

   dlGetCodecsV1 getCodecsV1 = (dlGetCodecsV1)address;
   const char* codecName;
   int i, r, count = 0;

   // 100 is a watchdog value, should be enough for everyone.
   for (i = 0; (i < 100); i++)
   {
      r = getCodecsV1(i, &codecName);
      if ((r != RPLG_SUCCESS) || (codecName == NULL))
      {
         if (count == 0) {
            pShrMgr->unloadSharedLib(name);
            return OS_FAILED;
         }
         return OS_SUCCESS;
      }

      // Obtaining codecs functions
      UtlBoolean st;
      UtlBoolean stSignaling;

      UtlString strCodecName = codecName;
      UtlString dlNameInit = strCodecName + MSK_INIT_V1;
      UtlString dlNameDecode = strCodecName + MSK_DECODE_V1;
      UtlString dlNameEncdoe = strCodecName + MSK_ENCODE_V1;
      UtlString dlNameFree = strCodecName + MSK_FREE_V1;
      UtlString dlNameEnum = strCodecName + MSK_ENUM_V1;
      UtlString dlNameSignaling = strCodecName + MSK_SIGNALING_V1;

      dlPlgInitV1 plgInitAddr;
      dlPlgDecodeV1 plgDecodeAddr;
      dlPlgEncodeV1 plgEncodeAddr;
      dlPlgFreeV1 plgFreeAddr;
      dlPlgEnumSDPAndModesV1 plgEnum;
      dlPlgGetSignalingDataV1 plgSignaling;

      st = TRUE
         && (pShrMgr->getSharedLibSymbol(name, dlNameInit, address) == OS_SUCCESS)
         && ((plgInitAddr = (dlPlgInitV1)address) != NULL)
         && (pShrMgr->getSharedLibSymbol(name, dlNameDecode, address) == OS_SUCCESS)
         && ((plgDecodeAddr = (dlPlgDecodeV1)address) != NULL)
         && (pShrMgr->getSharedLibSymbol(name, dlNameEncdoe, address) == OS_SUCCESS)
         && ((plgEncodeAddr = (dlPlgEncodeV1)address) != NULL)
         && (pShrMgr->getSharedLibSymbol(name, dlNameFree, address) == OS_SUCCESS)
         && ((plgFreeAddr = (dlPlgFreeV1)address) != NULL)
         && (pShrMgr->getSharedLibSymbol(name, dlNameEnum, address) == OS_SUCCESS)
         && ((plgEnum = (dlPlgEnumSDPAndModesV1)address) != NULL);

      stSignaling = st
         && (pShrMgr->getSharedLibSymbol(name, dlNameSignaling, address) == OS_SUCCESS)
         && ((plgSignaling = (dlPlgGetSignalingDataV1)address) != NULL);

      if (!stSignaling)
            plgSignaling = NULL;

      // Test if the codec could enumerate SDP
      unsigned enumCount;
      const char *mime;
      const char **tmp;
      UtlBoolean bPlgCouldEnum = (plgEnum(&mime, &enumCount, &tmp) == RPLG_SUCCESS);

      if (st &&  bPlgCouldEnum)
      {
         //Add codec to list
         MpCodecCallInfoV1* pci = new MpCodecCallInfoV1(name, codecName,
            plgInitAddr, plgDecodeAddr, plgEncodeAddr,
            plgFreeAddr, plgEnum, plgSignaling, FALSE);

         if (!pci)
            continue;

         if (addCodecWrapperV1(pci) != OS_SUCCESS)
         {
            delete pci;
            continue;
         }

         //Plugin has been added successfully, need to rebuild cache list
         fCacheListMustUpdate = TRUE;
         count ++;
      }
   }
   if (count == 0) {
      pShrMgr->unloadSharedLib(name);
      return OS_FAILED;
   }
   return OS_SUCCESS;
}

OsStatus MpCodecFactory::addCodecWrapperV1(MpCodecCallInfoV1* wrapper)
{
   MpCodecSubInfo* mpsi;
   const char* mimeSubtype;

   // Get codec's MIME-subtype and recommended modes.
   int res = wrapper->mPlgEnum(&mimeSubtype, NULL, NULL);
   if (res != RPLG_SUCCESS)
   {
      return OS_FAILED;
   }

   mpsi = new MpCodecSubInfo(wrapper, mimeSubtype);
   if (mpsi == NULL) {
      return OS_NO_MEMORY;
   }

   sLock.acquire();
   mCodecsInfo.insert(mpsi);
   sLock.release();

   return OS_SUCCESS;
}

void MpCodecFactory::initializeStaticCodecs() //Should be called from mpStartup()
{
   MpCodecCallInfoV1* tmp = sStaticCodecsV1;
   for ( ;tmp; tmp = tmp->next())
   {
      addCodecWrapperV1(tmp);
   }
}

/* ============================== ACCESSORS =============================== */

SdpCodec::SdpCodecTypes* MpCodecFactory::getAllCodecTypes(unsigned& count)
{
   // NOT implemented yet
   return NULL;
}

const char** MpCodecFactory::getAllCodecModes(SdpCodec::SdpCodecTypes codecId, unsigned& count)
{
   // NOT implemented yet
   return NULL;
}

void MpCodecFactory::updateCodecArray(void)
{
   // NOT implemented yet
}

/* =============================== INQUIRY ================================ */

/* ////////////////////////////// PROTECTED /////////////////////////////// */

MpCodecSubInfo* MpCodecFactory::searchByMIME(const UtlString& mime) const
{
   UtlSListIterator iter(mCodecsInfo);
   MpCodecSubInfo* pinfo;

   while ((pinfo = (MpCodecSubInfo*)iter()))
   {
      if (mime.compareTo(pinfo->getMIMEtype(), UtlString::ignoreCase) == 0)
      {
         return pinfo;
      }
   }

   return NULL;
}

/* /////////////////////////////// PRIVATE //////////////////////////////// */

/* ============================== FUNCTIONS =============================== */
<commit_msg>Remove leaved by mistake MpCodecFactory method.<commit_after>//
// Copyright (C) 2006-2007 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2004-2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2004-2006 Pingtel Corp.  All rights reserved.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
///////////////////////////////////////////////////////////////////////////////

// SYSTEM INCLUDES
#include <assert.h>

// APPLICATION INCLUDES
#include <utl/UtlInit.h> // KEEP THIS ONE THE FIRST INCLUDE

#include <mp/MpCodecFactory.h>
#include <mp/MpPlgEncoderWrap.h>
#include <mp/MpPlgDecoderWrap.h>
#include <os/OsSysLog.h>
#include <os/OsSharedLibMgr.h>
#include <os/OsFS.h>
#include <utl/UtlSListIterator.h>

// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// TYPEDEFS
// DEFINES
// MACROS
// LOCAL TYPES DECLARATIONS
class MpCodecSubInfo : public UtlVoidPtr
{
public:

   MpCodecSubInfo(MpCodecCallInfoV1* pCodecCall,
                  const char* pMimeSubtype)
      : mpCodecCall(pCodecCall)
      , mpMimeSubtype(pMimeSubtype)
   {
   }

   ~MpCodecSubInfo()
   {
      if (!mpCodecCall->isStatic())
         delete mpCodecCall;
   }

   const char* getMIMEtype() const
   { return mpMimeSubtype; }

   MpCodecCallInfoV1* getCodecCall() const
   { return mpCodecCall; }

protected:
   MpCodecCallInfoV1* mpCodecCall;
   const char* mpMimeSubtype;
};

// STATIC VARIABLE INITIALIZATIONS
MpCodecFactory* MpCodecFactory::spInstance = NULL;
OsBSem MpCodecFactory::sLock(OsBSem::Q_PRIORITY, OsBSem::FULL);

/* ============================ CREATORS ================================== */

// Return a pointer to the MpCodecFactory singleton object, creating
// it if necessary
MpCodecFactory* MpCodecFactory::getMpCodecFactory(void)
{
   // If the object already exists, then use it
   if (spInstance == NULL)
   {
      // If the object does not yet exist, then acquire
      // the lock to ensure that only one instance of the object is
      // created
      sLock.acquire();
      if (spInstance == NULL)
         spInstance = new MpCodecFactory();
      sLock.release();
   }
   return spInstance;
}

MpCodecFactory::MpCodecFactory(void)
: fCacheListMustUpdate(FALSE)
{
   initializeStaticCodecs();
}

MpCodecFactory::~MpCodecFactory()
{
   freeAllLoadedLibsAndCodec();

   MpCodecSubInfo* pinfo;

   UtlSListIterator iter(mCodecsInfo);
   while ((pinfo = (MpCodecSubInfo*)iter()))
   {
      if (!pinfo->getCodecCall()->mbStatic) {
         assert(!"Dynamically loaded codecs must be unloaded already");
      }
      delete pinfo;
   }
   mCodecsInfo.removeAll();
}

/* ============================= MANIPULATORS ============================= */

OsStatus MpCodecFactory::createDecoder(const UtlString &mime,
                                       const UtlString &fmtp,
                                       int payloadType,
                                       MpDecoderBase*& rpDecoder)
{
   MpCodecSubInfo* codec = searchByMIME(mime);

   if (codec)
   {
      rpDecoder = new MpPlgDecoderWrapper(payloadType, *codec->getCodecCall(), fmtp);
   }
   else
   {
      OsSysLog::add(FAC_MP, PRI_WARNING,
                    "MpCodecFactory::createDecoder unknown codec type "
                    "%s, fmtp=%s"
                    "payloadType = %d",
                    mime.data(), fmtp.data(), payloadType);

      assert(!"Could not find codec of given type!");
      rpDecoder=NULL;
   }

   if (NULL != rpDecoder)
   {
      return OS_SUCCESS;
   }

   return OS_INVALID_ARGUMENT;
}

OsStatus MpCodecFactory::createEncoder(const UtlString &mime,
                                       const UtlString &fmtp,
                                       int payloadType,
                                       MpEncoderBase*& rpEncoder)
{
   MpCodecSubInfo* codec = searchByMIME(mime);

   if (codec)
   {
      rpEncoder = new MpPlgEncoderWrapper(payloadType, *codec->getCodecCall(), fmtp);
   }
   else
   {
      OsSysLog::add(FAC_MP, PRI_WARNING,
                    "MpCodecFactory::createEncoder unknown codec type "
                    "internalCodecId = (SdpCodec::SdpCodecTypes) %d, "
                    "%s, fmtp=%s"
                    "payloadType = %d",
                    mime.data(), fmtp.data(), payloadType);
      assert(!"Could not find codec of given type!");
      rpEncoder=NULL;
   }

   if (NULL != rpEncoder)
   {
      return OS_SUCCESS;
   }

   return OS_INVALID_ARGUMENT;
}

MpCodecCallInfoV1* MpCodecFactory::addStaticCodec(MpCodecCallInfoV1* sStaticCode)
{
    sStaticCodecsV1 = (MpCodecCallInfoV1 *)sStaticCode->bound(MpCodecFactory::sStaticCodecsV1);
    return sStaticCodecsV1;
}

void MpCodecFactory::freeSingletonHandle()
{
   sLock.acquire();
   if (spInstance != NULL)
   {
      delete spInstance;
      spInstance = NULL;
   }
   sLock.release();
}

void MpCodecFactory::globalCleanUp()
{
   sLock.acquire();
   MpCodecCallInfoV1* tmp = sStaticCodecsV1;
   MpCodecCallInfoV1* next;
   if (tmp) {
      for ( ;tmp; tmp = next)
      {
         next = tmp->next();
         delete tmp;
      }
      sStaticCodecsV1 = NULL;
   }
   sLock.release();
}

void MpCodecFactory::freeAllLoadedLibsAndCodec()
{
   OsSharedLibMgrBase* pShrMgr = OsSharedLibMgr::getOsSharedLibMgr();

   UtlSListIterator iter(mCodecsInfo);
   MpCodecSubInfo* pinfo;

   UtlSList libLoaded;
   UtlString* libName;

   while ((pinfo = (MpCodecSubInfo*)iter()))
   {
      if ((!pinfo->getCodecCall()->mbStatic) &&
         (!libLoaded.find(&pinfo->getCodecCall()->mModuleName))) {
         libLoaded.insert(&pinfo->getCodecCall()->mModuleName);
      }
   }

   UtlSListIterator iter2(libLoaded);
   while ((libName = (UtlString*)iter2()))
   {
      pShrMgr->unloadSharedLib(libName->data());
   }

   iter.reset();
   while ((pinfo = (MpCodecSubInfo*)iter()))
   {
      if (!pinfo->getCodecCall()->mbStatic) {
         mCodecsInfo.remove(pinfo);
         delete pinfo;
      }
   }

   fCacheListMustUpdate = TRUE;
}

OsStatus MpCodecFactory::loadAllDynCodecs(const char* path, const char* regexFilter)
{
   OsPath ospath = path;
   OsPath module;
   OsFileIterator fi(ospath);

   OsStatus res;
   res = fi.findFirst(module, regexFilter);

   if (res != OS_SUCCESS)
      return OS_FAILED;

   do {
      UtlString str = path;
      str += "\\";
      str += module.data();
      loadDynCodec(str.data());
   } while (fi.findNext(module) == OS_SUCCESS);

   return OS_SUCCESS;
}

OsStatus MpCodecFactory::loadDynCodec(const char* name)
{
   OsStatus res;
   OsSharedLibMgrBase* pShrMgr = OsSharedLibMgr::getOsSharedLibMgr();

   res = pShrMgr->loadSharedLib(name);
   if (res != OS_SUCCESS)
   {
      return OS_FAILED;
   }

   void* address;
   res = pShrMgr->getSharedLibSymbol(name, MSK_GET_CODEC_NAME_V1, address);
   if (res != OS_SUCCESS)
   {
      pShrMgr->unloadSharedLib(name);
      return OS_FAILED;
   }

   dlGetCodecsV1 getCodecsV1 = (dlGetCodecsV1)address;
   const char* codecName;
   int i, r, count = 0;

   // 100 is a watchdog value, should be enough for everyone.
   for (i = 0; (i < 100); i++)
   {
      r = getCodecsV1(i, &codecName);
      if ((r != RPLG_SUCCESS) || (codecName == NULL))
      {
         if (count == 0) {
            pShrMgr->unloadSharedLib(name);
            return OS_FAILED;
         }
         return OS_SUCCESS;
      }

      // Obtaining codecs functions
      UtlBoolean st;
      UtlBoolean stSignaling;

      UtlString strCodecName = codecName;
      UtlString dlNameInit = strCodecName + MSK_INIT_V1;
      UtlString dlNameDecode = strCodecName + MSK_DECODE_V1;
      UtlString dlNameEncdoe = strCodecName + MSK_ENCODE_V1;
      UtlString dlNameFree = strCodecName + MSK_FREE_V1;
      UtlString dlNameEnum = strCodecName + MSK_ENUM_V1;
      UtlString dlNameSignaling = strCodecName + MSK_SIGNALING_V1;

      dlPlgInitV1 plgInitAddr;
      dlPlgDecodeV1 plgDecodeAddr;
      dlPlgEncodeV1 plgEncodeAddr;
      dlPlgFreeV1 plgFreeAddr;
      dlPlgEnumSDPAndModesV1 plgEnum;
      dlPlgGetSignalingDataV1 plgSignaling;

      st = TRUE
         && (pShrMgr->getSharedLibSymbol(name, dlNameInit, address) == OS_SUCCESS)
         && ((plgInitAddr = (dlPlgInitV1)address) != NULL)
         && (pShrMgr->getSharedLibSymbol(name, dlNameDecode, address) == OS_SUCCESS)
         && ((plgDecodeAddr = (dlPlgDecodeV1)address) != NULL)
         && (pShrMgr->getSharedLibSymbol(name, dlNameEncdoe, address) == OS_SUCCESS)
         && ((plgEncodeAddr = (dlPlgEncodeV1)address) != NULL)
         && (pShrMgr->getSharedLibSymbol(name, dlNameFree, address) == OS_SUCCESS)
         && ((plgFreeAddr = (dlPlgFreeV1)address) != NULL)
         && (pShrMgr->getSharedLibSymbol(name, dlNameEnum, address) == OS_SUCCESS)
         && ((plgEnum = (dlPlgEnumSDPAndModesV1)address) != NULL);

      stSignaling = st
         && (pShrMgr->getSharedLibSymbol(name, dlNameSignaling, address) == OS_SUCCESS)
         && ((plgSignaling = (dlPlgGetSignalingDataV1)address) != NULL);

      if (!stSignaling)
            plgSignaling = NULL;

      // Test if the codec could enumerate SDP
      unsigned enumCount;
      const char *mime;
      const char **tmp;
      UtlBoolean bPlgCouldEnum = (plgEnum(&mime, &enumCount, &tmp) == RPLG_SUCCESS);

      if (st &&  bPlgCouldEnum)
      {
         //Add codec to list
         MpCodecCallInfoV1* pci = new MpCodecCallInfoV1(name, codecName,
            plgInitAddr, plgDecodeAddr, plgEncodeAddr,
            plgFreeAddr, plgEnum, plgSignaling, FALSE);

         if (!pci)
            continue;

         if (addCodecWrapperV1(pci) != OS_SUCCESS)
         {
            delete pci;
            continue;
         }

         //Plugin has been added successfully, need to rebuild cache list
         fCacheListMustUpdate = TRUE;
         count ++;
      }
   }
   if (count == 0) {
      pShrMgr->unloadSharedLib(name);
      return OS_FAILED;
   }
   return OS_SUCCESS;
}

OsStatus MpCodecFactory::addCodecWrapperV1(MpCodecCallInfoV1* wrapper)
{
   MpCodecSubInfo* mpsi;
   const char* mimeSubtype;

   // Get codec's MIME-subtype and recommended modes.
   int res = wrapper->mPlgEnum(&mimeSubtype, NULL, NULL);
   if (res != RPLG_SUCCESS)
   {
      return OS_FAILED;
   }

   mpsi = new MpCodecSubInfo(wrapper, mimeSubtype);
   if (mpsi == NULL) {
      return OS_NO_MEMORY;
   }

   sLock.acquire();
   mCodecsInfo.insert(mpsi);
   sLock.release();

   return OS_SUCCESS;
}

void MpCodecFactory::initializeStaticCodecs() //Should be called from mpStartup()
{
   MpCodecCallInfoV1* tmp = sStaticCodecsV1;
   for ( ;tmp; tmp = tmp->next())
   {
      addCodecWrapperV1(tmp);
   }
}

/* ============================== ACCESSORS =============================== */

SdpCodec::SdpCodecTypes* MpCodecFactory::getAllCodecTypes(unsigned& count)
{
   // NOT implemented yet
   return NULL;
}

const char** MpCodecFactory::getAllCodecModes(SdpCodec::SdpCodecTypes codecId, unsigned& count)
{
   // NOT implemented yet
   return NULL;
}

/* =============================== INQUIRY ================================ */

/* ////////////////////////////// PROTECTED /////////////////////////////// */

MpCodecSubInfo* MpCodecFactory::searchByMIME(const UtlString& mime) const
{
   UtlSListIterator iter(mCodecsInfo);
   MpCodecSubInfo* pinfo;

   while ((pinfo = (MpCodecSubInfo*)iter()))
   {
      if (mime.compareTo(pinfo->getMIMEtype(), UtlString::ignoreCase) == 0)
      {
         return pinfo;
      }
   }

   return NULL;
}

/* /////////////////////////////// PRIVATE //////////////////////////////// */

/* ============================== FUNCTIONS =============================== */
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <multimedia/qradioplayer.h>
#include <multimedia/qmediaservice.h>
#include <multimedia/qmediaobject_p.h>
#include <multimedia/qradioplayercontrol.h>

/*!
    \class QRadioPlayer
    \brief The QRadioPlayer class provides an interface to the systems radio device.

    You can control the systems radio device using this interface, for example:

    \code
        player = new QRadioPlayer;
        connect(player,SIGNAL(frequencyChanged(int)),this,SLOT(freqChanged(int)));
        if(player->isSupportedBand(QRadioPlayer::FM))
            player->setBand(QRadioPlayer::FM);
        player->setFrequency(yourRadioStationFrequency);
        player->setVolume(100);
    \endcode

    The player object will emit signals for any changes in state such as:
    bandChanged(), frequencyChanged(), stereoStatusChanged(), searchingStatusChanged(),
    signalStrengthChanged(), durationChanged(), volumeChanged(), mutingChanged().

    You can change between the frequency bands using setBand() however it is recommended
    that you check to make sure the band is available first using isSupportedBand().

*/

class QRadioPlayerPrivate : public QMediaObjectPrivate
{
public:
    QRadioPlayerPrivate():provider(0), control(0) {}
    QMediaServiceProvider *provider;
    QRadioPlayerControl* control;
};

/*!
    Construct a QRadioPlayer object with service \a provider and \a parent.

    If the service is not specified the system default will be used.
*/

QRadioPlayer::QRadioPlayer(QObject *parent, QMediaServiceProvider* provider):
    QMediaObject(*new QRadioPlayerPrivate, parent, provider->requestService("radio"))
{
    Q_D(QRadioPlayer);

    d->provider = provider;

    if (d->service != 0) {
        d->control = qobject_cast<QRadioPlayerControl*>(d->service->control(QRadioPlayerControl_iid));
        if (d->control != 0) {
            connect(d->control, SIGNAL(bandChanged(QRadioPlayer::Band)), SIGNAL(bandChanged(QRadioPlayer::Band)));
            connect(d->control, SIGNAL(frequencyChanged(int)), SIGNAL(frequencyChanged(int)));
            connect(d->control, SIGNAL(stereoStatusChanged(bool)), SIGNAL(stereoStatusChanged(bool)));
            connect(d->control, SIGNAL(searchingStatusChanged(bool)), SIGNAL(searchingStatusChanged(bool)));
            connect(d->control, SIGNAL(signalStrengthChanged(int)), SIGNAL(signalStrengthChanged(int)));
            connect(d->control, SIGNAL(durationChanged(qint64)), SIGNAL(durationChanged(qint64)));
            connect(d->control, SIGNAL(volumeChanged(int)), SIGNAL(volumeChanged(int)));
            connect(d->control, SIGNAL(mutingChanged(bool)), SIGNAL(mutingChanged(bool)));

            addPropertyWatch("duration");
        }
    }
}

/*!
    Destruct the QRadioPlayer object.
*/

QRadioPlayer::~QRadioPlayer()
{
    Q_D(QRadioPlayer);

    d->provider->releaseService(d->service);
}

/*!
    \property QRadioPlayer::band
    \brief The current frequency range being used.

    \sa QRadioPlayer::Band
*/

/*!
    Returns the current QRadioPlayer::Band.
*/

QRadioPlayer::Band QRadioPlayer::band() const
{
    Q_D(const QRadioPlayer);

    if (d->control != 0)
        return d->control->band();

    return QRadioPlayer::FM;
}

/*!
    \property QRadioPlayer::frequency
    \brief The current frequency being used in Hertz.
*/

/*!
    Returns the current frequency.
*/

int QRadioPlayer::frequency() const
{
    Q_D(const QRadioPlayer);

    if (d->control != 0)
        return d->control->frequency();

    return 0;
}

/*!
    \property QRadioPlayer::stereo
    \brief In Stereo mode.
*/

/*!
    Returns true if in stereo.
*/

bool QRadioPlayer::isStereo() const
{
    Q_D(const QRadioPlayer);

    if (d->control != 0)
        return d->control->isStereo();

    return false;
}

/*!
    Returns true if \a b is an available band.
*/

bool QRadioPlayer::isSupportedBand(QRadioPlayer::Band b) const
{
    Q_D(const QRadioPlayer);

    if (d->control != 0)
        return d->control->isSupportedBand(b);

    return false;
}

/*!
    \property QRadioPlayer::signalStrength
    \brief The strength of the current radio signal as a percentage.
*/

/*!
    Returns the signal strength as a percentage.
*/

int QRadioPlayer::signalStrength() const
{
    Q_D(const QRadioPlayer);

    if (d->control != 0)
        return d->control->signalStrength();

    return 0;
}

/*!
    \property QRadioPlayer::duration
    \brief The duration at current frequency in milliseconds.
*/

/*!
    Returns duration at current frequency in milliseconds.
*/

qint64 QRadioPlayer::duration() const
{
    Q_D(const QRadioPlayer);

    if (d->control != 0)
        return d->control->duration();

    return 0;
}

/*!
    \property QRadioPlayer::volume
    \brief The current volume as a percentage.
*/

/*!
    Returns the volume as a percentage.
*/

int QRadioPlayer::volume() const
{
    Q_D(const QRadioPlayer);

    if (d->control != 0)
        return d->control->volume();
}

/*!
    \property QRadioPlayer::muted
    \brief Returns true if muted.
*/

/*!
    Returns true if muted.
*/

bool QRadioPlayer::isMuted() const
{
    Q_D(const QRadioPlayer);

    if (d->control != 0)
        return d->control->isMuted();

    return false;
}

/*!
    Sets the band being used to \a band.
*/

void QRadioPlayer::setBand(QRadioPlayer::Band band)
{
    Q_D(QRadioPlayer);

    if (d->control != 0)
        d->control->setBand(band);
}

/*!
    Sets the frequency being used to \a frequency.
*/

void QRadioPlayer::setFrequency(int frequency)
{
    Q_D(QRadioPlayer);

    if (d->control != 0)
        d->control->setFrequency(frequency);
}

/*!
    If \a stereo is true, Sets to stereo mode, otherwise, mono mode.
*/

void QRadioPlayer::setStereo(bool stereo)
{
    Q_D(QRadioPlayer);

    if (d->control != 0)
        d->control->setStereo(stereo);
}

/*!
    Sets the volume to \a volume.
    volume is a percentage.
*/

void QRadioPlayer::setVolume(int volume)
{
    Q_D(QRadioPlayer);

    if (d->control != 0)
        d->control->setVolume(volume);
}

/*!
    If muted is true sets to mute, otherwise unmute.
*/

void QRadioPlayer::setMuted(bool muted)
{
    Q_D(QRadioPlayer);

    if (d->control != 0)
        d->control->setMuted(muted);
}

/*!
    \property QRadioPlayer::searching
    \brief Returns true if currently scanning.
*/

/*!
    Returns true if currently scanning.
*/

bool QRadioPlayer::isSearching() const
{
    Q_D(const QRadioPlayer);

    if (d->control != 0)
        return d->control->isSearching();

    return false;
}

/*!
    Start scanning through frequencies, ascending.
*/

void QRadioPlayer::searchForward()
{
    Q_D(QRadioPlayer);

    if (d->control != 0)
        d->control->searchForward();
}

/*!
    Start scanning through frequencies, descending.
*/

void QRadioPlayer::searchBackward()
{
    Q_D(QRadioPlayer);

    if (d->control != 0)
        d->control->searchBackward();
}

/*!
    Stop any scanning being done.
*/

void QRadioPlayer::cancelSearch()
{
    Q_D(QRadioPlayer);

    if (d->control != 0)
        d->control->cancelSearch();
}

/*!
    \fn void QRadioPlayer::bandChanged(QRadioPlayer::Band band)

    Signal the change in frequency range to \a band.
*/

/*!
    \fn void QRadioPlayer::frequencyChanged(int frequency)

    Signal the change in current \a frequency.
*/

/*!
    \fn void QRadioPlayer::mutingChanged(bool muted)

    Signal the change in mute condition to \a muted.
*/

/*!
    \fn void QRadioPlayer::volumeChanged(int volume)

    Signal the change in volume percentage to \a volume.
*/

/*!
    \fn void QRadioPlayer::searchingStatusChanged(bool searching)

    Signal the change in scanning mode to \a searching.
*/

/*!
    \fn void QRadioPlayer::stereoStatusChanged(bool stereo)

    Signal the change in stereo mode to \a stereo.
*/

/*!
    \fn void QRadioPlayer::durationChanged(qint64 duration)

    Signal the change in the \a duration of the current frequency playback in milliseconds.
*/

/*!
    \fn void QRadioPlayer::signalStrengthChanged(int signalStrength)

    Signal emitted when signal strength changes to new value \a signalStrength.
*/

/*!
    \enum QRadioPlayer::Band

    \value AM 520 to 1610 kHz, 9 or 10kHz channel spacing, extended 1610 to 1710 kHz
    \value FM 87.5 to 108.0 MHz, except Japan 76-90 MHz
    \value SW 1.711 to 30.0 MHz, divided into 15 bands. 5kHz channel spacing
    \value LW 148.5 to 283.5 kHz, 9kHz channel spacing (Europe, Africa, Asia)
*/

<commit_msg>QRadioPlayer; return default volume(0) when no control available.<commit_after>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <multimedia/qradioplayer.h>
#include <multimedia/qmediaservice.h>
#include <multimedia/qmediaobject_p.h>
#include <multimedia/qradioplayercontrol.h>

/*!
    \class QRadioPlayer
    \brief The QRadioPlayer class provides an interface to the systems radio device.

    You can control the systems radio device using this interface, for example:

    \code
        player = new QRadioPlayer;
        connect(player,SIGNAL(frequencyChanged(int)),this,SLOT(freqChanged(int)));
        if(player->isSupportedBand(QRadioPlayer::FM))
            player->setBand(QRadioPlayer::FM);
        player->setFrequency(yourRadioStationFrequency);
        player->setVolume(100);
    \endcode

    The player object will emit signals for any changes in state such as:
    bandChanged(), frequencyChanged(), stereoStatusChanged(), searchingStatusChanged(),
    signalStrengthChanged(), durationChanged(), volumeChanged(), mutingChanged().

    You can change between the frequency bands using setBand() however it is recommended
    that you check to make sure the band is available first using isSupportedBand().

*/

class QRadioPlayerPrivate : public QMediaObjectPrivate
{
public:
    QRadioPlayerPrivate():provider(0), control(0) {}
    QMediaServiceProvider *provider;
    QRadioPlayerControl* control;
};

/*!
    Construct a QRadioPlayer object with service \a provider and \a parent.

    If the service is not specified the system default will be used.
*/

QRadioPlayer::QRadioPlayer(QObject *parent, QMediaServiceProvider* provider):
    QMediaObject(*new QRadioPlayerPrivate, parent, provider->requestService("radio"))
{
    Q_D(QRadioPlayer);

    d->provider = provider;

    if (d->service != 0) {
        d->control = qobject_cast<QRadioPlayerControl*>(d->service->control(QRadioPlayerControl_iid));
        if (d->control != 0) {
            connect(d->control, SIGNAL(bandChanged(QRadioPlayer::Band)), SIGNAL(bandChanged(QRadioPlayer::Band)));
            connect(d->control, SIGNAL(frequencyChanged(int)), SIGNAL(frequencyChanged(int)));
            connect(d->control, SIGNAL(stereoStatusChanged(bool)), SIGNAL(stereoStatusChanged(bool)));
            connect(d->control, SIGNAL(searchingStatusChanged(bool)), SIGNAL(searchingStatusChanged(bool)));
            connect(d->control, SIGNAL(signalStrengthChanged(int)), SIGNAL(signalStrengthChanged(int)));
            connect(d->control, SIGNAL(durationChanged(qint64)), SIGNAL(durationChanged(qint64)));
            connect(d->control, SIGNAL(volumeChanged(int)), SIGNAL(volumeChanged(int)));
            connect(d->control, SIGNAL(mutingChanged(bool)), SIGNAL(mutingChanged(bool)));

            addPropertyWatch("duration");
        }
    }
}

/*!
    Destruct the QRadioPlayer object.
*/

QRadioPlayer::~QRadioPlayer()
{
    Q_D(QRadioPlayer);

    d->provider->releaseService(d->service);
}

/*!
    \property QRadioPlayer::band
    \brief The current frequency range being used.

    \sa QRadioPlayer::Band
*/

/*!
    Returns the current QRadioPlayer::Band.
*/

QRadioPlayer::Band QRadioPlayer::band() const
{
    Q_D(const QRadioPlayer);

    if (d->control != 0)
        return d->control->band();

    return QRadioPlayer::FM;
}

/*!
    \property QRadioPlayer::frequency
    \brief The current frequency being used in Hertz.
*/

/*!
    Returns the current frequency.
*/

int QRadioPlayer::frequency() const
{
    Q_D(const QRadioPlayer);

    if (d->control != 0)
        return d->control->frequency();

    return 0;
}

/*!
    \property QRadioPlayer::stereo
    \brief In Stereo mode.
*/

/*!
    Returns true if in stereo.
*/

bool QRadioPlayer::isStereo() const
{
    Q_D(const QRadioPlayer);

    if (d->control != 0)
        return d->control->isStereo();

    return false;
}

/*!
    Returns true if \a b is an available band.
*/

bool QRadioPlayer::isSupportedBand(QRadioPlayer::Band b) const
{
    Q_D(const QRadioPlayer);

    if (d->control != 0)
        return d->control->isSupportedBand(b);

    return false;
}

/*!
    \property QRadioPlayer::signalStrength
    \brief The strength of the current radio signal as a percentage.
*/

/*!
    Returns the signal strength as a percentage.
*/

int QRadioPlayer::signalStrength() const
{
    Q_D(const QRadioPlayer);

    if (d->control != 0)
        return d->control->signalStrength();

    return 0;
}

/*!
    \property QRadioPlayer::duration
    \brief The duration at current frequency in milliseconds.
*/

/*!
    Returns duration at current frequency in milliseconds.
*/

qint64 QRadioPlayer::duration() const
{
    Q_D(const QRadioPlayer);

    if (d->control != 0)
        return d->control->duration();

    return 0;
}

/*!
    \property QRadioPlayer::volume
    \brief The current volume as a percentage.
*/

/*!
    Returns the volume as a percentage.
*/

int QRadioPlayer::volume() const
{
    Q_D(const QRadioPlayer);

    if (d->control != 0)
        return d->control->volume();

    return 0;
}

/*!
    \property QRadioPlayer::muted
    \brief Returns true if muted.
*/

/*!
    Returns true if muted.
*/

bool QRadioPlayer::isMuted() const
{
    Q_D(const QRadioPlayer);

    if (d->control != 0)
        return d->control->isMuted();

    return false;
}

/*!
    Sets the band being used to \a band.
*/

void QRadioPlayer::setBand(QRadioPlayer::Band band)
{
    Q_D(QRadioPlayer);

    if (d->control != 0)
        d->control->setBand(band);
}

/*!
    Sets the frequency being used to \a frequency.
*/

void QRadioPlayer::setFrequency(int frequency)
{
    Q_D(QRadioPlayer);

    if (d->control != 0)
        d->control->setFrequency(frequency);
}

/*!
    If \a stereo is true, Sets to stereo mode, otherwise, mono mode.
*/

void QRadioPlayer::setStereo(bool stereo)
{
    Q_D(QRadioPlayer);

    if (d->control != 0)
        d->control->setStereo(stereo);
}

/*!
    Sets the volume to \a volume.
    volume is a percentage.
*/

void QRadioPlayer::setVolume(int volume)
{
    Q_D(QRadioPlayer);

    if (d->control != 0)
        d->control->setVolume(volume);
}

/*!
    If muted is true sets to mute, otherwise unmute.
*/

void QRadioPlayer::setMuted(bool muted)
{
    Q_D(QRadioPlayer);

    if (d->control != 0)
        d->control->setMuted(muted);
}

/*!
    \property QRadioPlayer::searching
    \brief Returns true if currently scanning.
*/

/*!
    Returns true if currently scanning.
*/

bool QRadioPlayer::isSearching() const
{
    Q_D(const QRadioPlayer);

    if (d->control != 0)
        return d->control->isSearching();

    return false;
}

/*!
    Start scanning through frequencies, ascending.
*/

void QRadioPlayer::searchForward()
{
    Q_D(QRadioPlayer);

    if (d->control != 0)
        d->control->searchForward();
}

/*!
    Start scanning through frequencies, descending.
*/

void QRadioPlayer::searchBackward()
{
    Q_D(QRadioPlayer);

    if (d->control != 0)
        d->control->searchBackward();
}

/*!
    Stop any scanning being done.
*/

void QRadioPlayer::cancelSearch()
{
    Q_D(QRadioPlayer);

    if (d->control != 0)
        d->control->cancelSearch();
}

/*!
    \fn void QRadioPlayer::bandChanged(QRadioPlayer::Band band)

    Signal the change in frequency range to \a band.
*/

/*!
    \fn void QRadioPlayer::frequencyChanged(int frequency)

    Signal the change in current \a frequency.
*/

/*!
    \fn void QRadioPlayer::mutingChanged(bool muted)

    Signal the change in mute condition to \a muted.
*/

/*!
    \fn void QRadioPlayer::volumeChanged(int volume)

    Signal the change in volume percentage to \a volume.
*/

/*!
    \fn void QRadioPlayer::searchingStatusChanged(bool searching)

    Signal the change in scanning mode to \a searching.
*/

/*!
    \fn void QRadioPlayer::stereoStatusChanged(bool stereo)

    Signal the change in stereo mode to \a stereo.
*/

/*!
    \fn void QRadioPlayer::durationChanged(qint64 duration)

    Signal the change in the \a duration of the current frequency playback in milliseconds.
*/

/*!
    \fn void QRadioPlayer::signalStrengthChanged(int signalStrength)

    Signal emitted when signal strength changes to new value \a signalStrength.
*/

/*!
    \enum QRadioPlayer::Band

    \value AM 520 to 1610 kHz, 9 or 10kHz channel spacing, extended 1610 to 1710 kHz
    \value FM 87.5 to 108.0 MHz, except Japan 76-90 MHz
    \value SW 1.711 to 30.0 MHz, divided into 15 bands. 5kHz channel spacing
    \value LW 148.5 to 283.5 kHz, 9kHz channel spacing (Europe, Africa, Asia)
*/

<|endoftext|>