<commit_before>/*
The MIT License (MIT)

Copyright (c) 2013-2016 SRS(ossrs)

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

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

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

#include <srs_core.hpp>

#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

#include <sstream>
using namespace std;

#ifdef SRS_AUTO_GPERF_MP
    #include <gperftools/heap-profiler.h>
#endif
#ifdef SRS_AUTO_GPERF_CP
    #include <gperftools/profiler.h>
#endif

using namespace std;

#include <srs_kernel_error.hpp>
#include <srs_app_server.hpp>
#include <srs_app_config.hpp>
#include <srs_app_log.hpp>
#include <srs_kernel_utility.hpp>
#include <srs_core_performance.hpp>
#include <srs_app_utility.hpp>
#include <srs_core_autofree.hpp>

// pre-declare
int run(SrsServer* svr);
int run_master(SrsServer* svr);

// @global log and context.
ISrsLog* _srs_log = new SrsFastLog();
ISrsThreadContext* _srs_context = new ISrsThreadContext();
// @global config object for app module.
SrsConfig* _srs_config = new SrsConfig();

// @global version of srs, which can grep keyword "XCORE"
extern const char* _srs_version;

/**
* show the features by macro, the actual macro values.
*/
void show_macro_features()
{
    if (true) {
        stringstream ss;

        ss << "features";

        // rch(rtmp complex handshake)
        ss << ", rch:" << srs_bool2switch(SRS_AUTO_SSL_BOOL);
        ss << ", hls:" << srs_bool2switch(SRS_AUTO_HLS_BOOL);
        ss << ", hds:" << srs_bool2switch(SRS_AUTO_HDS_BOOL);
        // hc(http callback)
        ss << ", hc:" << srs_bool2switch(SRS_AUTO_HTTP_CALLBACK_BOOL);
        // ha(http api)
        ss << ", ha:" << srs_bool2switch(SRS_AUTO_HTTP_API_BOOL);
        // hs(http server)
        ss << ", hs:" << srs_bool2switch(SRS_AUTO_HTTP_SERVER_BOOL);
        // hp(http parser)
        ss << ", hp:" << srs_bool2switch(SRS_AUTO_HTTP_CORE_BOOL);
        ss << ", dvr:" << srs_bool2switch(SRS_AUTO_DVR_BOOL);
        // trans(transcode)
        ss << ", trans:" << srs_bool2switch(SRS_AUTO_TRANSCODE_BOOL);
        // inge(ingest)
        ss << ", inge:" << srs_bool2switch(SRS_AUTO_INGEST_BOOL);
        ss << ", kafka:" << srs_bool2switch(SRS_AUTO_KAFKA_BOOL);
        ss << ", stat:" << srs_bool2switch(SRS_AUTO_STAT_BOOL);
        ss << ", nginx:" << srs_bool2switch(SRS_AUTO_NGINX_BOOL);
        // ff(ffmpeg)
        ss << ", ff:" << srs_bool2switch(SRS_AUTO_FFMPEG_TOOL_BOOL);
        // sc(stream-caster)
        ss << ", sc:" << srs_bool2switch(SRS_AUTO_STREAM_CASTER_BOOL);
        srs_trace(ss.str().c_str());
    }

    if (true) {
        stringstream ss;
        ss << "SRS on ";
#ifdef SRS_OSX
        ss << "OSX";
#endif
#ifdef SRS_PI
        ss << "RespberryPi";
#endif
#ifdef SRS_CUBIE
        ss << "CubieBoard";
#endif
#ifdef SRS_ARM_UBUNTU12
        ss << "ARM(build on ubuntu)";
#endif
#ifdef SRS_MIPS_UBUNTU12
        ss << "MIPS(build on ubuntu)";
#endif

#if defined(__amd64__)
        ss << " amd64";
#endif
#if defined(__x86_64__)
        ss << " x86_64";
#endif
#if defined(__i386__)
        ss << " i386";
#endif
#if defined(__arm__)
        ss << "arm";
#endif

#ifndef SRS_OSX
        ss << ", glibc" << (int)__GLIBC__ << "." <<  (int)__GLIBC_MINOR__;
#endif

        ss << ", conf:" << _srs_config->config() << ", limit:" << _srs_config->get_max_connections()
            << ", writev:" << sysconf(_SC_IOV_MAX) << ", encoding:" << (srs_is_little_endian()? "little-endian":"big-endian")
            << ", HZ:" << (int)sysconf(_SC_CLK_TCK);

        srs_trace(ss.str().c_str());
    }

    if (true) {
        stringstream ss;

        // mw(merged-write)
        ss << "mw sleep:" << SRS_PERF_MW_SLEEP << "ms";

        // mr(merged-read)
        ss << ". mr ";
#ifdef SRS_PERF_MERGED_READ
        ss << "enabled:on";
#else
        ss << "enabled:off";
#endif
        ss << ", default:" << SRS_PERF_MR_ENABLED << ", sleep:" << SRS_PERF_MR_SLEEP << "ms";
        ss << ", @see " << RTMP_SIG_SRS_ISSUES(241);

        srs_trace(ss.str().c_str());
    }

    if (true) {
        stringstream ss;

        // gc(gop-cache)
        ss << "gc:" << srs_bool2switch(SRS_PERF_GOP_CACHE);
        // pq(play-queue)
        ss << ", pq:" << SRS_PERF_PLAY_QUEUE << "s";
        // cscc(chunk stream cache cid)
        ss << ", cscc:[0," << SRS_PERF_CHUNK_STREAM_CACHE << ")";
        // csa(complex send algorithm)
        ss << ", csa:";
#ifndef SRS_PERF_COMPLEX_SEND
        ss << "off";
#else
        ss << "on";
#endif

        // tn(TCP_NODELAY)
        ss << ", tn:";
#ifdef SRS_PERF_TCP_NODELAY
        ss << "on(may hurts performance)";
#else
        ss << "off";
#endif

        // ss(SO_SENDBUF)
        ss << ", ss:";
#ifdef SRS_PERF_SO_SNDBUF_SIZE
        ss << SRS_PERF_SO_SNDBUF_SIZE;
#else
        ss << "auto(guess by merged write)";
#endif

        srs_trace(ss.str().c_str());
    }

    // others
    int possible_mr_latency = 0;
#ifdef SRS_PERF_MERGED_READ
    possible_mr_latency = SRS_PERF_MR_SLEEP;
#endif
    srs_trace("system default latency in ms: mw(0-%d) + mr(0-%d) + play-queue(0-%d)",
              SRS_PERF_MW_SLEEP, possible_mr_latency, SRS_PERF_PLAY_QUEUE*1000);

#ifdef SRS_AUTO_MEM_WATCH
    #warning "srs memory watcher will hurts performance. user should kill by SIGTERM or init.d script."
    srs_warn("srs memory watcher will hurts performance. user should kill by SIGTERM or init.d script.");
#endif

#if defined(SRS_AUTO_STREAM_CASTER)
    #warning "stream caster is experiment feature."
    srs_warn("stream caster is experiment feature.");
#endif

#if VERSION_MAJOR > VERSION_STABLE
    #warning "current branch is not stable, please use stable branch instead."
    srs_warn("SRS %s is not stable, please use stable branch %s instead", RTMP_SIG_SRS_VERSION, VERSION_STABLE_BRANCH);
#endif

#if defined(SRS_PERF_SO_SNDBUF_SIZE) && !defined(SRS_PERF_MW_SO_SNDBUF)
    #error "SRS_PERF_SO_SNDBUF_SIZE depends on SRS_PERF_MW_SO_SNDBUF"
#endif
}

/**
* main entrance.
*/
int main(int argc, char** argv)
{
    int ret = ERROR_SUCCESS;

    // TODO: support both little and big endian.
    srs_assert(srs_is_little_endian());

    // for gperf gmp or gcp,
    // should never enable it when not enabled for performance issue.
#ifdef SRS_AUTO_GPERF_MP
    HeapProfilerStart("gperf.srs.gmp");
#endif
#ifdef SRS_AUTO_GPERF_CP
    ProfilerStart("gperf.srs.gcp");
#endif

    // directly compile error when these two macro defines.
#if defined(SRS_AUTO_GPERF_MC) && defined(SRS_AUTO_GPERF_MP)
    #error ("option --with-gmc confict with --with-gmp, "
        "@see: http://google-perftools.googlecode.com/svn/trunk/doc/heap_checker.html\n"
        "Note that since the heap-checker uses the heap-profiling framework internally, "
        "it is not possible to run both the heap-checker and heap profiler at the same time");
#endif

    // never use gmp to check memory leak.
#ifdef SRS_AUTO_GPERF_MP
    #warning "gmp is not used for memory leak, please use gmc instead."
#endif

    // never use srs log(srs_trace, srs_error, etc) before config parse the option,
    // which will load the log config and apply it.
    if ((ret = _srs_config->parse_options(argc, argv)) != ERROR_SUCCESS) {
        return ret;
    }

    // change the work dir and set cwd.
    string cwd = _srs_config->get_work_dir();
    if (!cwd.empty() && cwd != "./" && (ret = chdir(cwd.c_str())) != ERROR_SUCCESS) {
        srs_error("change cwd to %s failed. ret=%d", cwd.c_str(), ret);
        return ret;
    }
    if ((ret = _srs_config->initialize_cwd()) != ERROR_SUCCESS) {
        return ret;
    }

    // config parsed, initialize log.
    if ((ret = _srs_log->initialize()) != ERROR_SUCCESS) {
        return ret;
    }

    // config already applied to log.
    srs_trace(RTMP_SIG_SRS_SERVER", stable is "RTMP_SIG_SRS_PRIMARY);
    srs_trace("license: "RTMP_SIG_SRS_LICENSE", "RTMP_SIG_SRS_COPYRIGHT);
    srs_trace("authors: "RTMP_SIG_SRS_AUTHROS);
    srs_trace("contributors: "SRS_AUTO_CONSTRIBUTORS);
    srs_trace("build: %s, configure:%s, uname: %s", SRS_AUTO_BUILD_DATE, SRS_AUTO_USER_CONFIGURE, SRS_AUTO_UNAME);
    srs_trace("configure detail: "SRS_AUTO_CONFIGURE);
#ifdef SRS_AUTO_EMBEDED_TOOL_CHAIN
    srs_trace("crossbuild tool chain: "SRS_AUTO_EMBEDED_TOOL_CHAIN);
#endif
    srs_trace("cwd=%s, work_dir=%s", _srs_config->cwd().c_str(), cwd.c_str());

#ifdef SRS_PERF_GLIBC_MEMORY_CHECK
    // ensure glibc write error to stderr.
    setenv("LIBC_FATAL_STDERR_", "1", 1);
    // ensure glibc to do alloc check.
    setenv("MALLOC_CHECK_", "1", 1);
    srs_trace("env MALLOC_CHECK_=1 LIBC_FATAL_STDERR_=1");
#endif

#ifdef SRS_AUTO_GPERF_MD
    char* TCMALLOC_PAGE_FENCE = getenv("TCMALLOC_PAGE_FENCE");
    if (!TCMALLOC_PAGE_FENCE || strcmp(TCMALLOC_PAGE_FENCE, "1")) {
        srs_trace("gmd enabled without env TCMALLOC_PAGE_FENCE=1");
    } else {
        srs_trace("env TCMALLOC_PAGE_FENCE=1");
    }
#endif

    // we check the config when the log initialized.
    if ((ret = _srs_config->check_config()) != ERROR_SUCCESS) {
        return ret;
    }

    // features
    show_macro_features();

    SrsServer* svr = new SrsServer();
    SrsAutoFree(SrsServer, svr);

    /**
    * we do nothing in the constructor of server,
    * and use initialize to create members, set hooks for instance the reload handler,
    * all initialize will done in this stage.
    */
    if ((ret = svr->initialize(NULL)) != ERROR_SUCCESS) {
        return ret;
    }

    return run(svr);
}

int run(SrsServer* svr)
{
    // if not deamon, directly run master.
    if (!_srs_config->get_deamon()) {
        return run_master(svr);
    }

    srs_trace("start deamon mode...");

    int pid = fork();

    if(pid < 0) {
        srs_error("create process error. ret=-1"); //ret=0
        return -1;
    }

    // grandpa
    if(pid > 0) {
        int status = 0;
        if(waitpid(pid, &status, 0) == -1) {
            srs_error("wait child process error! ret=-1"); //ret=0
        }
        srs_trace("grandpa process exit.");
        exit(0);
    }

    // father
    pid = fork();

    if(pid < 0) {
        srs_error("create process error. ret=0");
        return -1;
    }

    if(pid > 0) {
        srs_trace("father process exit. ret=0");
        exit(0);
    }

    // son
    srs_trace("son(deamon) process running.");

    return run_master(svr);
}

int run_master(SrsServer* svr)
{
    int ret = ERROR_SUCCESS;

    if ((ret = svr->initialize_st()) != ERROR_SUCCESS) {
        return ret;
    }

    if ((ret = svr->initialize_signal()) != ERROR_SUCCESS) {
        return ret;
    }

    if ((ret = svr->acquire_pid_file()) != ERROR_SUCCESS) {
        return ret;
    }

    if ((ret = svr->listen()) != ERROR_SUCCESS) {
        return ret;
    }

    if ((ret = svr->register_signal()) != ERROR_SUCCESS) {
        return ret;
    }

    if ((ret = svr->http_handle()) != ERROR_SUCCESS) {
        return ret;
    }

    if ((ret = svr->ingest()) != ERROR_SUCCESS) {
        return ret;
    }

    if ((ret = svr->cycle()) != ERROR_SUCCESS) {
        return ret;
    }

    return 0;
}

<commit_msg>fix bug<commit_after>/*
The MIT License (MIT)

Copyright (c) 2013-2016 SRS(ossrs)

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

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

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

#include <srs_core.hpp>

#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

#include <sstream>
using namespace std;

#ifdef SRS_AUTO_GPERF_MP
    #include <gperftools/heap-profiler.h>
#endif
#ifdef SRS_AUTO_GPERF_CP
    #include <gperftools/profiler.h>
#endif

using namespace std;

#include <srs_kernel_error.hpp>
#include <srs_app_server.hpp>
#include <srs_app_config.hpp>
#include <srs_app_log.hpp>
#include <srs_kernel_utility.hpp>
#include <srs_core_performance.hpp>
#include <srs_app_utility.hpp>
#include <srs_core_autofree.hpp>

// pre-declare
int run(SrsServer* svr);
int run_master(SrsServer* svr);

// @global log and context.
ISrsLog* _srs_log = new SrsFastLog();
ISrsThreadContext* _srs_context = new SrsThreadContext();
// @global config object for app module.
SrsConfig* _srs_config = new SrsConfig();

// @global version of srs, which can grep keyword "XCORE"
extern const char* _srs_version;

/**
* show the features by macro, the actual macro values.
*/
void show_macro_features()
{
    if (true) {
        stringstream ss;

        ss << "features";

        // rch(rtmp complex handshake)
        ss << ", rch:" << srs_bool2switch(SRS_AUTO_SSL_BOOL);
        ss << ", hls:" << srs_bool2switch(SRS_AUTO_HLS_BOOL);
        ss << ", hds:" << srs_bool2switch(SRS_AUTO_HDS_BOOL);
        // hc(http callback)
        ss << ", hc:" << srs_bool2switch(SRS_AUTO_HTTP_CALLBACK_BOOL);
        // ha(http api)
        ss << ", ha:" << srs_bool2switch(SRS_AUTO_HTTP_API_BOOL);
        // hs(http server)
        ss << ", hs:" << srs_bool2switch(SRS_AUTO_HTTP_SERVER_BOOL);
        // hp(http parser)
        ss << ", hp:" << srs_bool2switch(SRS_AUTO_HTTP_CORE_BOOL);
        ss << ", dvr:" << srs_bool2switch(SRS_AUTO_DVR_BOOL);
        // trans(transcode)
        ss << ", trans:" << srs_bool2switch(SRS_AUTO_TRANSCODE_BOOL);
        // inge(ingest)
        ss << ", inge:" << srs_bool2switch(SRS_AUTO_INGEST_BOOL);
        ss << ", kafka:" << srs_bool2switch(SRS_AUTO_KAFKA_BOOL);
        ss << ", stat:" << srs_bool2switch(SRS_AUTO_STAT_BOOL);
        ss << ", nginx:" << srs_bool2switch(SRS_AUTO_NGINX_BOOL);
        // ff(ffmpeg)
        ss << ", ff:" << srs_bool2switch(SRS_AUTO_FFMPEG_TOOL_BOOL);
        // sc(stream-caster)
        ss << ", sc:" << srs_bool2switch(SRS_AUTO_STREAM_CASTER_BOOL);
        srs_trace(ss.str().c_str());
    }

    if (true) {
        stringstream ss;
        ss << "SRS on ";
#ifdef SRS_OSX
        ss << "OSX";
#endif
#ifdef SRS_PI
        ss << "RespberryPi";
#endif
#ifdef SRS_CUBIE
        ss << "CubieBoard";
#endif
#ifdef SRS_ARM_UBUNTU12
        ss << "ARM(build on ubuntu)";
#endif
#ifdef SRS_MIPS_UBUNTU12
        ss << "MIPS(build on ubuntu)";
#endif

#if defined(__amd64__)
        ss << " amd64";
#endif
#if defined(__x86_64__)
        ss << " x86_64";
#endif
#if defined(__i386__)
        ss << " i386";
#endif
#if defined(__arm__)
        ss << "arm";
#endif

#ifndef SRS_OSX
        ss << ", glibc" << (int)__GLIBC__ << "." <<  (int)__GLIBC_MINOR__;
#endif

        ss << ", conf:" << _srs_config->config() << ", limit:" << _srs_config->get_max_connections()
            << ", writev:" << sysconf(_SC_IOV_MAX) << ", encoding:" << (srs_is_little_endian()? "little-endian":"big-endian")
            << ", HZ:" << (int)sysconf(_SC_CLK_TCK);

        srs_trace(ss.str().c_str());
    }

    if (true) {
        stringstream ss;

        // mw(merged-write)
        ss << "mw sleep:" << SRS_PERF_MW_SLEEP << "ms";

        // mr(merged-read)
        ss << ". mr ";
#ifdef SRS_PERF_MERGED_READ
        ss << "enabled:on";
#else
        ss << "enabled:off";
#endif
        ss << ", default:" << SRS_PERF_MR_ENABLED << ", sleep:" << SRS_PERF_MR_SLEEP << "ms";
        ss << ", @see " << RTMP_SIG_SRS_ISSUES(241);

        srs_trace(ss.str().c_str());
    }

    if (true) {
        stringstream ss;

        // gc(gop-cache)
        ss << "gc:" << srs_bool2switch(SRS_PERF_GOP_CACHE);
        // pq(play-queue)
        ss << ", pq:" << SRS_PERF_PLAY_QUEUE << "s";
        // cscc(chunk stream cache cid)
        ss << ", cscc:[0," << SRS_PERF_CHUNK_STREAM_CACHE << ")";
        // csa(complex send algorithm)
        ss << ", csa:";
#ifndef SRS_PERF_COMPLEX_SEND
        ss << "off";
#else
        ss << "on";
#endif

        // tn(TCP_NODELAY)
        ss << ", tn:";
#ifdef SRS_PERF_TCP_NODELAY
        ss << "on(may hurts performance)";
#else
        ss << "off";
#endif

        // ss(SO_SENDBUF)
        ss << ", ss:";
#ifdef SRS_PERF_SO_SNDBUF_SIZE
        ss << SRS_PERF_SO_SNDBUF_SIZE;
#else
        ss << "auto(guess by merged write)";
#endif

        srs_trace(ss.str().c_str());
    }

    // others
    int possible_mr_latency = 0;
#ifdef SRS_PERF_MERGED_READ
    possible_mr_latency = SRS_PERF_MR_SLEEP;
#endif
    srs_trace("system default latency in ms: mw(0-%d) + mr(0-%d) + play-queue(0-%d)",
              SRS_PERF_MW_SLEEP, possible_mr_latency, SRS_PERF_PLAY_QUEUE*1000);

#ifdef SRS_AUTO_MEM_WATCH
    #warning "srs memory watcher will hurts performance. user should kill by SIGTERM or init.d script."
    srs_warn("srs memory watcher will hurts performance. user should kill by SIGTERM or init.d script.");
#endif

#if defined(SRS_AUTO_STREAM_CASTER)
    #warning "stream caster is experiment feature."
    srs_warn("stream caster is experiment feature.");
#endif

#if VERSION_MAJOR > VERSION_STABLE
    #warning "current branch is not stable, please use stable branch instead."
    srs_warn("SRS %s is not stable, please use stable branch %s instead", RTMP_SIG_SRS_VERSION, VERSION_STABLE_BRANCH);
#endif

#if defined(SRS_PERF_SO_SNDBUF_SIZE) && !defined(SRS_PERF_MW_SO_SNDBUF)
    #error "SRS_PERF_SO_SNDBUF_SIZE depends on SRS_PERF_MW_SO_SNDBUF"
#endif
}

/**
* main entrance.
*/
int main(int argc, char** argv)
{
    int ret = ERROR_SUCCESS;

    // TODO: support both little and big endian.
    srs_assert(srs_is_little_endian());

    // for gperf gmp or gcp,
    // should never enable it when not enabled for performance issue.
#ifdef SRS_AUTO_GPERF_MP
    HeapProfilerStart("gperf.srs.gmp");
#endif
#ifdef SRS_AUTO_GPERF_CP
    ProfilerStart("gperf.srs.gcp");
#endif

    // directly compile error when these two macro defines.
#if defined(SRS_AUTO_GPERF_MC) && defined(SRS_AUTO_GPERF_MP)
    #error ("option --with-gmc confict with --with-gmp, "
        "@see: http://google-perftools.googlecode.com/svn/trunk/doc/heap_checker.html\n"
        "Note that since the heap-checker uses the heap-profiling framework internally, "
        "it is not possible to run both the heap-checker and heap profiler at the same time");
#endif

    // never use gmp to check memory leak.
#ifdef SRS_AUTO_GPERF_MP
    #warning "gmp is not used for memory leak, please use gmc instead."
#endif

    // never use srs log(srs_trace, srs_error, etc) before config parse the option,
    // which will load the log config and apply it.
    if ((ret = _srs_config->parse_options(argc, argv)) != ERROR_SUCCESS) {
        return ret;
    }

    // change the work dir and set cwd.
    string cwd = _srs_config->get_work_dir();
    if (!cwd.empty() && cwd != "./" && (ret = chdir(cwd.c_str())) != ERROR_SUCCESS) {
        srs_error("change cwd to %s failed. ret=%d", cwd.c_str(), ret);
        return ret;
    }
    if ((ret = _srs_config->initialize_cwd()) != ERROR_SUCCESS) {
        return ret;
    }

    // config parsed, initialize log.
    if ((ret = _srs_log->initialize()) != ERROR_SUCCESS) {
        return ret;
    }

    // config already applied to log.
    srs_trace(RTMP_SIG_SRS_SERVER", stable is "RTMP_SIG_SRS_PRIMARY);
    srs_trace("license: "RTMP_SIG_SRS_LICENSE", "RTMP_SIG_SRS_COPYRIGHT);
    srs_trace("authors: "RTMP_SIG_SRS_AUTHROS);
    srs_trace("contributors: "SRS_AUTO_CONSTRIBUTORS);
    srs_trace("build: %s, configure:%s, uname: %s", SRS_AUTO_BUILD_DATE, SRS_AUTO_USER_CONFIGURE, SRS_AUTO_UNAME);
    srs_trace("configure detail: "SRS_AUTO_CONFIGURE);
#ifdef SRS_AUTO_EMBEDED_TOOL_CHAIN
    srs_trace("crossbuild tool chain: "SRS_AUTO_EMBEDED_TOOL_CHAIN);
#endif
    srs_trace("cwd=%s, work_dir=%s", _srs_config->cwd().c_str(), cwd.c_str());

#ifdef SRS_PERF_GLIBC_MEMORY_CHECK
    // ensure glibc write error to stderr.
    setenv("LIBC_FATAL_STDERR_", "1", 1);
    // ensure glibc to do alloc check.
    setenv("MALLOC_CHECK_", "1", 1);
    srs_trace("env MALLOC_CHECK_=1 LIBC_FATAL_STDERR_=1");
#endif

#ifdef SRS_AUTO_GPERF_MD
    char* TCMALLOC_PAGE_FENCE = getenv("TCMALLOC_PAGE_FENCE");
    if (!TCMALLOC_PAGE_FENCE || strcmp(TCMALLOC_PAGE_FENCE, "1")) {
        srs_trace("gmd enabled without env TCMALLOC_PAGE_FENCE=1");
    } else {
        srs_trace("env TCMALLOC_PAGE_FENCE=1");
    }
#endif

    // we check the config when the log initialized.
    if ((ret = _srs_config->check_config()) != ERROR_SUCCESS) {
        return ret;
    }

    // features
    show_macro_features();

    SrsServer* svr = new SrsServer();
    SrsAutoFree(SrsServer, svr);

    /**
    * we do nothing in the constructor of server,
    * and use initialize to create members, set hooks for instance the reload handler,
    * all initialize will done in this stage.
    */
    if ((ret = svr->initialize(NULL)) != ERROR_SUCCESS) {
        return ret;
    }

    return run(svr);
}

int run(SrsServer* svr)
{
    // if not deamon, directly run master.
    if (!_srs_config->get_deamon()) {
        return run_master(svr);
    }

    srs_trace("start deamon mode...");

    int pid = fork();

    if(pid < 0) {
        srs_error("create process error. ret=-1"); //ret=0
        return -1;
    }

    // grandpa
    if(pid > 0) {
        int status = 0;
        if(waitpid(pid, &status, 0) == -1) {
            srs_error("wait child process error! ret=-1"); //ret=0
        }
        srs_trace("grandpa process exit.");
        exit(0);
    }

    // father
    pid = fork();

    if(pid < 0) {
        srs_error("create process error. ret=0");
        return -1;
    }

    if(pid > 0) {
        srs_trace("father process exit. ret=0");
        exit(0);
    }

    // son
    srs_trace("son(deamon) process running.");

    return run_master(svr);
}

int run_master(SrsServer* svr)
{
    int ret = ERROR_SUCCESS;

    if ((ret = svr->initialize_st()) != ERROR_SUCCESS) {
        return ret;
    }

    if ((ret = svr->initialize_signal()) != ERROR_SUCCESS) {
        return ret;
    }

    if ((ret = svr->acquire_pid_file()) != ERROR_SUCCESS) {
        return ret;
    }

    if ((ret = svr->listen()) != ERROR_SUCCESS) {
        return ret;
    }

    if ((ret = svr->register_signal()) != ERROR_SUCCESS) {
        return ret;
    }

    if ((ret = svr->http_handle()) != ERROR_SUCCESS) {
        return ret;
    }

    if ((ret = svr->ingest()) != ERROR_SUCCESS) {
        return ret;
    }

    if ((ret = svr->cycle()) != ERROR_SUCCESS) {
        return ret;
    }

    return 0;
}

<|endoftext|>


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

#include "ui/app_list/views/contents_view.h"

#include <algorithm>

#include "base/logging.h"
#include "ui/app_list/app_list_constants.h"
#include "ui/app_list/app_list_view_delegate.h"
#include "ui/app_list/pagination_model.h"
#include "ui/app_list/views/app_list_main_view.h"
#include "ui/app_list/views/apps_container_view.h"
#include "ui/app_list/views/apps_grid_view.h"
#include "ui/app_list/views/search_result_list_view.h"
#include "ui/events/event.h"
#include "ui/views/animation/bounds_animator.h"
#include "ui/views/view_model.h"
#include "ui/views/view_model_utils.h"

namespace app_list {

namespace {

// Indexes of interesting views in ViewModel of ContentsView.
const int kIndexAppsContainer = 0;
const int kIndexSearchResults = 1;

const int kMinMouseWheelToSwitchPage = 20;
const int kMinScrollToSwitchPage = 20;
const int kMinHorizVelocityToSwitchPage = 800;

const double kFinishTransitionThreshold = 0.33;

AppsContainerView* GetAppsContainerView(views::ViewModel* model) {
  return static_cast<AppsContainerView*>(model->view_at(kIndexAppsContainer));
}

SearchResultListView* GetSearchResultListView(views::ViewModel* model) {
  return static_cast<SearchResultListView*>(
      model->view_at(kIndexSearchResults));
}

}  // namespace

ContentsView::ContentsView(AppListMainView* app_list_main_view,
                           PaginationModel* pagination_model,
                           AppListModel* model,
                           AppListViewDelegate* view_delegate)
    : show_state_(SHOW_APPS),
      pagination_model_(pagination_model),
      view_model_(new views::ViewModel),
      bounds_animator_(new views::BoundsAnimator(this)) {
  DCHECK(model);
  pagination_model_->SetTransitionDurations(
      kPageTransitionDurationInMs,
      kOverscrollPageTransitionDurationMs);

  content::WebContents* start_page_contents =
      view_delegate ? view_delegate->GetStartPageContents() : NULL;
  apps_container_view_ = new AppsContainerView(
      app_list_main_view, pagination_model, model, start_page_contents);
  AddChildView(apps_container_view_);
  view_model_->Add(apps_container_view_, kIndexAppsContainer);

  SearchResultListView* search_results_view = new SearchResultListView(
      app_list_main_view, view_delegate);
  AddChildView(search_results_view);
  view_model_->Add(search_results_view, kIndexSearchResults);

  GetSearchResultListView(view_model_.get())->SetResults(model->results());
}

ContentsView::~ContentsView() {
}

void ContentsView::CancelDrag() {
  if (apps_container_view_->apps_grid_view()->has_dragged_view())
    apps_container_view_->apps_grid_view()->EndDrag(true);
}

void ContentsView::SetDragAndDropHostOfCurrentAppList(
    ApplicationDragAndDropHost* drag_and_drop_host) {
  apps_container_view_->SetDragAndDropHostOfCurrentAppList(drag_and_drop_host);
}

void ContentsView::SetShowState(ShowState show_state) {
  if (show_state_ == show_state)
    return;

  show_state_ = show_state;
  ShowStateChanged();
}

void ContentsView::ShowStateChanged() {
  SearchResultListView* results_view =
      GetSearchResultListView(view_model_.get());
  // TODO(xiyuan): Highlight default match instead of the first.
  if (show_state_ == SHOW_SEARCH_RESULTS && results_view->visible())
    results_view->SetSelectedIndex(0);
  results_view->UpdateAutoLaunchState();

  AnimateToIdealBounds();
}

void ContentsView::CalculateIdealBounds() {
  gfx::Rect rect(GetContentsBounds());
  if (rect.IsEmpty())
    return;

  gfx::Rect container_frame(rect);
  gfx::Rect results_frame(rect);

  // Offsets apps grid and result list based on |show_state_|.
  // SearchResultListView is on top of apps grid. Visible view is left in
  // visible area and invisible ones is put out of the visible area.
  int contents_area_height = rect.height();
  switch (show_state_) {
    case SHOW_APPS:
      results_frame.Offset(0, -contents_area_height);
      break;
    case SHOW_SEARCH_RESULTS:
      container_frame.Offset(0, contents_area_height);
      break;
    default:
      NOTREACHED() << "Unknown show_state_ " << show_state_;
      break;
  }

  view_model_->set_ideal_bounds(kIndexAppsContainer, container_frame);
  view_model_->set_ideal_bounds(kIndexSearchResults, results_frame);
}

void ContentsView::AnimateToIdealBounds() {
  CalculateIdealBounds();
  for (int i = 0; i < view_model_->view_size(); ++i) {
    bounds_animator_->AnimateViewTo(view_model_->view_at(i),
                                    view_model_->ideal_bounds(i));
  }
}

void ContentsView::ShowSearchResults(bool show) {
  SetShowState(show ? SHOW_SEARCH_RESULTS : SHOW_APPS);
}

void ContentsView::ShowFolderContent(AppListFolderItem* item) {
  apps_container_view_->ShowActiveFolder(item);
}

void ContentsView::Prerender() {
  const int selected_page = std::max(0, pagination_model_->selected_page());
  apps_container_view_->apps_grid_view()->Prerender(selected_page);
}

gfx::Size ContentsView::GetPreferredSize() {
  const gfx::Size container_size = GetAppsContainerView(view_model_.get())->
      apps_grid_view()->GetPreferredSize();
  const gfx::Size results_size =
      GetSearchResultListView(view_model_.get())->GetPreferredSize();

  int width = std::max(container_size.width(), results_size.width());
  int height = std::max(container_size.height(), results_size.height());
  return gfx::Size(width, height);
}

void ContentsView::Layout() {
  CalculateIdealBounds();
  views::ViewModelUtils::SetViewBoundsToIdealBounds(*view_model_);
}

bool ContentsView::OnKeyPressed(const ui::KeyEvent& event) {
  switch (show_state_) {
    case SHOW_APPS:
      return GetAppsContainerView(view_model_.get())->OnKeyPressed(event);
    case SHOW_SEARCH_RESULTS:
      return GetSearchResultListView(view_model_.get())->OnKeyPressed(event);
    default:
      NOTREACHED() << "Unknown show state " << show_state_;
  }
  return false;
}

bool ContentsView::OnMouseWheel(const ui::MouseWheelEvent& event) {
  if (show_state_ != SHOW_APPS)
    return false;

  int offset;
  if (abs(event.x_offset()) > abs(event.y_offset()))
    offset = event.x_offset();
  else
    offset = event.y_offset();

  if (abs(offset) > kMinMouseWheelToSwitchPage) {
    if (!pagination_model_->has_transition()) {
      pagination_model_->SelectPageRelative(
          offset > 0 ? -1 : 1, true);
    }
    return true;
  }

  return false;
}

void ContentsView::OnGestureEvent(ui::GestureEvent* event) {
  if (show_state_ != SHOW_APPS)
    return;

  switch (event->type()) {
    case ui::ET_GESTURE_SCROLL_BEGIN:
      pagination_model_->StartScroll();
      event->SetHandled();
      return;
    case ui::ET_GESTURE_SCROLL_UPDATE:
      // event->details.scroll_x() > 0 means moving contents to right. That is,
      // transitioning to previous page.
      pagination_model_->UpdateScroll(
          event->details().scroll_x() / GetContentsBounds().width());
      event->SetHandled();
      return;
    case ui::ET_GESTURE_SCROLL_END:
      pagination_model_->EndScroll(pagination_model_->
          transition().progress < kFinishTransitionThreshold);
      event->SetHandled();
      return;
    case ui::ET_SCROLL_FLING_START: {
      pagination_model_->EndScroll(true);
      if (fabs(event->details().velocity_x()) > kMinHorizVelocityToSwitchPage) {
        pagination_model_->SelectPageRelative(
            event->details().velocity_x() < 0 ? 1 : -1,
            true);
      }
      event->SetHandled();
      return;
    }
    default:
      break;
  }
}

void ContentsView::OnScrollEvent(ui::ScrollEvent* event) {
  if (show_state_ != SHOW_APPS ||
      event->type() == ui::ET_SCROLL_FLING_CANCEL) {
    return;
  }

  float offset;
  if (abs(event->x_offset()) > abs(event->y_offset()))
    offset = event->x_offset();
  else
    offset = event->y_offset();

  if (abs(offset) > kMinScrollToSwitchPage) {
    if (!pagination_model_->has_transition()) {
      pagination_model_->SelectPageRelative(offset > 0 ? -1 : 1,
                                            true);
    }
    event->SetHandled();
    event->StopPropagation();
  }
}

}  // namespace app_list
<commit_msg>Change content view switching animation for experimental app launcher.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/app_list/views/contents_view.h"

#include <algorithm>

#include "base/logging.h"
#include "ui/app_list/app_list_constants.h"
#include "ui/app_list/app_list_switches.h"
#include "ui/app_list/app_list_view_delegate.h"
#include "ui/app_list/pagination_model.h"
#include "ui/app_list/views/app_list_main_view.h"
#include "ui/app_list/views/apps_container_view.h"
#include "ui/app_list/views/apps_grid_view.h"
#include "ui/app_list/views/search_result_list_view.h"
#include "ui/events/event.h"
#include "ui/views/animation/bounds_animator.h"
#include "ui/views/view_model.h"
#include "ui/views/view_model_utils.h"

namespace app_list {

namespace {

// Indexes of interesting views in ViewModel of ContentsView.
const int kIndexAppsContainer = 0;
const int kIndexSearchResults = 1;

const int kMinMouseWheelToSwitchPage = 20;
const int kMinScrollToSwitchPage = 20;
const int kMinHorizVelocityToSwitchPage = 800;

const double kFinishTransitionThreshold = 0.33;

AppsContainerView* GetAppsContainerView(views::ViewModel* model) {
  return static_cast<AppsContainerView*>(model->view_at(kIndexAppsContainer));
}

SearchResultListView* GetSearchResultListView(views::ViewModel* model) {
  return static_cast<SearchResultListView*>(
      model->view_at(kIndexSearchResults));
}

}  // namespace

ContentsView::ContentsView(AppListMainView* app_list_main_view,
                           PaginationModel* pagination_model,
                           AppListModel* model,
                           AppListViewDelegate* view_delegate)
    : show_state_(SHOW_APPS),
      pagination_model_(pagination_model),
      view_model_(new views::ViewModel),
      bounds_animator_(new views::BoundsAnimator(this)) {
  DCHECK(model);
  pagination_model_->SetTransitionDurations(
      kPageTransitionDurationInMs,
      kOverscrollPageTransitionDurationMs);

  content::WebContents* start_page_contents =
      view_delegate ? view_delegate->GetStartPageContents() : NULL;
  apps_container_view_ = new AppsContainerView(
      app_list_main_view, pagination_model, model, start_page_contents);
  AddChildView(apps_container_view_);
  view_model_->Add(apps_container_view_, kIndexAppsContainer);

  SearchResultListView* search_results_view = new SearchResultListView(
      app_list_main_view, view_delegate);
  AddChildView(search_results_view);
  view_model_->Add(search_results_view, kIndexSearchResults);

  GetSearchResultListView(view_model_.get())->SetResults(model->results());
}

ContentsView::~ContentsView() {
}

void ContentsView::CancelDrag() {
  if (apps_container_view_->apps_grid_view()->has_dragged_view())
    apps_container_view_->apps_grid_view()->EndDrag(true);
}

void ContentsView::SetDragAndDropHostOfCurrentAppList(
    ApplicationDragAndDropHost* drag_and_drop_host) {
  apps_container_view_->SetDragAndDropHostOfCurrentAppList(drag_and_drop_host);
}

void ContentsView::SetShowState(ShowState show_state) {
  if (show_state_ == show_state)
    return;

  show_state_ = show_state;
  ShowStateChanged();
}

void ContentsView::ShowStateChanged() {
  SearchResultListView* results_view =
      GetSearchResultListView(view_model_.get());
  // TODO(xiyuan): Highlight default match instead of the first.
  if (show_state_ == SHOW_SEARCH_RESULTS && results_view->visible())
    results_view->SetSelectedIndex(0);
  results_view->UpdateAutoLaunchState();

  AnimateToIdealBounds();
}

void ContentsView::CalculateIdealBounds() {
  gfx::Rect rect(GetContentsBounds());
  if (rect.IsEmpty())
    return;

  if (app_list::switches::IsExperimentalAppListEnabled()) {
    int incoming_view_index = 0;
    switch (show_state_) {
      case SHOW_APPS:
        incoming_view_index = kIndexAppsContainer;
        break;
      case SHOW_SEARCH_RESULTS:
        incoming_view_index = kIndexSearchResults;
        break;
      default:
        NOTREACHED();
    }

    gfx::Rect incoming_target(rect);
    gfx::Rect outgoing_target(rect);
    outgoing_target.set_y(-outgoing_target.height());

    for (int i = 0; i < view_model_->view_size(); ++i) {
      view_model_->set_ideal_bounds(i,
                                    i == incoming_view_index ? incoming_target
                                                             : outgoing_target);
    }
    return;
  }

  gfx::Rect container_frame(rect);
  gfx::Rect results_frame(rect);

  // Offsets apps grid and result list based on |show_state_|.
  // SearchResultListView is on top of apps grid. Visible view is left in
  // visible area and invisible ones is put out of the visible area.
  int contents_area_height = rect.height();
  switch (show_state_) {
    case SHOW_APPS:
      results_frame.Offset(0, -contents_area_height);
      break;
    case SHOW_SEARCH_RESULTS:
      container_frame.Offset(0, contents_area_height);
      break;
    default:
      NOTREACHED() << "Unknown show_state_ " << show_state_;
      break;
  }

  view_model_->set_ideal_bounds(kIndexAppsContainer, container_frame);
  view_model_->set_ideal_bounds(kIndexSearchResults, results_frame);
}

void ContentsView::AnimateToIdealBounds() {
  CalculateIdealBounds();
  for (int i = 0; i < view_model_->view_size(); ++i) {
    bounds_animator_->AnimateViewTo(view_model_->view_at(i),
                                    view_model_->ideal_bounds(i));
  }
}

void ContentsView::ShowSearchResults(bool show) {
  SetShowState(show ? SHOW_SEARCH_RESULTS : SHOW_APPS);
}

void ContentsView::ShowFolderContent(AppListFolderItem* item) {
  apps_container_view_->ShowActiveFolder(item);
}

void ContentsView::Prerender() {
  const int selected_page = std::max(0, pagination_model_->selected_page());
  apps_container_view_->apps_grid_view()->Prerender(selected_page);
}

gfx::Size ContentsView::GetPreferredSize() {
  const gfx::Size container_size = GetAppsContainerView(view_model_.get())->
      apps_grid_view()->GetPreferredSize();
  const gfx::Size results_size =
      GetSearchResultListView(view_model_.get())->GetPreferredSize();

  int width = std::max(container_size.width(), results_size.width());
  int height = std::max(container_size.height(), results_size.height());
  return gfx::Size(width, height);
}

void ContentsView::Layout() {
  CalculateIdealBounds();
  views::ViewModelUtils::SetViewBoundsToIdealBounds(*view_model_);
}

bool ContentsView::OnKeyPressed(const ui::KeyEvent& event) {
  switch (show_state_) {
    case SHOW_APPS:
      return GetAppsContainerView(view_model_.get())->OnKeyPressed(event);
    case SHOW_SEARCH_RESULTS:
      return GetSearchResultListView(view_model_.get())->OnKeyPressed(event);
    default:
      NOTREACHED() << "Unknown show state " << show_state_;
  }
  return false;
}

bool ContentsView::OnMouseWheel(const ui::MouseWheelEvent& event) {
  if (show_state_ != SHOW_APPS)
    return false;

  int offset;
  if (abs(event.x_offset()) > abs(event.y_offset()))
    offset = event.x_offset();
  else
    offset = event.y_offset();

  if (abs(offset) > kMinMouseWheelToSwitchPage) {
    if (!pagination_model_->has_transition()) {
      pagination_model_->SelectPageRelative(
          offset > 0 ? -1 : 1, true);
    }
    return true;
  }

  return false;
}

void ContentsView::OnGestureEvent(ui::GestureEvent* event) {
  if (show_state_ != SHOW_APPS)
    return;

  switch (event->type()) {
    case ui::ET_GESTURE_SCROLL_BEGIN:
      pagination_model_->StartScroll();
      event->SetHandled();
      return;
    case ui::ET_GESTURE_SCROLL_UPDATE:
      // event->details.scroll_x() > 0 means moving contents to right. That is,
      // transitioning to previous page.
      pagination_model_->UpdateScroll(
          event->details().scroll_x() / GetContentsBounds().width());
      event->SetHandled();
      return;
    case ui::ET_GESTURE_SCROLL_END:
      pagination_model_->EndScroll(pagination_model_->
          transition().progress < kFinishTransitionThreshold);
      event->SetHandled();
      return;
    case ui::ET_SCROLL_FLING_START: {
      pagination_model_->EndScroll(true);
      if (fabs(event->details().velocity_x()) > kMinHorizVelocityToSwitchPage) {
        pagination_model_->SelectPageRelative(
            event->details().velocity_x() < 0 ? 1 : -1,
            true);
      }
      event->SetHandled();
      return;
    }
    default:
      break;
  }
}

void ContentsView::OnScrollEvent(ui::ScrollEvent* event) {
  if (show_state_ != SHOW_APPS ||
      event->type() == ui::ET_SCROLL_FLING_CANCEL) {
    return;
  }

  float offset;
  if (abs(event->x_offset()) > abs(event->y_offset()))
    offset = event->x_offset();
  else
    offset = event->y_offset();

  if (abs(offset) > kMinScrollToSwitchPage) {
    if (!pagination_model_->has_transition()) {
      pagination_model_->SelectPageRelative(offset > 0 ? -1 : 1,
                                            true);
    }
    event->SetHandled();
    event->StopPropagation();
  }
}

}  // namespace app_list
<|endoftext|>


<commit_before>/*
    Copyright (C) 2001 by Jorrit Tyberghein

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "demo.h"
#include "demoseq.h"
#include "demoop.h"
#include "ivideo/graph3d.h"
#include "ivideo/txtmgr.h"
#include "ivaria/conout.h"
#include "iengine/engine.h"
#include "iengine/sector.h"
#include "iengine/polygon.h"
#include "iengine/thing.h"
#include "iengine/light.h"
#include "iengine/view.h"
#include "iengine/camera.h"
#include "iengine/mesh.h"
#include "iengine/movable.h"
#include "imesh/object.h"
#include "csutil/cscolor.h"
#include "csgeom/path.h"
#include "csfx/csfxscr.h"

//-----------------------------------------------------------------------------

void FadeOp::Do (cs_time dt)
{
  DemoSequenceManager::demoseq->SetupFade (start_fade,
  	end_fade, total_fade_time, dt);
}

RotatePartOp::RotatePartOp (const char* meshName, cs_time total,
	float aspeed) : total_rotate_time (total), angle_speed (aspeed)
{
  mesh = DemoSequenceManager::demo->engine->FindMeshObject (meshName);
  if (!mesh)
  {
    DemoSequenceManager::demo->Printf (MSG_FATAL_ERROR,
    	"Can't find mesh '%s'\n", meshName);
    exit (0);
  }
}

void RotatePartOp::Do (cs_time dt)
{
  DemoSequenceManager::demoseq->SetupRotatePart (mesh, angle_speed,
  	total_rotate_time, dt);
}

AttachOp::AttachOp (const char* meshName, const char* pathName)
{
  if (meshName)
  {
    mesh = DemoSequenceManager::demo->engine->FindMeshObject (meshName);
    if (!mesh)
    {
      DemoSequenceManager::demo->Printf (MSG_FATAL_ERROR,
    	  "Can't find mesh '%s'\n", meshName);
      exit (0);
    }
  }
  else
    mesh = NULL;
  path = DemoSequenceManager::demoseq->FindPath (pathName);
  if (!path)
  {
    DemoSequenceManager::demo->Printf (MSG_FATAL_ERROR,
    	"Can't find path '%s'\n", pathName);
    exit (0);
  }
}

void AttachOp::Do (cs_time /*dt*/)
{
  DemoSequenceManager::demoseq->ReplacePathObject (path, mesh);
}

PathOp::PathOp (cs_time t, const char* meshName, const char* pathName)
{
  total_path_time = t;
  if (meshName)
  {
    mesh = DemoSequenceManager::demo->engine->FindMeshObject (meshName);
    if (!mesh)
    {
      DemoSequenceManager::demo->Printf (MSG_FATAL_ERROR,
    	  "Can't find mesh '%s'\n", meshName);
      exit (0);
    }
  }
  else
    mesh = NULL;
  path = DemoSequenceManager::demoseq->FindPath (pathName);
  if (!path)
  {
    DemoSequenceManager::demo->Printf (MSG_FATAL_ERROR,
    	"Can't find path '%s'\n", pathName);
    exit (0);
  }
}

void PathOp::Do (cs_time dt)
{
  DemoSequenceManager::demoseq->SetupPath (path, mesh,
  	total_path_time, dt);
}

SetupMeshOp::SetupMeshOp (const char* meshName, const char* sectName,
	const csVector3& p)
{
  pos = p;
  mesh = DemoSequenceManager::demo->engine->FindMeshObject (meshName);
  if (!mesh)
  {
    DemoSequenceManager::demo->Printf (MSG_FATAL_ERROR,
    	"Can't find mesh '%s'\n", meshName);
    exit (0);
  }
  sector = DemoSequenceManager::demo->engine->FindSector (sectName);
  if (!sector)
  {
    DemoSequenceManager::demo->Printf (MSG_FATAL_ERROR,
    	"Can't find sector '%s'\n", sectName);
    exit (0);
  }
}

void SetupMeshOp::Do (cs_time /*dt*/)
{
  if (mesh)
  {
    iMovable* movable = mesh->GetMovable ();
    movable->SetSector (sector);
    movable->SetPosition (pos);
    movable->UpdateMove ();
    mesh->DeferUpdateLighting (CS_NLIGHT_STATIC|CS_NLIGHT_DYNAMIC, 10);
  }
}

ShowMeshOp::ShowMeshOp (const char* meshName)
{
  mesh = DemoSequenceManager::demo->engine->FindMeshObject (meshName);
  if (!mesh)
  {
    DemoSequenceManager::demo->Printf (MSG_FATAL_ERROR,
    	"Can't find mesh '%s'\n", meshName);
    exit (0);
  }
}

void ShowMeshOp::Do (cs_time /*dt*/)
{
  if (mesh)
  {
    mesh->GetFlags ().Reset (CS_ENTITY_INVISIBLE);
    mesh->DeferUpdateLighting (CS_NLIGHT_STATIC|CS_NLIGHT_DYNAMIC, 10);
  }
}

HideMeshOp::HideMeshOp (const char* meshName)
{
  mesh = DemoSequenceManager::demo->engine->FindMeshObject (meshName);
  if (!mesh)
  {
    DemoSequenceManager::demo->Printf (MSG_FATAL_ERROR,
    	"Can't find mesh '%s'\n", meshName);
    exit (0);
  }
}

void HideMeshOp::Do (cs_time /*dt*/)
{
  if (mesh)
  {
    mesh->GetFlags ().Set (CS_ENTITY_INVISIBLE);
  }
}

void TestOp::Do (cs_time dt)
{
  printf ("dt=%ld fps=%g\n", dt,
  	(long)DemoSequenceManager::demoseq->GetFPS ()); fflush (stdout);
}

//-----------------------------------------------------------------------------

<commit_msg>Oops.<commit_after>/*
    Copyright (C) 2001 by Jorrit Tyberghein

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "demo.h"
#include "demoseq.h"
#include "demoop.h"
#include "ivideo/graph3d.h"
#include "ivideo/txtmgr.h"
#include "ivaria/conout.h"
#include "iengine/engine.h"
#include "iengine/sector.h"
#include "iengine/polygon.h"
#include "iengine/thing.h"
#include "iengine/light.h"
#include "iengine/view.h"
#include "iengine/camera.h"
#include "iengine/mesh.h"
#include "iengine/movable.h"
#include "imesh/object.h"
#include "csutil/cscolor.h"
#include "csgeom/path.h"
#include "csfx/csfxscr.h"

//-----------------------------------------------------------------------------

void FadeOp::Do (cs_time dt)
{
  DemoSequenceManager::demoseq->SetupFade (start_fade,
  	end_fade, total_fade_time, dt);
}

RotatePartOp::RotatePartOp (const char* meshName, cs_time total,
	float aspeed) : total_rotate_time (total), angle_speed (aspeed)
{
  mesh = DemoSequenceManager::demo->engine->FindMeshObject (meshName);
  if (!mesh)
  {
    DemoSequenceManager::demo->Printf (MSG_FATAL_ERROR,
    	"Can't find mesh '%s'\n", meshName);
    exit (0);
  }
}

void RotatePartOp::Do (cs_time dt)
{
  DemoSequenceManager::demoseq->SetupRotatePart (mesh, angle_speed,
  	total_rotate_time, dt);
}

AttachOp::AttachOp (const char* meshName, const char* pathName)
{
  if (meshName)
  {
    mesh = DemoSequenceManager::demo->engine->FindMeshObject (meshName);
    if (!mesh)
    {
      DemoSequenceManager::demo->Printf (MSG_FATAL_ERROR,
    	  "Can't find mesh '%s'\n", meshName);
      exit (0);
    }
  }
  else
    mesh = NULL;
  path = DemoSequenceManager::demoseq->FindPath (pathName);
  if (!path)
  {
    DemoSequenceManager::demo->Printf (MSG_FATAL_ERROR,
    	"Can't find path '%s'\n", pathName);
    exit (0);
  }
}

void AttachOp::Do (cs_time /*dt*/)
{
  DemoSequenceManager::demoseq->ReplacePathObject (path, mesh);
}

PathOp::PathOp (cs_time t, const char* meshName, const char* pathName)
{
  total_path_time = t;
  if (meshName)
  {
    mesh = DemoSequenceManager::demo->engine->FindMeshObject (meshName);
    if (!mesh)
    {
      DemoSequenceManager::demo->Printf (MSG_FATAL_ERROR,
    	  "Can't find mesh '%s'\n", meshName);
      exit (0);
    }
  }
  else
    mesh = NULL;
  path = DemoSequenceManager::demoseq->FindPath (pathName);
  if (!path)
  {
    DemoSequenceManager::demo->Printf (MSG_FATAL_ERROR,
    	"Can't find path '%s'\n", pathName);
    exit (0);
  }
}

void PathOp::Do (cs_time dt)
{
  DemoSequenceManager::demoseq->SetupPath (path, mesh,
  	total_path_time, dt);
}

SetupMeshOp::SetupMeshOp (const char* meshName, const char* sectName,
	const csVector3& p)
{
  pos = p;
  mesh = DemoSequenceManager::demo->engine->FindMeshObject (meshName);
  if (!mesh)
  {
    DemoSequenceManager::demo->Printf (MSG_FATAL_ERROR,
    	"Can't find mesh '%s'\n", meshName);
    exit (0);
  }
  sector = DemoSequenceManager::demo->engine->FindSector (sectName);
  if (!sector)
  {
    DemoSequenceManager::demo->Printf (MSG_FATAL_ERROR,
    	"Can't find sector '%s'\n", sectName);
    exit (0);
  }
}

void SetupMeshOp::Do (cs_time /*dt*/)
{
  if (mesh)
  {
    iMovable* movable = mesh->GetMovable ();
    movable->SetSector (sector);
    movable->SetPosition (pos);
    movable->UpdateMove ();
    mesh->DeferUpdateLighting (CS_NLIGHT_STATIC|CS_NLIGHT_DYNAMIC, 10);
  }
}

ShowMeshOp::ShowMeshOp (const char* meshName)
{
  mesh = DemoSequenceManager::demo->engine->FindMeshObject (meshName);
  if (!mesh)
  {
    DemoSequenceManager::demo->Printf (MSG_FATAL_ERROR,
    	"Can't find mesh '%s'\n", meshName);
    exit (0);
  }
}

void ShowMeshOp::Do (cs_time /*dt*/)
{
  if (mesh)
  {
    mesh->GetFlags ().Reset (CS_ENTITY_INVISIBLE);
    mesh->DeferUpdateLighting (CS_NLIGHT_STATIC|CS_NLIGHT_DYNAMIC, 10);
  }
}

HideMeshOp::HideMeshOp (const char* meshName)
{
  mesh = DemoSequenceManager::demo->engine->FindMeshObject (meshName);
  if (!mesh)
  {
    DemoSequenceManager::demo->Printf (MSG_FATAL_ERROR,
    	"Can't find mesh '%s'\n", meshName);
    exit (0);
  }
}

void HideMeshOp::Do (cs_time /*dt*/)
{
  if (mesh)
  {
    mesh->GetFlags ().Set (CS_ENTITY_INVISIBLE);
  }
}

void TestOp::Do (cs_time dt)
{
  printf ("dt=%ld fps=%g\n", (long)dt,
  	DemoSequenceManager::demoseq->GetFPS ()); fflush (stdout);
}

//-----------------------------------------------------------------------------

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2010 Bolloré telecom
 *
 * Author:
 *	Jeremy Lainé
 *
 * Source:
 *	http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * 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.
 *
 */

#include <QTcpServer>
#include <QTcpSocket>

#include "QXmppSocks.h"

const static char SocksVersion = 5;

enum AuthenticationMethod {
    NoAuthentication = 0,
    GSSAPI = 1,
    UsernamePassword = 2,
};

enum Command {
    ConnectCommand = 1,
    BindCommand = 2,
    AssociateCommand = 3,
};

enum AddressType {
    IPv4Address = 1,
    DomainName = 3,
    IPv6Address = 4,
};

enum ReplyType {
    Succeeded = 0,
    SocksFailure = 1,
    ConnectionNotAllowed = 2,
    NetworkUnreachable = 3,
    HostUnreachable = 4,
    ConnectionRefused = 5,
    TtlExpired = 6,
    CommandNotSupported = 7,
    AddressTypeNotSupported = 8,
};

QByteArray encodeHostAndPort(quint8 type, const QByteArray &host, quint16 port)
{
    QByteArray buffer;
    buffer.resize(2);
    // set host name
    buffer[0] = type;
    buffer[1] = host.size();
    buffer.append(host);
    // set port
    int pos = buffer.size();
    buffer.resize(pos + 2);
    quint16 p = htons(port);
    memcpy(buffer.data() + pos, &p, 2);
    return buffer;
}

bool parseHostAndPort(const QByteArray buffer, quint8 &type, QByteArray &host, quint16 &port)
{
    if (buffer.size() < 4)
        return false;

    // parse host type
    int pos = 0;
    type = buffer.at(pos);
    pos++;

    // parse host name
    quint8 hostLength = buffer.at(pos);
    pos++;
    if (buffer.size() < hostLength + 4)
    {
        qWarning("Invalid host length");
        return false;
    }
    host = buffer.mid(pos, hostLength);
    pos += hostLength;

    // parse host port
    quint16 p;
    memcpy(&p, buffer.data() + pos, 2);
    port = ntohs(p);
    return true;
}

QXmppSocksClient::QXmppSocksClient(const QHostAddress &proxyAddress, quint16 proxyPort, QObject *parent)
    : QObject(parent), m_proxyAddress(proxyAddress), m_proxyPort(proxyPort)
{
    m_socket = new QTcpSocket(this);
}

void QXmppSocksClient::connectToHost(const QString &hostName, quint16 hostPort)
{
    m_hostName = hostName;
    m_hostPort = hostPort;
    m_socket->connectToHost(m_proxyAddress, m_proxyPort);
}

QString QXmppSocksClient::errorString() const
{
    return m_socket->errorString();
}

QByteArray QXmppSocksClient::readAll()
{
    return m_socket->readAll();
}

bool QXmppSocksClient::waitForConnected(int msecs)
{
    if (!m_socket->waitForConnected(msecs))
        return false;

    // send connect to server
    QByteArray buffer;
    buffer.resize(3);
    buffer[0] = SocksVersion;
    buffer[1] = 0x01; // number of methods
    buffer[2] = NoAuthentication;
    m_socket->write(buffer);

    // wait for connect to server response
    if (!m_socket->waitForReadyRead(msecs))
        return false;
    buffer = m_socket->readAll();
    if (buffer.size() != 2 || buffer.at(0) != SocksVersion || buffer.at(1) != NoAuthentication)
    {
        qWarning("QXmppSocksClient received an invalid response during handshake");
        return false;
    }

    // send CONNECT command
    buffer.resize(3);
    buffer[0] = SocksVersion;
    buffer[1] = ConnectCommand;
    buffer[2] = 0x00; // reserved
    buffer.append(encodeHostAndPort(
        DomainName,
        m_hostName.toAscii(),
        m_hostPort));
    m_socket->write(buffer);

    // wait for CONNECT response
    if (!m_socket->waitForReadyRead(msecs))
        return false;
    buffer = m_socket->readAll();
    if (buffer.size() < 6 ||
        buffer.at(0) != SocksVersion ||
        buffer.at(1) != Succeeded ||
        buffer.at(2) != 0)
    {
        qWarning("QXmppSocksClient received an invalid response to CONNECT command");
        return false;
    }

    // parse host
    quint8 hostType;
    QByteArray hostName;
    quint16 hostPort;
    if (!parseHostAndPort(buffer.mid(3), hostType, hostName, hostPort))
    {
        qWarning("QXmppSocksClient could not parse type/host/port");
        return false;
    }
    // FIXME : what do we do with the resulting name / port?

    connect(m_socket, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
    connect(m_socket, SIGNAL(readyRead()), this, SIGNAL(readyRead()));
    return true;
}

QXmppSocksServer::QXmppSocksServer(QObject *parent)
    : QObject(parent),
    m_hostPort(0),
    m_socket(0)
{
    m_server = new QTcpServer(this);
    connect(m_server, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
}

bool QXmppSocksServer::listen(const QHostAddress &address, quint16 port)
{
    return m_server->listen(address, port);
}

QHostAddress QXmppSocksServer::serverAddress() const
{
    return m_server->serverAddress();
}

quint16 QXmppSocksServer::serverPort() const
{
    return m_server->serverPort();
}

void QXmppSocksServer::slotNewConnection()
{
    m_socket = m_server->nextPendingConnection();
    if (!m_socket)
        return;

    // wait for connect to server
    if (!m_socket->waitForReadyRead())
        return;
    QByteArray buffer = m_socket->readAll();
    if (buffer.size() < 3 ||
        buffer.at(0) != SocksVersion ||
        buffer.at(1) != 0x01 ||
        buffer.at(2) != NoAuthentication)
    {
        qWarning("QXmppSocksServer received invalid handshake");
        m_socket->close();
        return;
    }

    // send connect to server response
    buffer.resize(2);
    buffer[0] = SocksVersion;
    buffer[1] = NoAuthentication;
    m_socket->write(buffer);

    // wait for connect command
    if (!m_socket->waitForReadyRead())
        return;
    buffer = m_socket->readAll();
    if (buffer.size() < 4 ||
        buffer.at(0) != SocksVersion ||
        buffer.at(1) != ConnectCommand ||
        buffer.at(2) != 0x00)
    {
        qWarning("QXmppSocksServer received an invalid command");
        m_socket->close();
        return;
    }

    // parse host
    quint8 hostType;
    QByteArray hostName;
    quint16 hostPort;
    if (!parseHostAndPort(buffer.mid(3), hostType, hostName, hostPort))
    {
        qWarning("QXmppSocksServer could not parse type/host/port");
        m_socket->close();
        return;
    }
    if (hostName != m_hostName || hostPort != m_hostPort)
    {
        qWarning("QXmppSocksServer got wrong host or port");
        m_socket->close();
        return;
    }

    //send connect response
    buffer.resize(3);
    buffer[0] = SocksVersion;
    buffer[1] = Succeeded;
    buffer[2] = 0x00;
    buffer.append(encodeHostAndPort(
        DomainName,
        m_server->serverAddress().toString().toAscii(),
        m_server->serverPort()));
    m_socket->write(buffer);

    // connect signals
    connect(m_socket, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
    connect(m_socket, SIGNAL(bytesWritten(qint64)), this, SIGNAL(bytesWritten(qint64)));
}

void QXmppSocksServer::setHostName(const QString &hostName)
{
    m_hostName = hostName;
}

void QXmppSocksServer::setHostPort(quint16 hostPort)
{
    m_hostPort = hostPort;
}

void QXmppSocksServer::write(const QByteArray &data)
{
    if (m_socket)
        m_socket->write(data);
}
<commit_msg>fix build on linux/windows<commit_after>/*
 * Copyright (C) 2010 Bolloré telecom
 *
 * Author:
 *	Jeremy Lainé
 *
 * Source:
 *	http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * 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.
 *
 */

#include <QTcpServer>
#include <QTcpSocket>

#ifdef Q_OS_WIN
#include <winsock2.h>
#else
#include <arpa/inet.h>
#endif

#include "QXmppSocks.h"

const static char SocksVersion = 5;

enum AuthenticationMethod {
    NoAuthentication = 0,
    GSSAPI = 1,
    UsernamePassword = 2,
};

enum Command {
    ConnectCommand = 1,
    BindCommand = 2,
    AssociateCommand = 3,
};

enum AddressType {
    IPv4Address = 1,
    DomainName = 3,
    IPv6Address = 4,
};

enum ReplyType {
    Succeeded = 0,
    SocksFailure = 1,
    ConnectionNotAllowed = 2,
    NetworkUnreachable = 3,
    HostUnreachable = 4,
    ConnectionRefused = 5,
    TtlExpired = 6,
    CommandNotSupported = 7,
    AddressTypeNotSupported = 8,
};

QByteArray encodeHostAndPort(quint8 type, const QByteArray &host, quint16 port)
{
    QByteArray buffer;
    buffer.resize(2);
    // set host name
    buffer[0] = type;
    buffer[1] = host.size();
    buffer.append(host);
    // set port
    int pos = buffer.size();
    buffer.resize(pos + 2);
    quint16 p = htons(port);
    memcpy(buffer.data() + pos, &p, 2);
    return buffer;
}

bool parseHostAndPort(const QByteArray buffer, quint8 &type, QByteArray &host, quint16 &port)
{
    if (buffer.size() < 4)
        return false;

    // parse host type
    int pos = 0;
    type = buffer.at(pos);
    pos++;

    // parse host name
    quint8 hostLength = buffer.at(pos);
    pos++;
    if (buffer.size() < hostLength + 4)
    {
        qWarning("Invalid host length");
        return false;
    }
    host = buffer.mid(pos, hostLength);
    pos += hostLength;

    // parse host port
    quint16 p;
    memcpy(&p, buffer.data() + pos, 2);
    port = ntohs(p);
    return true;
}

QXmppSocksClient::QXmppSocksClient(const QHostAddress &proxyAddress, quint16 proxyPort, QObject *parent)
    : QObject(parent), m_proxyAddress(proxyAddress), m_proxyPort(proxyPort)
{
    m_socket = new QTcpSocket(this);
}

void QXmppSocksClient::connectToHost(const QString &hostName, quint16 hostPort)
{
    m_hostName = hostName;
    m_hostPort = hostPort;
    m_socket->connectToHost(m_proxyAddress, m_proxyPort);
}

QString QXmppSocksClient::errorString() const
{
    return m_socket->errorString();
}

QByteArray QXmppSocksClient::readAll()
{
    return m_socket->readAll();
}

bool QXmppSocksClient::waitForConnected(int msecs)
{
    if (!m_socket->waitForConnected(msecs))
        return false;

    // send connect to server
    QByteArray buffer;
    buffer.resize(3);
    buffer[0] = SocksVersion;
    buffer[1] = 0x01; // number of methods
    buffer[2] = NoAuthentication;
    m_socket->write(buffer);

    // wait for connect to server response
    if (!m_socket->waitForReadyRead(msecs))
        return false;
    buffer = m_socket->readAll();
    if (buffer.size() != 2 || buffer.at(0) != SocksVersion || buffer.at(1) != NoAuthentication)
    {
        qWarning("QXmppSocksClient received an invalid response during handshake");
        return false;
    }

    // send CONNECT command
    buffer.resize(3);
    buffer[0] = SocksVersion;
    buffer[1] = ConnectCommand;
    buffer[2] = 0x00; // reserved
    buffer.append(encodeHostAndPort(
        DomainName,
        m_hostName.toAscii(),
        m_hostPort));
    m_socket->write(buffer);

    // wait for CONNECT response
    if (!m_socket->waitForReadyRead(msecs))
        return false;
    buffer = m_socket->readAll();
    if (buffer.size() < 6 ||
        buffer.at(0) != SocksVersion ||
        buffer.at(1) != Succeeded ||
        buffer.at(2) != 0)
    {
        qWarning("QXmppSocksClient received an invalid response to CONNECT command");
        return false;
    }

    // parse host
    quint8 hostType;
    QByteArray hostName;
    quint16 hostPort;
    if (!parseHostAndPort(buffer.mid(3), hostType, hostName, hostPort))
    {
        qWarning("QXmppSocksClient could not parse type/host/port");
        return false;
    }
    // FIXME : what do we do with the resulting name / port?

    connect(m_socket, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
    connect(m_socket, SIGNAL(readyRead()), this, SIGNAL(readyRead()));
    return true;
}

QXmppSocksServer::QXmppSocksServer(QObject *parent)
    : QObject(parent),
    m_hostPort(0),
    m_socket(0)
{
    m_server = new QTcpServer(this);
    connect(m_server, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
}

bool QXmppSocksServer::listen(const QHostAddress &address, quint16 port)
{
    return m_server->listen(address, port);
}

QHostAddress QXmppSocksServer::serverAddress() const
{
    return m_server->serverAddress();
}

quint16 QXmppSocksServer::serverPort() const
{
    return m_server->serverPort();
}

void QXmppSocksServer::slotNewConnection()
{
    m_socket = m_server->nextPendingConnection();
    if (!m_socket)
        return;

    // wait for connect to server
    if (!m_socket->waitForReadyRead())
        return;
    QByteArray buffer = m_socket->readAll();
    if (buffer.size() < 3 ||
        buffer.at(0) != SocksVersion ||
        buffer.at(1) != 0x01 ||
        buffer.at(2) != NoAuthentication)
    {
        qWarning("QXmppSocksServer received invalid handshake");
        m_socket->close();
        return;
    }

    // send connect to server response
    buffer.resize(2);
    buffer[0] = SocksVersion;
    buffer[1] = NoAuthentication;
    m_socket->write(buffer);

    // wait for connect command
    if (!m_socket->waitForReadyRead())
        return;
    buffer = m_socket->readAll();
    if (buffer.size() < 4 ||
        buffer.at(0) != SocksVersion ||
        buffer.at(1) != ConnectCommand ||
        buffer.at(2) != 0x00)
    {
        qWarning("QXmppSocksServer received an invalid command");
        m_socket->close();
        return;
    }

    // parse host
    quint8 hostType;
    QByteArray hostName;
    quint16 hostPort;
    if (!parseHostAndPort(buffer.mid(3), hostType, hostName, hostPort))
    {
        qWarning("QXmppSocksServer could not parse type/host/port");
        m_socket->close();
        return;
    }
    if (hostName != m_hostName || hostPort != m_hostPort)
    {
        qWarning("QXmppSocksServer got wrong host or port");
        m_socket->close();
        return;
    }

    //send connect response
    buffer.resize(3);
    buffer[0] = SocksVersion;
    buffer[1] = Succeeded;
    buffer[2] = 0x00;
    buffer.append(encodeHostAndPort(
        DomainName,
        m_server->serverAddress().toString().toAscii(),
        m_server->serverPort()));
    m_socket->write(buffer);

    // connect signals
    connect(m_socket, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
    connect(m_socket, SIGNAL(bytesWritten(qint64)), this, SIGNAL(bytesWritten(qint64)));
}

void QXmppSocksServer::setHostName(const QString &hostName)
{
    m_hostName = hostName;
}

void QXmppSocksServer::setHostPort(quint16 hostPort)
{
    m_hostPort = hostPort;
}

void QXmppSocksServer::write(const QByteArray &data)
{
    if (m_socket)
        m_socket->write(data);
}
<|endoftext|>


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

  Program:   Monteverdi2
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
#include <QtOpenGL>

//
// System includes (sorted by alphabetic order)
// necessary for the opengl variables and methods

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)

//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdImageModelRenderer.h"
#include "mvdVectorImageModel.h"

namespace mvd
{
/*
  TRANSLATOR mvd::ImageModelRenderer

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
ImageModelRenderer
::ImageModelRenderer( QObject* parent ) :
  QObject( parent )
{
}

/*****************************************************************************/
ImageModelRenderer
::~ImageModelRenderer()
{
}

/*****************************************************************************/
void ImageModelRenderer::paintGL( const RenderingContext& context )
{
  // the VectorImageModel used for the rendering
  VectorImageModel * viModel = qobject_cast< VectorImageModel * >(
    const_cast<AbstractImageModel*>(context.m_AbstractImageModel)
  );

  // the region of the image to be rendered
  const ImageRegionType&  region = context.m_ImageRegion;

  // If the image is a j2k image
  int lod = 0;
  ImageRegionType  scaledRegion = region;
  if ( viModel->GetBestLevelOfDetail(context.m_IsotropicZoom, lod) )
    {
    // if the level of detail is an overview
    // recompute the region to request
    if (lod != 0)
      {
      ImageRegionType::SizeType  scaledSize;
      ImageRegionType::IndexType scaledOrigin;

      scaledSize[0] = region.GetSize()[0]/(1<<lod);
      scaledSize[1] = region.GetSize()[1]/(1<<lod);

      scaledOrigin[0] = region.GetIndex()[0]/(1<<lod);
      scaledOrigin[1] = region.GetIndex()[1]/(1<<lod);

      scaledRegion.SetSize(scaledSize) ;
      scaledRegion.SetIndex(scaledOrigin);
      }
    }
  // TODO : remove verbosity
  std::cout <<"J2k resolution requested :" << lod<< std::endl;

  // request the data for the current region
  m_Buffer = viModel->RasterizeRegion(scaledRegion, context.m_IsotropicZoom);

  // Current resolution
  double currentResolutionFactor = 1 << lod;

  // if buffer not null do the rendering
  if (m_Buffer != NULL)
    {
      unsigned int nb_displayed_cols = scaledRegion.GetSize()[ 0 ] ;
      unsigned int nb_displayed_rows = scaledRegion.GetSize()[ 1 ] ;

      unsigned int first_displayed_col = 0;
      if ( context.m_WidgetWidth  >
           scaledRegion.GetSize()[0] * context.m_IsotropicZoom*currentResolutionFactor  )
        {
        first_displayed_col = (context.m_WidgetWidth
                               - scaledRegion.GetSize()[0] * context.m_IsotropicZoom*currentResolutionFactor) /2;
        }

      unsigned int first_displayed_row = 0;
      if (context.m_WidgetHeight >
          scaledRegion.GetSize()[1] * context.m_IsotropicZoom*currentResolutionFactor)
        {
        first_displayed_row = (context.m_WidgetHeight
                               - scaledRegion.GetSize()[1] * context.m_IsotropicZoom*currentResolutionFactor)/2;
        }

      // std::cout <<"\tImageModeRenderer : contex.Zoom  "<<   context.m_IsotropicZoom
      //           << " currentResolutFactor "<< currentResolutionFactor << std::endl;
      // std::cout <<"\tImageModeRenderer : finalZoom to apply:  "<<
      //   context.m_IsotropicZoom*currentResolutionFactor << std::endl;

      // Render the buffer
      glPixelZoom(context.m_IsotropicZoom*currentResolutionFactor,
                  context.m_IsotropicZoom*currentResolutionFactor);
      glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
      glRasterPos2f(first_displayed_col, first_displayed_row);
      glDrawPixels(nb_displayed_cols,
                   nb_displayed_rows,
                   GL_RGB,
                   GL_UNSIGNED_BYTE,
                   m_Buffer);

      // glEnable(GL_TEXTURE_2D);
      // //glColor4f(1.0, 1.0, 1.0, 0.0);
      // GLuint texture;
      // glGenTextures(1, &texture);
      // glBindTexture(GL_TEXTURE_2D, texture);
      // glTexImage2D(GL_TEXTURE_2D, 0, 3, nb_displayed_cols,
      //              nb_displayed_rows, 0, GL_RGB, GL_UNSIGNED_BYTE, buffer);
      // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
      // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
      // glBindTexture (GL_TEXTURE_2D, texture);
      // glBegin (GL_QUADS);
      // glTexCoord2f (0.0, 1.0);
      // glVertex3f (first_displayed_col, first_displayed_row, 0.0);
      // glTexCoord2f (1.0, 1.0);
      // glVertex3f (first_displayed_col + scaledRegion.GetSize()[0], first_displayed_row, 0.0);
      // glTexCoord2f (1.0, 0.0);
      // glVertex3f (first_displayed_col + scaledRegion.GetSize()[0], first_displayed_row + scaledRegion.GetSize()[1], 0.0);
      // glTexCoord2f (0.0, 0.0);
      // glVertex3f (first_displayed_col, first_displayed_row + scaledRegion.GetSize()[1], 0.0);
      // glEnd ();
      // glDeleteTextures(1, &texture);
      // glDisable(GL_TEXTURE_2D);

      //glFlush();
    }
}

/*****************************************************************************/
/* SLOTS                                                                     */
/*****************************************************************************/

/*****************************************************************************/

} // end namespace 'mvd'
<commit_msg>ENH: use texture to render<commit_after>/*=========================================================================

  Program:   Monteverdi2
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
#include <QtOpenGL>

//
// System includes (sorted by alphabetic order)
// necessary for the opengl variables and methods

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)

//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdImageModelRenderer.h"
#include "mvdVectorImageModel.h"

namespace mvd
{
/*
  TRANSLATOR mvd::ImageModelRenderer

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
ImageModelRenderer
::ImageModelRenderer( QObject* parent ) :
  QObject( parent )
{
}

/*****************************************************************************/
ImageModelRenderer
::~ImageModelRenderer()
{
}

/*****************************************************************************/
void ImageModelRenderer::paintGL( const RenderingContext& context )
{
  // the VectorImageModel used for the rendering
  VectorImageModel * viModel = qobject_cast< VectorImageModel * >(
    const_cast<AbstractImageModel*>(context.m_AbstractImageModel)
  );

  // the region of the image to be rendered
  const ImageRegionType&  region = context.m_ImageRegion;

  // If the image is a j2k image
  int lod = 0;
  ImageRegionType  scaledRegion = region;
  if ( viModel->GetBestLevelOfDetail(context.m_IsotropicZoom, lod) )
    {
    // if the level of detail is an overview
    // recompute the region to request
    if (lod != 0)
      {
      ImageRegionType::SizeType  scaledSize;
      ImageRegionType::IndexType scaledOrigin;

      scaledSize[0] = region.GetSize()[0]/(1<<lod);
      scaledSize[1] = region.GetSize()[1]/(1<<lod);

      scaledOrigin[0] = region.GetIndex()[0]/(1<<lod);
      scaledOrigin[1] = region.GetIndex()[1]/(1<<lod);

      scaledRegion.SetSize(scaledSize) ;
      scaledRegion.SetIndex(scaledOrigin);
      }
    }
  // TODO : remove verbosity
  std::cout <<"J2k resolution requested :" << lod<< std::endl;

  // request the data for the current region
  m_Buffer = viModel->RasterizeRegion(scaledRegion, context.m_IsotropicZoom);

  // Current resolution
  double currentResolutionFactor = 1 << lod;

  // if buffer not null do the rendering
  if (m_Buffer != NULL)
    {
      unsigned int nb_displayed_cols = scaledRegion.GetSize()[ 0 ] ;
      unsigned int nb_displayed_rows = scaledRegion.GetSize()[ 1 ] ;

      unsigned int first_displayed_col = 0;
      if ( context.m_WidgetWidth  >
           scaledRegion.GetSize()[0] * context.m_IsotropicZoom*currentResolutionFactor  )
        {
        first_displayed_col = (context.m_WidgetWidth
                               - scaledRegion.GetSize()[0] * context.m_IsotropicZoom*currentResolutionFactor) /2;
        }

      unsigned int first_displayed_row = 0;
      if (context.m_WidgetHeight >
          scaledRegion.GetSize()[1] * context.m_IsotropicZoom*currentResolutionFactor)
        {
        first_displayed_row = (context.m_WidgetHeight
                               - scaledRegion.GetSize()[1] * context.m_IsotropicZoom*currentResolutionFactor)/2;
        }

      // std::cout <<"\tImageModeRenderer : contex.Zoom  "<<   context.m_IsotropicZoom
      //           << " currentResolutFactor "<< currentResolutionFactor << std::endl;
      // std::cout <<"\tImageModeRenderer : finalZoom to apply:  "<<
      //   context.m_IsotropicZoom*currentResolutionFactor << std::endl;

      // Render the buffer
      // glPixelZoom(context.m_IsotropicZoom*currentResolutionFactor,
      //             context.m_IsotropicZoom*currentResolutionFactor);
      // glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
      // glRasterPos2f(first_displayed_col, first_displayed_row);
      // glDrawPixels(nb_displayed_cols,
      //              nb_displayed_rows,
      //              GL_RGB,
      //              GL_UNSIGNED_BYTE,
      //              m_Buffer);

      glEnable(GL_TEXTURE_2D);
      //glColor4f(1.0, 1.0, 1.0, 0.0);
      GLuint texture;
      glGenTextures(1, &texture);
      glBindTexture(GL_TEXTURE_2D, texture);
      glTexImage2D(GL_TEXTURE_2D, 0, 3,
                   scaledRegion.GetSize()[0],
                   scaledRegion.GetSize()[1],
                   0, GL_RGB, GL_UNSIGNED_BYTE, m_Buffer);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
      glBindTexture (GL_TEXTURE_2D, texture);

      glBegin (GL_QUADS);
      glTexCoord2f (0.0, 1.0);
      glVertex3f (first_displayed_col, first_displayed_row, 0.0);
      glTexCoord2f (1.0, 1.0);
      glVertex3f (first_displayed_col + scaledRegion.GetSize()[0], first_displayed_row, 0.0);
      glTexCoord2f (1.0, 0.0);
      glVertex3f (first_displayed_col + scaledRegion.GetSize()[0], first_displayed_row + scaledRegion.GetSize()[1], 0.0);
      glTexCoord2f (0.0, 0.0);
      glVertex3f (first_displayed_col, first_displayed_row + scaledRegion.GetSize()[1], 0.0);
      glEnd ();
      glDeleteTextures(1, &texture);
      glDisable(GL_TEXTURE_2D);

      //glFlush();
    }
}

/*****************************************************************************/
/* SLOTS                                                                     */
/*****************************************************************************/

/*****************************************************************************/

} // end namespace 'mvd'
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: datetime.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: fs $ $Date: 2000-11-02 10:30:17 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

//= conversions UNO3.TimeClass <-> Tools.TimeClass (Date/Time/DateTime)

#ifndef _UNOTOOLS_DATETIME_HXX_
#define _UNOTOOLS_DATETIME_HXX_

#include <com/sun/star/util/Date.hpp>
#include <com/sun/star/util/Time.hpp>
#include <com/sun/star/util/DateTime.hpp>

class Date;
class Time;
class DateTime;

//.........................................................................
namespace utl
{
//.........................................................................

    namespace starutil = ::com::sun::star::util;

    void typeConvert(const Time& _rTime, starutil::Time& _rOut);
    void typeConvert(const starutil::Time& _rTime, Time& _rOut);

    void typeConvert(const Date& _rDate, starutil::Date& _rOut);
    void typeConvert(const starutil::Date& _rDate, Date& _rOut);

    void typeConvert(const DateTime& _rDateTime, starutil::DateTime& _rOut);
    void typeConvert(const starutil::DateTime& _rDateTime, DateTime& _rOut);

//.........................................................................
}   // namespace utl
//.........................................................................

#endif // _UNOTOOLS_DATETIME_HXX_

<commit_msg>INTEGRATION: CWS visibility03 (1.3.226); FILE MERGED 2005/02/28 04:33:53 mnicel 1.3.226.1: Issue number:  40092 Part of visibility work<commit_after>/*************************************************************************
 *
 *  $RCSfile: datetime.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2005-04-13 12:25:14 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

//= conversions UNO3.TimeClass <-> Tools.TimeClass (Date/Time/DateTime)
#ifndef INCLUDED_UNOTOOLSDLLAPI_H
#include "unotools/unotoolsdllapi.h"
#endif

#ifndef _UNOTOOLS_DATETIME_HXX_
#define _UNOTOOLS_DATETIME_HXX_

#include <com/sun/star/util/Date.hpp>
#include <com/sun/star/util/Time.hpp>
#include <com/sun/star/util/DateTime.hpp>

class Date;
class Time;
class DateTime;

//.........................................................................
namespace utl
{
//.........................................................................

    namespace starutil = ::com::sun::star::util;

    UNOTOOLS_DLLPUBLIC void typeConvert(const Time& _rTime, starutil::Time& _rOut);
    UNOTOOLS_DLLPUBLIC void typeConvert(const starutil::Time& _rTime, Time& _rOut);

    UNOTOOLS_DLLPUBLIC void typeConvert(const Date& _rDate, starutil::Date& _rOut);
    UNOTOOLS_DLLPUBLIC void typeConvert(const starutil::Date& _rDate, Date& _rOut);

    UNOTOOLS_DLLPUBLIC void typeConvert(const DateTime& _rDateTime, starutil::DateTime& _rOut);
    UNOTOOLS_DLLPUBLIC void typeConvert(const starutil::DateTime& _rDateTime, DateTime& _rOut);

//.........................................................................
}   // namespace utl
//.........................................................................

#endif // _UNOTOOLS_DATETIME_HXX_

<|endoftext|>