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

#include <map>
#include <stack>
#include <string>

#include "arch/alpha/osfpal.hh"
#include "base/trace.hh"
#include "base/statistics.hh"
#include "base/stats/bin.hh"
#include "cpu/exec_context.hh"
#include "cpu/pc_event.hh"
#include "cpu/static_inst.hh"
#include "kern/kernel_stats.hh"
#include "kern/linux/linux_syscalls.hh"

using namespace std;
using namespace Stats;

namespace Kernel {

const char *modestr[] = { "kernel", "user", "idle", "interrupt" };

Statistics::Statistics(ExecContext *context)
    : xc(context), idleProcess((Addr)-1), themode(kernel), lastModeTick(0),
      iplLast(0), iplLastTick(0)
{
    bin_int = xc->system->params->bin_int;
}

void
Statistics::regStats(const string &_name)
{
    myname = _name;

    _arm
        .name(name() + ".inst.arm")
        .desc("number of arm instructions executed")
        ;

    _quiesce
        .name(name() + ".inst.quiesce")
        .desc("number of quiesce instructions executed")
        ;

    _ivlb
        .name(name() + ".inst.ivlb")
        .desc("number of ivlb instructions executed")
        ;

    _ivle
        .name(name() + ".inst.ivle")
        .desc("number of ivle instructions executed")
        ;

    _hwrei
        .name(name() + ".inst.hwrei")
        .desc("number of hwrei instructions executed")
        ;

    _iplCount
        .init(32)
        .name(name() + ".ipl_count")
        .desc("number of times we switched to this ipl")
        .flags(total | pdf | nozero | nonan)
        ;

    _iplGood
        .init(32)
        .name(name() + ".ipl_good")
        .desc("number of times we switched to this ipl from a different ipl")
        .flags(total | pdf | nozero | nonan)
        ;

    _iplTicks
        .init(32)
        .name(name() + ".ipl_ticks")
        .desc("number of cycles we spent at this ipl")
        .flags(total | pdf | nozero | nonan)
        ;

    _iplUsed
        .name(name() + ".ipl_used")
        .desc("fraction of swpipl calls that actually changed the ipl")
        .flags(total | nozero | nonan)
        ;

    _iplUsed = _iplGood / _iplCount;

    _callpal
        .init(256)
        .name(name() + ".callpal")
        .desc("number of callpals executed")
        .flags(total | pdf | nozero | nonan)
        ;

    for (int i = 0; i < PAL::NumCodes; ++i) {
        const char *str = PAL::name(i);
        if (str)
            _callpal.subname(i, str);
    }

    _syscall
        .init(SystemCalls<Tru64>::Number)
        .name(name() + ".syscall")
        .desc("number of syscalls executed")
        .flags(total | pdf | nozero | nonan)
        ;

    for (int i = 0; i < SystemCalls<Tru64>::Number; ++i) {
        const char *str = SystemCalls<Tru64>::name(i);
        if (str) {
            _syscall.subname(i, str);
        }
    }

    _faults
        .init(Num_Faults)
        .name(name() + ".faults")
        .desc("number of faults")
        .flags(total | pdf | nozero | nonan)
        ;

    for (int i = 1; i < Num_Faults; ++i) {
        const char *str = FaultName(i);
        if (str)
            _faults.subname(i, str);
    }

    _mode
        .init(cpu_mode_num)
        .name(name() + ".mode_switch")
        .desc("number of protection mode switches")
        ;

    for (int i = 0; i < cpu_mode_num; ++i)
        _mode.subname(i, modestr[i]);

    _modeGood
        .init(cpu_mode_num)
        .name(name() + ".mode_good")
        ;

    for (int i = 0; i < cpu_mode_num; ++i)
        _modeGood.subname(i, modestr[i]);

    _modeFraction
        .name(name() + ".mode_switch_good")
        .desc("fraction of useful protection mode switches")
        .flags(total)
        ;

    for (int i = 0; i < cpu_mode_num; ++i)
        _modeFraction.subname(i, modestr[i]);

    _modeFraction = _modeGood / _mode;

    _modeTicks
        .init(cpu_mode_num)
        .name(name() + ".mode_ticks")
        .desc("number of ticks spent at the given mode")
        .flags(pdf)
        ;
    for (int i = 0; i < cpu_mode_num; ++i)
        _modeTicks.subname(i, modestr[i]);

    _swap_context
        .name(name() + ".swap_context")
        .desc("number of times the context was actually changed")
        ;
}

void
Statistics::setIdleProcess(Addr idlepcbb)
{
    assert(themode == kernel || themode == interrupt);
    idleProcess = idlepcbb;
    themode = idle;
    changeMode(themode);
}

void
Statistics::changeMode(cpu_mode newmode)
{
    _mode[newmode]++;

    if (newmode == themode)
        return;

    DPRINTF(Context, "old mode=%-8s new mode=%-8s\n",
            modestr[themode], modestr[newmode]);

    _modeGood[newmode]++;
    _modeTicks[themode] += curTick - lastModeTick;

    xc->system->kernelBinning->changeMode(newmode);

    lastModeTick = curTick;
    themode = newmode;
}

void
Statistics::swpipl(int ipl)
{
    assert(ipl >= 0 && ipl <= 0x1f && "invalid IPL\n");

    _iplCount[ipl]++;

    if (ipl == iplLast)
        return;

    _iplGood[ipl]++;
    _iplTicks[iplLast] += curTick - iplLastTick;
    iplLastTick = curTick;
    iplLast = ipl;
}

void
Statistics::mode(cpu_mode newmode)
{
    Addr pcbb = xc->regs.ipr[AlphaISA::IPR_PALtemp23];

    if ((newmode == kernel || newmode == interrupt) &&
            pcbb == idleProcess)
        newmode = idle;

    if (bin_int == false && newmode == interrupt)
        newmode = kernel;

    changeMode(newmode);
}

void
Statistics::context(Addr oldpcbb, Addr newpcbb)
{
    assert(themode != user);

    _swap_context++;
    changeMode(newpcbb == idleProcess ? idle : kernel);
}

void
Statistics::callpal(int code)
{
    if (!PAL::name(code))
        return;

    _callpal[code]++;

    switch (code) {
      case PAL::callsys: {
          int number = xc->regs.intRegFile[0];
          if (SystemCalls<Tru64>::validSyscallNumber(number)) {
              int cvtnum = SystemCalls<Tru64>::convert(number);
              _syscall[cvtnum]++;
          }
      } break;

      case PAL::swpctx:
        if (xc->system->kernelBinning)
            xc->system->kernelBinning->palSwapContext(xc);
        break;
    }
}

void
Statistics::serialize(ostream &os)
{
    int exemode = themode;
    SERIALIZE_SCALAR(exemode);
    SERIALIZE_SCALAR(idleProcess);
}

void
Statistics::unserialize(Checkpoint *cp, const string &section)
{
    int exemode;
    UNSERIALIZE_SCALAR(exemode);
    UNSERIALIZE_SCALAR(idleProcess);
    themode = (cpu_mode)exemode;
}

/* end namespace Kernel */ }
<commit_msg>few more stat items to serialize<commit_after>/*
 * Copyright (c) 2003 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <map>
#include <stack>
#include <string>

#include "arch/alpha/osfpal.hh"
#include "base/trace.hh"
#include "base/statistics.hh"
#include "base/stats/bin.hh"
#include "cpu/exec_context.hh"
#include "cpu/pc_event.hh"
#include "cpu/static_inst.hh"
#include "kern/kernel_stats.hh"
#include "kern/linux/linux_syscalls.hh"

using namespace std;
using namespace Stats;

namespace Kernel {

const char *modestr[] = { "kernel", "user", "idle", "interrupt" };

Statistics::Statistics(ExecContext *context)
    : xc(context), idleProcess((Addr)-1), themode(kernel), lastModeTick(0),
      iplLast(0), iplLastTick(0)
{
    bin_int = xc->system->params->bin_int;
}

void
Statistics::regStats(const string &_name)
{
    myname = _name;

    _arm
        .name(name() + ".inst.arm")
        .desc("number of arm instructions executed")
        ;

    _quiesce
        .name(name() + ".inst.quiesce")
        .desc("number of quiesce instructions executed")
        ;

    _ivlb
        .name(name() + ".inst.ivlb")
        .desc("number of ivlb instructions executed")
        ;

    _ivle
        .name(name() + ".inst.ivle")
        .desc("number of ivle instructions executed")
        ;

    _hwrei
        .name(name() + ".inst.hwrei")
        .desc("number of hwrei instructions executed")
        ;

    _iplCount
        .init(32)
        .name(name() + ".ipl_count")
        .desc("number of times we switched to this ipl")
        .flags(total | pdf | nozero | nonan)
        ;

    _iplGood
        .init(32)
        .name(name() + ".ipl_good")
        .desc("number of times we switched to this ipl from a different ipl")
        .flags(total | pdf | nozero | nonan)
        ;

    _iplTicks
        .init(32)
        .name(name() + ".ipl_ticks")
        .desc("number of cycles we spent at this ipl")
        .flags(total | pdf | nozero | nonan)
        ;

    _iplUsed
        .name(name() + ".ipl_used")
        .desc("fraction of swpipl calls that actually changed the ipl")
        .flags(total | nozero | nonan)
        ;

    _iplUsed = _iplGood / _iplCount;

    _callpal
        .init(256)
        .name(name() + ".callpal")
        .desc("number of callpals executed")
        .flags(total | pdf | nozero | nonan)
        ;

    for (int i = 0; i < PAL::NumCodes; ++i) {
        const char *str = PAL::name(i);
        if (str)
            _callpal.subname(i, str);
    }

    _syscall
        .init(SystemCalls<Tru64>::Number)
        .name(name() + ".syscall")
        .desc("number of syscalls executed")
        .flags(total | pdf | nozero | nonan)
        ;

    for (int i = 0; i < SystemCalls<Tru64>::Number; ++i) {
        const char *str = SystemCalls<Tru64>::name(i);
        if (str) {
            _syscall.subname(i, str);
        }
    }

    _faults
        .init(Num_Faults)
        .name(name() + ".faults")
        .desc("number of faults")
        .flags(total | pdf | nozero | nonan)
        ;

    for (int i = 1; i < Num_Faults; ++i) {
        const char *str = FaultName(i);
        if (str)
            _faults.subname(i, str);
    }

    _mode
        .init(cpu_mode_num)
        .name(name() + ".mode_switch")
        .desc("number of protection mode switches")
        ;

    for (int i = 0; i < cpu_mode_num; ++i)
        _mode.subname(i, modestr[i]);

    _modeGood
        .init(cpu_mode_num)
        .name(name() + ".mode_good")
        ;

    for (int i = 0; i < cpu_mode_num; ++i)
        _modeGood.subname(i, modestr[i]);

    _modeFraction
        .name(name() + ".mode_switch_good")
        .desc("fraction of useful protection mode switches")
        .flags(total)
        ;

    for (int i = 0; i < cpu_mode_num; ++i)
        _modeFraction.subname(i, modestr[i]);

    _modeFraction = _modeGood / _mode;

    _modeTicks
        .init(cpu_mode_num)
        .name(name() + ".mode_ticks")
        .desc("number of ticks spent at the given mode")
        .flags(pdf)
        ;
    for (int i = 0; i < cpu_mode_num; ++i)
        _modeTicks.subname(i, modestr[i]);

    _swap_context
        .name(name() + ".swap_context")
        .desc("number of times the context was actually changed")
        ;
}

void
Statistics::setIdleProcess(Addr idlepcbb)
{
    assert(themode == kernel || themode == interrupt);
    idleProcess = idlepcbb;
    themode = idle;
    changeMode(themode);
}

void
Statistics::changeMode(cpu_mode newmode)
{
    _mode[newmode]++;

    if (newmode == themode)
        return;

    DPRINTF(Context, "old mode=%-8s new mode=%-8s\n",
            modestr[themode], modestr[newmode]);

    _modeGood[newmode]++;
    _modeTicks[themode] += curTick - lastModeTick;

    xc->system->kernelBinning->changeMode(newmode);

    lastModeTick = curTick;
    themode = newmode;
}

void
Statistics::swpipl(int ipl)
{
    assert(ipl >= 0 && ipl <= 0x1f && "invalid IPL\n");

    _iplCount[ipl]++;

    if (ipl == iplLast)
        return;

    _iplGood[ipl]++;
    _iplTicks[iplLast] += curTick - iplLastTick;
    iplLastTick = curTick;
    iplLast = ipl;
}

void
Statistics::mode(cpu_mode newmode)
{
    Addr pcbb = xc->regs.ipr[AlphaISA::IPR_PALtemp23];

    if ((newmode == kernel || newmode == interrupt) &&
            pcbb == idleProcess)
        newmode = idle;

    if (bin_int == false && newmode == interrupt)
        newmode = kernel;

    changeMode(newmode);
}

void
Statistics::context(Addr oldpcbb, Addr newpcbb)
{
    assert(themode != user);

    _swap_context++;
    changeMode(newpcbb == idleProcess ? idle : kernel);
}

void
Statistics::callpal(int code)
{
    if (!PAL::name(code))
        return;

    _callpal[code]++;

    switch (code) {
      case PAL::callsys: {
          int number = xc->regs.intRegFile[0];
          if (SystemCalls<Tru64>::validSyscallNumber(number)) {
              int cvtnum = SystemCalls<Tru64>::convert(number);
              _syscall[cvtnum]++;
          }
      } break;

      case PAL::swpctx:
        if (xc->system->kernelBinning)
            xc->system->kernelBinning->palSwapContext(xc);
        break;
    }
}

void
Statistics::serialize(ostream &os)
{
    int exemode = themode;
    SERIALIZE_SCALAR(exemode);
    SERIALIZE_SCALAR(idleProcess);
    SERIALIZE_SCALAR(iplLast);
    SERIALIZE_SCALAR(iplLastTick);
    SERIALIZE_SCALAR(lastModeTick);
}

void
Statistics::unserialize(Checkpoint *cp, const string &section)
{
    int exemode;
    UNSERIALIZE_SCALAR(exemode);
    UNSERIALIZE_SCALAR(idleProcess);
    UNSERIALIZE_SCALAR(iplLast);
    UNSERIALIZE_SCALAR(iplLastTick);
    UNSERIALIZE_SCALAR(lastModeTick);
    themode = (cpu_mode)exemode;
}

/* end namespace Kernel */ }
<|endoftext|>


<commit_before>#include "cube-egl.h"
#include "cube.h"

#include <kms++util/kms++util.h>

using namespace std;

EglState::EglState(void *native_display)
{
	EGLBoolean b;
	EGLint major, minor, n;

	static const EGLint context_attribs[] = {
		EGL_CONTEXT_CLIENT_VERSION, 2,
		EGL_NONE
	};

	static const EGLint config_attribs[] = {
		EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
		EGL_RED_SIZE, 8,
		EGL_GREEN_SIZE, 8,
		EGL_BLUE_SIZE, 8,
		EGL_ALPHA_SIZE, 0,
		EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
		EGL_NONE
	};

	m_display = eglGetDisplay((EGLNativeDisplayType)native_display);
	FAIL_IF(!m_display, "failed to get egl display");

	b = eglInitialize(m_display, &major, &minor);
	FAIL_IF(!b, "failed to initialize");

	if (s_verbose) {
		printf("Using display %p with EGL version %d.%d\n", m_display, major, minor);

		printf("EGL_VENDOR:      %s\n", eglQueryString(m_display, EGL_VENDOR));
		printf("EGL_VERSION:     %s\n", eglQueryString(m_display, EGL_VERSION));
		printf("EGL_EXTENSIONS:  %s\n", eglQueryString(m_display, EGL_EXTENSIONS));
		printf("EGL_CLIENT_APIS: %s\n", eglQueryString(m_display, EGL_CLIENT_APIS));
	}

	b = eglBindAPI(EGL_OPENGL_ES_API);
	FAIL_IF(!b, "failed to bind api EGL_OPENGL_ES_API");

	b = eglChooseConfig(m_display, config_attribs, &m_config, 1, &n);
	FAIL_IF(!b || n != 1, "failed to choose config");

	auto getconf = [this](EGLint a) { EGLint v = -1; eglGetConfigAttrib(m_display, m_config, a, &v); return v; };

	if (s_verbose) {
		printf("EGL Config %d: color buf %d/%d/%d/%d = %d, depth %d, stencil %d\n",
		       getconf(EGL_CONFIG_ID),
		       getconf(EGL_ALPHA_SIZE),
		       getconf(EGL_RED_SIZE),
		       getconf(EGL_GREEN_SIZE),
		       getconf(EGL_BLUE_SIZE),
		       getconf(EGL_BUFFER_SIZE),
		       getconf(EGL_DEPTH_SIZE),
		       getconf(EGL_STENCIL_SIZE));
	}

	m_context = eglCreateContext(m_display, m_config, EGL_NO_CONTEXT, context_attribs);
	FAIL_IF(!m_context, "failed to create context");

	EGLBoolean ok = eglMakeCurrent(m_display, EGL_NO_SURFACE, EGL_NO_SURFACE, m_context);
	FAIL_IF(!ok, "eglMakeCurrent() failed");
}

EglState::~EglState()
{
	eglMakeCurrent(m_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
	eglTerminate(m_display);
}

EglSurface::EglSurface(const EglState &egl, void *native_window)
	: egl(egl)
{
	esurface = eglCreateWindowSurface(egl.display(), egl.config(), (EGLNativeWindowType)native_window, NULL);
	FAIL_IF(esurface == EGL_NO_SURFACE, "failed to create egl surface");
}

EglSurface::~EglSurface()
{
	eglDestroySurface(egl.display(), esurface);
}

void EglSurface::make_current()
{
	EGLBoolean ok = eglMakeCurrent(egl.display(), esurface, esurface, egl.context());
	FAIL_IF(!ok, "eglMakeCurrent() failed");
}

void EglSurface::swap_buffers()
{
	EGLBoolean ok = eglSwapBuffers(egl.display(), esurface);
	FAIL_IF(!ok, "eglMakeCurrent() failed");
}
<commit_msg>kmscube: improve egl config prints<commit_after>#include "cube-egl.h"
#include "cube.h"

#include <kms++util/kms++util.h>

using namespace std;

static void print_egl_config(EGLDisplay dpy, EGLConfig cfg)
{
	auto getconf = [dpy, cfg](EGLint a) { EGLint v = -1; eglGetConfigAttrib(dpy, cfg, a, &v); return v; };

	printf("EGL Config %d: color buf %d/%d/%d/%d = %d, depth %d, stencil %d, native visualid %d, native visualtype %d\n",
	       getconf(EGL_CONFIG_ID),
	       getconf(EGL_ALPHA_SIZE),
	       getconf(EGL_RED_SIZE),
	       getconf(EGL_GREEN_SIZE),
	       getconf(EGL_BLUE_SIZE),
	       getconf(EGL_BUFFER_SIZE),
	       getconf(EGL_DEPTH_SIZE),
	       getconf(EGL_STENCIL_SIZE),
	       getconf(EGL_NATIVE_VISUAL_ID),
	       getconf(EGL_NATIVE_VISUAL_TYPE));
}

EglState::EglState(void *native_display)
{
	EGLBoolean b;
	EGLint major, minor, n;

	static const EGLint context_attribs[] = {
		EGL_CONTEXT_CLIENT_VERSION, 2,
		EGL_NONE
	};

	static const EGLint config_attribs[] = {
		EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
		EGL_RED_SIZE, 8,
		EGL_GREEN_SIZE, 8,
		EGL_BLUE_SIZE, 8,
		EGL_ALPHA_SIZE, 0,
		EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
		EGL_NONE
	};

	m_display = eglGetDisplay((EGLNativeDisplayType)native_display);
	FAIL_IF(!m_display, "failed to get egl display");

	b = eglInitialize(m_display, &major, &minor);
	FAIL_IF(!b, "failed to initialize");

	if (s_verbose) {
		printf("Using display %p with EGL version %d.%d\n", m_display, major, minor);

		printf("EGL_VENDOR:      %s\n", eglQueryString(m_display, EGL_VENDOR));
		printf("EGL_VERSION:     %s\n", eglQueryString(m_display, EGL_VERSION));
		printf("EGL_EXTENSIONS:  %s\n", eglQueryString(m_display, EGL_EXTENSIONS));
		printf("EGL_CLIENT_APIS: %s\n", eglQueryString(m_display, EGL_CLIENT_APIS));
	}

	b = eglBindAPI(EGL_OPENGL_ES_API);
	FAIL_IF(!b, "failed to bind api EGL_OPENGL_ES_API");

	if (s_verbose) {
		EGLint numConfigs;
		b = eglGetConfigs(m_display, nullptr, 0, &numConfigs);
		FAIL_IF(!b, "failed to get number of configs");

		EGLConfig configs[numConfigs];
		b = eglGetConfigs(m_display, configs, numConfigs, &numConfigs);

		printf("Available configs:\n");

		for (int i = 0; i < numConfigs; ++i)
			print_egl_config(m_display, configs[i]);
	}

	b = eglChooseConfig(m_display, config_attribs, &m_config, 1, &n);
	FAIL_IF(!b || n != 1, "failed to choose config");

	if (s_verbose) {
		printf("Chosen config:\n");
		print_egl_config(m_display, m_config);
	}

	m_context = eglCreateContext(m_display, m_config, EGL_NO_CONTEXT, context_attribs);
	FAIL_IF(!m_context, "failed to create context");

	EGLBoolean ok = eglMakeCurrent(m_display, EGL_NO_SURFACE, EGL_NO_SURFACE, m_context);
	FAIL_IF(!ok, "eglMakeCurrent() failed");
}

EglState::~EglState()
{
	eglMakeCurrent(m_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
	eglTerminate(m_display);
}

EglSurface::EglSurface(const EglState &egl, void *native_window)
	: egl(egl)
{
	esurface = eglCreateWindowSurface(egl.display(), egl.config(), (EGLNativeWindowType)native_window, NULL);
	FAIL_IF(esurface == EGL_NO_SURFACE, "failed to create egl surface");
}

EglSurface::~EglSurface()
{
	eglDestroySurface(egl.display(), esurface);
}

void EglSurface::make_current()
{
	EGLBoolean ok = eglMakeCurrent(egl.display(), esurface, esurface, egl.context());
	FAIL_IF(!ok, "eglMakeCurrent() failed");
}

void EglSurface::swap_buffers()
{
	EGLBoolean ok = eglSwapBuffers(egl.display(), esurface);
	FAIL_IF(!ok, "eglMakeCurrent() failed");
}
<|endoftext|>


<commit_before>/*
 * MissionTerminalImplementation.cpp
 *
 *  Created on: 03/05/11
 *      Author: polonel
 */

#include "MissionTerminal.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/packets/scene/AttributeListMessage.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/packets/object/ObjectMenuResponse.h"
#include "server/zone/objects/region/CityRegion.h"

#include "server/zone/objects/player/sessions/SlicingSession.h"

void MissionTerminalImplementation::fillObjectMenuResponse(ObjectMenuResponse* menuResponse, CreatureObject* player) {

	CityRegion* city = player->getCityRegion();

	if(city != NULL && city->isMayor(player->getObjectID())){

		menuResponse->addRadialMenuItem(72, 3, "Remove");

	}
}

int MissionTerminalImplementation::handleObjectMenuSelect(CreatureObject* player, byte selectedID) {
	if (selectedID == 69) {

		if (player->containsActiveSession(SessionFacadeType::SLICING)) {
			player->sendSystemMessage("@slicing/slicing:already_slicing");
			return 0;
		}

		if (!player->checkCooldownRecovery("slicing.terminal")) {
			player->sendSystemMessage("@slicing/slicing:not_again");
			return 0;
		}

		//Create Session
		ManagedReference<SlicingSession*> session = new SlicingSession(player);
		session->initalizeSlicingMenu(player, _this);

		return 0;

	}

	else if (selectedID == 72) {

		CityRegion* city = player->getCityRegion();

		if (city != NULL)
			city->removeMissionTerminal(_this);

		_this->destroyObjectFromWorld(true);
		_this->destroyObjectFromDatabase(false);

	}

	else
		return TangibleObjectImplementation::handleObjectMenuSelect(player, selectedID);
}
<commit_msg>[Fixed] Mission Terminal Warning<commit_after>/*
 * MissionTerminalImplementation.cpp
 *
 *  Created on: 03/05/11
 *      Author: polonel
 */

#include "MissionTerminal.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/packets/scene/AttributeListMessage.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/packets/object/ObjectMenuResponse.h"
#include "server/zone/objects/region/CityRegion.h"

#include "server/zone/objects/player/sessions/SlicingSession.h"

void MissionTerminalImplementation::fillObjectMenuResponse(ObjectMenuResponse* menuResponse, CreatureObject* player) {

	CityRegion* city = player->getCityRegion();

	if(city != NULL && city->isMayor(player->getObjectID())){

		menuResponse->addRadialMenuItem(72, 3, "Remove");

	}
}

int MissionTerminalImplementation::handleObjectMenuSelect(CreatureObject* player, byte selectedID) {
	if (selectedID == 69) {

		if (player->containsActiveSession(SessionFacadeType::SLICING)) {
			player->sendSystemMessage("@slicing/slicing:already_slicing");
			return 0;
		}

		if (!player->checkCooldownRecovery("slicing.terminal")) {
			player->sendSystemMessage("@slicing/slicing:not_again");
			return 0;
		}

		//Create Session
		ManagedReference<SlicingSession*> session = new SlicingSession(player);
		session->initalizeSlicingMenu(player, _this);

		return 0;

	}

	if (selectedID == 72) {

		CityRegion* city = player->getCityRegion();

		if (city != NULL)
			city->removeMissionTerminal(_this);

		_this->destroyObjectFromWorld(true);
		_this->destroyObjectFromDatabase(false);

		return 0;
	}

	return TangibleObjectImplementation::handleObjectMenuSelect(player, selectedID);
}
<|endoftext|>


<commit_before>/* Copyright 2013 - 2014 Yurii Litvinov, CyberTech Labs Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

#include "servoMotor.h"

#include <trikKernel/configurer.h>
#include <trikHal/hardwareAbstractionInterface.h>
#include <QsLog.h>

#include "configurerHelper.h"

using namespace trikControl;

ServoMotor::ServoMotor(const QString &port, const trikKernel::Configurer &configurer
		, const trikHal::HardwareAbstractionInterface &hardwareAbstraction)
	: mDutyFile(hardwareAbstraction.createOutputDeviceFile(configurer.attributeByPort(port, "deviceFile")))
	, mPeriodFile(hardwareAbstraction.createOutputDeviceFile(configurer.attributeByPort(port, "periodFile")))
	, mRunFile(hardwareAbstraction.createOutputDeviceFile(configurer.attributeByPort(port, "runFile")))
	, mRun(false)
	, mCurrentDutyPercent(0)
	, mInvert(configurer.attributeByPort(port, "invert") == "true")
	, mCurrentPower(0)
	, mState("Servomotor on " + port)
{
	const auto configure = [this, &port, &configurer](const QString &parameterName) {
		return ConfigurerHelper::configureInt(configurer, mState, port, parameterName);
	};

	mPeriod = configure("period");
	mMin = configure("min");
	mMax = configure("max");
	mZero = configure("zero");
	mStop = configure("stop");
	mMinControlRange = configure("controlMin");
	mMaxControlRange = configure("controlMax");

	if (!mPeriodFile->open()) {
		mState.fail();
		return;
	}

	if (!mRunFile->open()) {
		mState.fail();
		return;
	} else {
		mRunFile->write(QString::number(mRun));
	}

	const QString command = QString::number(mPeriod);

	mPeriodFile->write(command);
	mPeriodFile->close();

	if (!mDutyFile->open()) {
		mState.fail();
	} else {
		mState.ready();
	}
}

ServoMotor::~ServoMotor()
{
}

ServoMotor::Status ServoMotor::status() const
{
	return mState.status();
}

int ServoMotor::minControl() const
{
	return mMinControlRange;
}

int ServoMotor::maxControl() const
{
	return mMaxControlRange;
}

int ServoMotor::power() const
{
	return mCurrentPower;
}

int ServoMotor::frequency() const
{
	return 1000000000.0 / static_cast<qreal>(mPeriod);
}

int ServoMotor::duty() const
{
	return mCurrentDutyPercent;
}

void ServoMotor::powerOff()
{
	if (!mState.isReady()) {
		QLOG_ERROR() << "Trying to power off motor which is not ready, ignoring";
		return;
	}

	mDutyFile->write(QString::number(mStop));
	mCurrentPower = 0;

	mRun = false;
	mRunFile->write(QString::number(mRun));
}

void ServoMotor::setPower(int power, bool constrain)
{
	if (!mState.isReady()) {
		QLOG_ERROR() << "Trying to turn on motor which is not ready, ignoring";
		return;
	}

	if (!mRun) {
		mRun = true;
		mRunFile->write(QString::number(mRun));
	}

	if (constrain) {
		if (power > mMaxControlRange) {
			power = mMaxControlRange;
		} else if (power < mMinControlRange) {
			power = mMinControlRange;
		}
	}

	mCurrentPower = power;

	const int meanControlRange = (mMaxControlRange + mMinControlRange) / 2;

	power = (mInvert ? -1 : 1) * (power - meanControlRange) + meanControlRange;

	const int range = power <= meanControlRange ? mZero - mMin : mMax - mZero;

	const qreal powerFactor = static_cast<qreal>(range) / (mMaxControlRange - mMinControlRange) * 2;
	const int duty = static_cast<int>(mZero + (power - meanControlRange) * powerFactor);
	const QString command = QString::number(duty);

	mCurrentDutyPercent = 100 * duty / mPeriod;

	mDutyFile->write(command);
}
<commit_msg>Some changes in motor running<commit_after>/* Copyright 2013 - 2014 Yurii Litvinov, CyberTech Labs Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

#include "servoMotor.h"

#include <trikKernel/configurer.h>
#include <trikHal/hardwareAbstractionInterface.h>
#include <QsLog.h>

#include "configurerHelper.h"

using namespace trikControl;

ServoMotor::ServoMotor(const QString &port, const trikKernel::Configurer &configurer
		, const trikHal::HardwareAbstractionInterface &hardwareAbstraction)
	: mDutyFile(hardwareAbstraction.createOutputDeviceFile(configurer.attributeByPort(port, "deviceFile")))
	, mPeriodFile(hardwareAbstraction.createOutputDeviceFile(configurer.attributeByPort(port, "periodFile")))
	, mRunFile(hardwareAbstraction.createOutputDeviceFile(configurer.attributeByPort(port, "runFile")))
	, mRun(false)
	, mCurrentDutyPercent(0)
	, mInvert(configurer.attributeByPort(port, "invert") == "true")
	, mCurrentPower(0)
	, mState("Servomotor on " + port)
{
	const auto configure = [this, &port, &configurer](const QString &parameterName) {
		return ConfigurerHelper::configureInt(configurer, mState, port, parameterName);
	};

	mPeriod = configure("period");
	mMin = configure("min");
	mMax = configure("max");
	mZero = configure("zero");
	mStop = configure("stop");
	mMinControlRange = configure("controlMin");
	mMaxControlRange = configure("controlMax");

	if (!mPeriodFile->open()) {
		mState.fail();
		return;
	}

	if (!mRunFile->open()) {
		mState.fail();
		return;
	} else {
		mRunFile->write(QString::number(mRun));
	}

	const QString command = QString::number(mPeriod);

	mPeriodFile->write(command);
	mPeriodFile->close();

	if (!mDutyFile->open()) {
		mState.fail();
	} else {
		mState.ready();
	}
}

ServoMotor::~ServoMotor()
{
}

ServoMotor::Status ServoMotor::status() const
{
	return mState.status();
}

int ServoMotor::minControl() const
{
	return mMinControlRange;
}

int ServoMotor::maxControl() const
{
	return mMaxControlRange;
}

int ServoMotor::power() const
{
	return mCurrentPower;
}

int ServoMotor::frequency() const
{
	return 1000000000.0 / static_cast<qreal>(mPeriod);
}

int ServoMotor::duty() const
{
	return mCurrentDutyPercent;
}

void ServoMotor::powerOff()
{
	if (!mState.isReady()) {
		QLOG_ERROR() << "Trying to power off motor which is not ready, ignoring";
		return;
	}

	mDutyFile->write(QString::number(mStop));
	mCurrentPower = 0;

	mRun = false;
	mRunFile->write(QString::number(mRun));
}

void ServoMotor::setPower(int power, bool constrain)
{
	if (!mState.isReady()) {
		QLOG_ERROR() << "Trying to turn on motor which is not ready, ignoring";
		return;
	}

	if (constrain) {
		if (power > mMaxControlRange) {
			power = mMaxControlRange;
		} else if (power < mMinControlRange) {
			power = mMinControlRange;
		}
	}

	mCurrentPower = power;

	const int meanControlRange = (mMaxControlRange + mMinControlRange) / 2;

	power = (mInvert ? -1 : 1) * (power - meanControlRange) + meanControlRange;

	const int range = power <= meanControlRange ? mZero - mMin : mMax - mZero;

	const qreal powerFactor = static_cast<qreal>(range) / (mMaxControlRange - mMinControlRange) * 2;
	const int duty = static_cast<int>(mZero + (power - meanControlRange) * powerFactor);
	const QString command = QString::number(duty);

	mCurrentDutyPercent = 100 * duty / mPeriod;

	mDutyFile->write(command);

	if (!mRun) {
		mRun = true;
		mRunFile->write(QString::number(mRun));
	}
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name:      stcdlg.cpp
// Purpose:   Implementation of class wxExSTCEntryDialog
// Author:    Anton van Wezenbeek
// Created:   2009-11-18
// RCS-ID:    $Id$
// Copyright: (c) 2009 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/extension/stcdlg.h>
#include <wx/extension/stc.h>

#if wxUSE_GUI

BEGIN_EVENT_TABLE(wxExSTCEntryDialog, wxExDialog)
  EVT_MENU(wxID_FIND, wxExSTCEntryDialog::OnCommand)
  EVT_MENU(wxID_REPLACE, wxExSTCEntryDialog::OnCommand)
END_EVENT_TABLE()

wxExSTCEntryDialog::wxExSTCEntryDialog(wxWindow* parent,
  const wxString& caption,
  const wxString& text,
  const wxString& prompt,
  long button_style,
  wxWindowID id,
  const wxPoint& pos,
  const wxSize& size,
  long style)
  : wxExDialog(parent, caption, button_style, id, pos, size, style)
{
  if (!prompt.empty())
  {
    AddUserSizer(CreateTextSizer(prompt), wxSizerFlags().Center());
  }

  wxFlexGridSizer* sizer = new wxFlexGridSizer(0);
  sizer->AddGrowableRow(0);
  sizer->AddGrowableCol(0);

  m_STC = new wxExSTC(
    this,
    text,
    0,
    wxEmptyString, // title
    wxExSTC::STC_MENU_SIMPLE |
      wxExSTC::STC_MENU_FIND |
      wxExSTC::STC_MENU_REPLACE,
    wxID_ANY,
    wxDefaultPosition);

  m_STC->SetEdgeMode(wxSTC_EDGE_NONE);
  m_STC->ResetMargins();
  m_STC->SetViewEOL(false);
  m_STC->SetViewWhiteSpace(wxSTC_WS_INVISIBLE);

  if ((button_style & wxCANCEL) == 0 &&
      (button_style & wxNO) == 0)
  {
    // You did not specify one of these buttons,
    // so you cannot cancel the operation.
    // Therefore make the component readonly.
    m_STC->SetReadOnly(true);
  }

  sizer->Add(m_STC, wxSizerFlags().Center().Border().Expand());

  AddUserSizer(sizer);

  LayoutSizers();
}

const wxExLexer* wxExSTCEntryDialog::GetLexer() const
{
  return &m_STC->GetLexer();
}

const wxString wxExSTCEntryDialog::GetText() const
{
  return m_STC->GetText();
}

const wxCharBuffer wxExSTCEntryDialog::GetTextRaw() const
{
  return m_STC->GetTextRaw();
}

void wxExSTCEntryDialog::OnCommand(wxCommandEvent& command)
{
  switch (command.GetId())
  {
    // Without these, events are not handled by the frame.
    case wxID_FIND:
    case wxID_REPLACE:
      wxPostEvent(wxTheApp->GetTopWindow(), command);
      break;

    default: wxFAIL;
  }
}

bool wxExSTCEntryDialog::SetLexer(const wxString& lexer)
{
  return m_STC->SetLexer(lexer);
}

void wxExSTCEntryDialog::SetText(const wxString& text)
{
  const bool readonly = m_STC->GetReadOnly();

  if (readonly)
  {
    m_STC->SetReadOnly(false);
  }

  m_STC->SetText(text);

  if (readonly)
  {
    m_STC->SetReadOnly(true);
  }
}

void wxExSTCEntryDialog::UpdateFromConfig()
{
  m_STC->ConfigGet();
}

#endif // wxUSE_GUI
<commit_msg>sizer is not needed<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name:      stcdlg.cpp
// Purpose:   Implementation of class wxExSTCEntryDialog
// Author:    Anton van Wezenbeek
// Created:   2009-11-18
// RCS-ID:    $Id$
// Copyright: (c) 2009 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/extension/stcdlg.h>
#include <wx/extension/stc.h>

#if wxUSE_GUI

BEGIN_EVENT_TABLE(wxExSTCEntryDialog, wxExDialog)
  EVT_MENU(wxID_FIND, wxExSTCEntryDialog::OnCommand)
  EVT_MENU(wxID_REPLACE, wxExSTCEntryDialog::OnCommand)
END_EVENT_TABLE()

wxExSTCEntryDialog::wxExSTCEntryDialog(wxWindow* parent,
  const wxString& caption,
  const wxString& text,
  const wxString& prompt,
  long button_style,
  wxWindowID id,
  const wxPoint& pos,
  const wxSize& size,
  long style)
  : wxExDialog(parent, caption, button_style, id, pos, size, style)
{
  if (!prompt.empty())
  {
    AddUserSizer(CreateTextSizer(prompt), wxSizerFlags().Center());
  }

  m_STC = new wxExSTC(
    this,
    text,
    0,
    wxEmptyString, // title
    wxExSTC::STC_MENU_SIMPLE |
      wxExSTC::STC_MENU_FIND |
      wxExSTC::STC_MENU_REPLACE,
    wxID_ANY,
    wxDefaultPosition);

  m_STC->SetEdgeMode(wxSTC_EDGE_NONE);
  m_STC->ResetMargins();
  m_STC->SetViewEOL(false);
  m_STC->SetViewWhiteSpace(wxSTC_WS_INVISIBLE);

  if ((button_style & wxCANCEL) == 0 &&
      (button_style & wxNO) == 0)
  {
    // You did not specify one of these buttons,
    // so you cannot cancel the operation.
    // Therefore make the component readonly.
    m_STC->SetReadOnly(true);
  }

  AddUserSizer(m_STC);

  LayoutSizers();
}

const wxExLexer* wxExSTCEntryDialog::GetLexer() const
{
  return &m_STC->GetLexer();
}

const wxString wxExSTCEntryDialog::GetText() const
{
  return m_STC->GetText();
}

const wxCharBuffer wxExSTCEntryDialog::GetTextRaw() const
{
  return m_STC->GetTextRaw();
}

void wxExSTCEntryDialog::OnCommand(wxCommandEvent& command)
{
  switch (command.GetId())
  {
    // Without these, events are not handled by the frame.
    case wxID_FIND:
    case wxID_REPLACE:
      wxPostEvent(wxTheApp->GetTopWindow(), command);
      break;

    default: wxFAIL;
  }
}

bool wxExSTCEntryDialog::SetLexer(const wxString& lexer)
{
  return m_STC->SetLexer(lexer);
}

void wxExSTCEntryDialog::SetText(const wxString& text)
{
  const bool readonly = m_STC->GetReadOnly();

  if (readonly)
  {
    m_STC->SetReadOnly(false);
  }

  m_STC->SetText(text);

  if (readonly)
  {
    m_STC->SetReadOnly(true);
  }
}

void wxExSTCEntryDialog::UpdateFromConfig()
{
  m_STC->ConfigGet();
}

#endif // wxUSE_GUI
<|endoftext|>


<commit_before>//
// Demo showing H -> ZZ -> 4 mu generated by Pythia.
// Requires libPythia6.

//==============================================================================
// Constants.
//------------------------------------------------------------------------------

const Double_t kR_min = 240;
const Double_t kR_max = 250;
const Double_t kZ_d   = 300;

// Solenoid field along z, in Tesla.
const Double_t kMagField = 4;

// Color for Higgs, Zs and muons
const Color_t  kColors[3] = { kRed, kGreen, kYellow };

//==============================================================================
// Global variables.
//------------------------------------------------------------------------------

class TPythia6;
TPythia6   *g_pythia = 0;

// Implemented in MultiView.C
class MultiView;
MultiView* gMultiView = 0;

TEveTrackList *gTrackList = 0;

//==============================================================================
// Forward decalarations of CINT functions.
//------------------------------------------------------------------------------

void pythia_next_event();
void pythia_make_gui();

//==============================================================================
// Main - pythia_display()
//------------------------------------------------------------------------------

void pythia_display()
{
   const TString weh("pythia_display()");

   if (g_pythia != 0)
   {
      Warning(weh, "Already initialized.");
      return;
   }

   if (gSystem->Load("libPythia6") < 0)
   {
      Error(weh, "Could not load 'libPythia6', make sure it is available!");
      return;
   }
   gSystem->Load("libEGPythia6");

   if (gROOT->LoadMacro("MultiView.C+") != 0)
   {
      Error(weh, "Failed loading MultiView.C in compiled mode.");
      return;
   }

   //========================================================================
   //========================================================================

   // Create an instance of the Pythia event generator ...
   g_pythia = new TPythia6;
   TPythia6& P = * g_pythia;

   P.SetMSEL(0);           // full user controll;
   P.SetMSUB(102, 1);      // g + g -> H0
   //P.SetMSUB(123, 1);    // f + f' -> f + f' + H0
   //P.SetMSUB(124, 1);    // f + f' -> f" + f"' + H0

   P.SetPMAS(6,  1, 175);  // mass of TOP
   P.SetPMAS(25, 1, 180);  // mass of Higgs

   P.SetCKIN(1, 170.0);    // range of allowed mass
   P.SetCKIN(2, 190.0);

   P.SetMSTP(61, 0);   // switch off ISR
   P.SetMSTP(71, 0);   // switch off FSR
   P.SetMSTP(81, 0);   // switch off multiple interactions

   P.SetMSTP(111, 0);  // Switch off fragmentation

   // Force h0 -> ZZ
   for (Int_t i = 210; i <= 288; ++i)
      P.SetMDME(i, 1, 0);
   P.SetMDME(225, 1, 1);

   // Force Z -> mumu
   for (Int_t i = 174; i <= 189; ++i)
      P.SetMDME(i, 1, 0);
   P.SetMDME(184, 1, 1);

   P.Initialize("cms", "p", "p", 14000);

   //========================================================================
   // Create views and containers.
   //========================================================================

   TEveManager::Create();

   TEveElementList *fake_geom = new TEveElementList("Geometry");

   TEveGeoShape *b;

   b = new TEveGeoShape("Barell 1");
   b->SetShape(new TGeoTube(kR_min, kR_max, kZ_d));
   b->SetMainColor(kCyan);
   b->SetMainTransparency(80);
   fake_geom->AddElement(b);

   b = new TEveGeoShape("Barell 2");
   b->SetShape(new TGeoTube(2*kR_min, 2*kR_max, 2*kZ_d));
   b->SetMainColor(kPink-3);
   b->SetMainTransparency(80);
   fake_geom->AddElement(b);

   gEve->AddGlobalElement(fake_geom);

   gMultiView = new MultiView;

   gMultiView->ImportGeomRPhi(fake_geom);
   gMultiView->ImportGeomRhoZ(fake_geom);

   gEve->GetBrowser()->GetTabRight()->SetTab(1);

   gTrackList = new TEveTrackList("Pythia Tracks");
   gTrackList->SetMainColor(kYellow);
   gTrackList->SetMarkerColor(kRed);
   gTrackList->SetMarkerStyle(4);
   gTrackList->SetMarkerSize(0.5);
   gEve->AddElement(gTrackList);

   TEveTrackPropagator* trkProp = gTrackList->GetPropagator();
   trkProp->SetMagField(kMagField);
   trkProp->SetMaxR(2*kR_max);
   trkProp->SetMaxZ(2*kZ_d);

   //========================================================================
   //========================================================================

   pythia_make_gui();
   pythia_next_event();

   gEve->Redraw3D(kTRUE);
}

//==============================================================================
// Next event
//------------------------------------------------------------------------------

void pythia_next_event()
{
   gTrackList->DestroyElements();

   TPythia6& P = * g_pythia;

   P.GenerateEvent();

   int nh = P.GetMSTU(72);

   // printf("N = %d, Nhard = %d :: NumSec = %d, separators (%d,%d,%d,%d)\n",
   //    P.GetN(), nh, P.GetMSTU(70), P.GetMSTU(71), P.GetMSTU(72), P.GetMSTU(73), P.GetMSTU(74));
   //                          2->2                 hard                  postfrag              final

   TEveTrackPropagator *trkProp = gTrackList->GetPropagator();
   TClonesArray        &MC      = * (TClonesArray*) P.GetListOfParticles();
   for (Int_t i = 0; i < 7; ++i)
   {
      TMCParticle& p = * MC[nh+i];
      TParticle pb(p.GetKF(), p.GetKS(), 0, 0,
                   p.GetFirstChild()-nh-1, p.GetLastChild()-nh-1,
                   p.GetPx(), p.GetPy(), p.GetPz(), p.GetEnergy(),
                   p.GetVx(), p.GetVy(), p.GetVz(), p.GetTime());

      TEveTrack* track = new TEveTrack(&pb, i, trkProp);
      track->SetName(Form("%s [%d]", pb.GetName(), i));
      track->SetStdTitle();
      track->SetAttLineAttMarker(gTrackList);
      if (i == 0)
         track->SetLineColor(kColors[0]);
      else if (i <= 2)
         track->SetLineColor(kColors[1]);

      gTrackList->AddElement(track);

      /*
        printf("%d - %d %d %d %d %d %d\n", i,
        p.GetKF(), p.GetKS(), 0, 0,
        p.GetFirstChild()-nh-1, p.GetLastChild()-nh-1);
        printf("%d - %f %f %f %f\n", i,
        p.GetPx(), p.GetPy(), p.GetPz(), p.GetEnergy(),
        printf("%d - %f %f %f %f\n", i,
        p.GetVx(), p.GetVy(), p.GetVz(), p.GetTime());
      */
   }

   gTrackList->MakeTracks();

   TEveElement* top = gEve->GetCurrentEvent();

   gMultiView->DestroyEventRPhi();
   gMultiView->ImportEventRPhi(top);

   gMultiView->DestroyEventRhoZ();
   gMultiView->ImportEventRhoZ(top);

   gEve->Redraw3D();
}

//==============================================================================
// GUI stuff
//------------------------------------------------------------------------------
class EvNavHandler
{
public:
   void Fwd()
   {
      pythia_next_event();
   }
   void Bck()
   {}
};

//______________________________________________________________________________
void pythia_make_gui()
{
   // Create minimal GUI for event navigation.

   TEveBrowser* browser = gEve->GetBrowser();
   browser->StartEmbedding(TRootBrowser::kLeft);

   TGMainFrame* frmMain = new TGMainFrame(gClient->GetRoot(), 1000, 600);
   frmMain->SetWindowName("XX GUI");
   frmMain->SetCleanup(kDeepCleanup);

   TGHorizontalFrame* hf = new TGHorizontalFrame(frmMain);
   {

      TString icondir( Form("%s/icons/", gSystem->Getenv("ROOTSYS")) );
      TGPictureButton* b = 0;
      EvNavHandler    *fh = new EvNavHandler;

      b = new TGPictureButton(hf, gClient->GetPicture(icondir + "GoBack.gif"));
      b->SetEnabled(kFALSE);
      b->SetToolTipText("Go to previous event - not supported.");
      hf->AddFrame(b);
      b->Connect("Clicked()", "EvNavHandler", fh, "Bck()");

      b = new TGPictureButton(hf, gClient->GetPicture(icondir + "GoForward.gif"));
      b->SetToolTipText("Generate new event.");
      hf->AddFrame(b);
      b->Connect("Clicked()", "EvNavHandler", fh, "Fwd()");
   }
   frmMain->AddFrame(hf);

   frmMain->MapSubwindows();
   frmMain->Resize();
   frmMain->MapWindow();

   browser->StopEmbedding();
   browser->SetTabTitle("Event Control", 0);
}
<commit_msg>From Bertrand: Do not try to load libPythia6, as it is a static library on Windoze.<commit_after>//
// Demo showing H -> ZZ -> 4 mu generated by Pythia.
// Requires libPythia6.

//==============================================================================
// Constants.
//------------------------------------------------------------------------------

const Double_t kR_min = 240;
const Double_t kR_max = 250;
const Double_t kZ_d   = 300;

// Solenoid field along z, in Tesla.
const Double_t kMagField = 4;

// Color for Higgs, Zs and muons
const Color_t  kColors[3] = { kRed, kGreen, kYellow };

//==============================================================================
// Global variables.
//------------------------------------------------------------------------------

class TPythia6;
TPythia6   *g_pythia = 0;

// Implemented in MultiView.C
class MultiView;
MultiView* gMultiView = 0;

TEveTrackList *gTrackList = 0;

//==============================================================================
// Forward decalarations of CINT functions.
//------------------------------------------------------------------------------

void pythia_next_event();
void pythia_make_gui();

//==============================================================================
// Main - pythia_display()
//------------------------------------------------------------------------------

void pythia_display()
{
   const TString weh("pythia_display()");

   if (g_pythia != 0)
   {
      Warning(weh, "Already initialized.");
      return;
   }
#ifndef G__WIN32 // libPythia6 is a static library on Windoze
   if (gSystem->Load("libPythia6") < 0)
   {
      Error(weh, "Could not load 'libPythia6', make sure it is available!");
      return;
   }
#endif
   gSystem->Load("libEGPythia6");

   if (gROOT->LoadMacro("MultiView.C+") != 0)
   {
      Error(weh, "Failed loading MultiView.C in compiled mode.");
      return;
   }

   //========================================================================
   //========================================================================

   // Create an instance of the Pythia event generator ...
   g_pythia = new TPythia6;
   TPythia6& P = * g_pythia;

   P.SetMSEL(0);           // full user controll;
   P.SetMSUB(102, 1);      // g + g -> H0
   //P.SetMSUB(123, 1);    // f + f' -> f + f' + H0
   //P.SetMSUB(124, 1);    // f + f' -> f" + f"' + H0

   P.SetPMAS(6,  1, 175);  // mass of TOP
   P.SetPMAS(25, 1, 180);  // mass of Higgs

   P.SetCKIN(1, 170.0);    // range of allowed mass
   P.SetCKIN(2, 190.0);

   P.SetMSTP(61, 0);   // switch off ISR
   P.SetMSTP(71, 0);   // switch off FSR
   P.SetMSTP(81, 0);   // switch off multiple interactions

   P.SetMSTP(111, 0);  // Switch off fragmentation

   // Force h0 -> ZZ
   for (Int_t i = 210; i <= 288; ++i)
      P.SetMDME(i, 1, 0);
   P.SetMDME(225, 1, 1);

   // Force Z -> mumu
   for (Int_t i = 174; i <= 189; ++i)
      P.SetMDME(i, 1, 0);
   P.SetMDME(184, 1, 1);

   P.Initialize("cms", "p", "p", 14000);

   //========================================================================
   // Create views and containers.
   //========================================================================

   TEveManager::Create();

   TEveElementList *fake_geom = new TEveElementList("Geometry");

   TEveGeoShape *b;

   b = new TEveGeoShape("Barell 1");
   b->SetShape(new TGeoTube(kR_min, kR_max, kZ_d));
   b->SetMainColor(kCyan);
   b->SetMainTransparency(80);
   fake_geom->AddElement(b);

   b = new TEveGeoShape("Barell 2");
   b->SetShape(new TGeoTube(2*kR_min, 2*kR_max, 2*kZ_d));
   b->SetMainColor(kPink-3);
   b->SetMainTransparency(80);
   fake_geom->AddElement(b);

   gEve->AddGlobalElement(fake_geom);

   gMultiView = new MultiView;

   gMultiView->ImportGeomRPhi(fake_geom);
   gMultiView->ImportGeomRhoZ(fake_geom);

   gEve->GetBrowser()->GetTabRight()->SetTab(1);

   gTrackList = new TEveTrackList("Pythia Tracks");
   gTrackList->SetMainColor(kYellow);
   gTrackList->SetMarkerColor(kRed);
   gTrackList->SetMarkerStyle(4);
   gTrackList->SetMarkerSize(0.5);
   gEve->AddElement(gTrackList);

   TEveTrackPropagator* trkProp = gTrackList->GetPropagator();
   trkProp->SetMagField(kMagField);
   trkProp->SetMaxR(2*kR_max);
   trkProp->SetMaxZ(2*kZ_d);

   //========================================================================
   //========================================================================

   pythia_make_gui();
   pythia_next_event();

   gEve->Redraw3D(kTRUE);
}

//==============================================================================
// Next event
//------------------------------------------------------------------------------

void pythia_next_event()
{
   gTrackList->DestroyElements();

   TPythia6& P = * g_pythia;

   P.GenerateEvent();

   int nh = P.GetMSTU(72);

   // printf("N = %d, Nhard = %d :: NumSec = %d, separators (%d,%d,%d,%d)\n",
   //    P.GetN(), nh, P.GetMSTU(70), P.GetMSTU(71), P.GetMSTU(72), P.GetMSTU(73), P.GetMSTU(74));
   //                          2->2                 hard                  postfrag              final

   TEveTrackPropagator *trkProp = gTrackList->GetPropagator();
   TClonesArray        &MC      = * (TClonesArray*) P.GetListOfParticles();
   for (Int_t i = 0; i < 7; ++i)
   {
      TMCParticle& p = * MC[nh+i];
      TParticle pb(p.GetKF(), p.GetKS(), 0, 0,
                   p.GetFirstChild()-nh-1, p.GetLastChild()-nh-1,
                   p.GetPx(), p.GetPy(), p.GetPz(), p.GetEnergy(),
                   p.GetVx(), p.GetVy(), p.GetVz(), p.GetTime());

      TEveTrack* track = new TEveTrack(&pb, i, trkProp);
      track->SetName(Form("%s [%d]", pb.GetName(), i));
      track->SetStdTitle();
      track->SetAttLineAttMarker(gTrackList);
      if (i == 0)
         track->SetLineColor(kColors[0]);
      else if (i <= 2)
         track->SetLineColor(kColors[1]);

      gTrackList->AddElement(track);

      /*
        printf("%d - %d %d %d %d %d %d\n", i,
        p.GetKF(), p.GetKS(), 0, 0,
        p.GetFirstChild()-nh-1, p.GetLastChild()-nh-1);
        printf("%d - %f %f %f %f\n", i,
        p.GetPx(), p.GetPy(), p.GetPz(), p.GetEnergy(),
        printf("%d - %f %f %f %f\n", i,
        p.GetVx(), p.GetVy(), p.GetVz(), p.GetTime());
      */
   }

   gTrackList->MakeTracks();

   TEveElement* top = gEve->GetCurrentEvent();

   gMultiView->DestroyEventRPhi();
   gMultiView->ImportEventRPhi(top);

   gMultiView->DestroyEventRhoZ();
   gMultiView->ImportEventRhoZ(top);

   gEve->Redraw3D();
}

//==============================================================================
// GUI stuff
//------------------------------------------------------------------------------
class EvNavHandler
{
public:
   void Fwd()
   {
      pythia_next_event();
   }
   void Bck()
   {}
};

//______________________________________________________________________________
void pythia_make_gui()
{
   // Create minimal GUI for event navigation.

   TEveBrowser* browser = gEve->GetBrowser();
   browser->StartEmbedding(TRootBrowser::kLeft);

   TGMainFrame* frmMain = new TGMainFrame(gClient->GetRoot(), 1000, 600);
   frmMain->SetWindowName("XX GUI");
   frmMain->SetCleanup(kDeepCleanup);

   TGHorizontalFrame* hf = new TGHorizontalFrame(frmMain);
   {

      TString icondir( Form("%s/icons/", gSystem->Getenv("ROOTSYS")) );
      TGPictureButton* b = 0;
      EvNavHandler    *fh = new EvNavHandler;

      b = new TGPictureButton(hf, gClient->GetPicture(icondir + "GoBack.gif"));
      b->SetEnabled(kFALSE);
      b->SetToolTipText("Go to previous event - not supported.");
      hf->AddFrame(b);
      b->Connect("Clicked()", "EvNavHandler", fh, "Bck()");

      b = new TGPictureButton(hf, gClient->GetPicture(icondir + "GoForward.gif"));
      b->SetToolTipText("Generate new event.");
      hf->AddFrame(b);
      b->Connect("Clicked()", "EvNavHandler", fh, "Fwd()");
   }
   frmMain->AddFrame(hf);

   frmMain->MapSubwindows();
   frmMain->Resize();
   frmMain->MapWindow();

   browser->StopEmbedding();
   browser->SetTabTitle("Event Control", 0);
}
<|endoftext|>


<commit_before>/*
  Q Light Controller Plus
  efxitem.cpp

  Copyright (C) Massimo Callegari

  Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

#include <QApplication>
#include <QPainter>
#include <qmath.h>
#include <QDebug>
#include <QMenu>
#include <qmath.h>

#include "efxitem.h"
#include "trackitem.h"
#include "headeritems.h"
#include "audiodecoder.h"

EFXItem::EFXItem(EFX *efx, ShowFunction *func)
    : ShowItem(func)
    , m_efx(efx)
{
    Q_ASSERT(efx != NULL);

    if (func->color().isValid())
        setColor(func->color());
    else
        setColor(ShowFunction::defaultColor(Function::EFX));

    calculateWidth();
    connect(m_efx, SIGNAL(changed(quint32)), this, SLOT(slotEFXChanged(quint32)));
}

void EFXItem::calculateWidth()
{
    int newWidth = 0;
    qint64 efx_duration = m_function->duration();

    if (efx_duration != 0)
        newWidth = ((50/(float)getTimeScale()) * (float)efx_duration) / 1000;
    else
        newWidth = 100;

    if (newWidth < (50 / m_timeScale))
        newWidth = 50 / m_timeScale;
    setWidth(newWidth);
}

void EFXItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(option);
    Q_UNUSED(widget);

    float xpos = 0;
    float timeScale = 50/(float)m_timeScale;
    quint32 efxDuration = m_efx->totalDuration();

    ShowItem::paint(painter, option, widget);

    int loopCount = qFloor(m_function->duration() / efxDuration);
    for (int i = 0; i < loopCount; i++)
    {
        xpos += ((timeScale * (float)efxDuration) / 1000);
        // draw loop vertical delimiter
        painter->setPen(QPen(Qt::white, 1));
        painter->drawLine(xpos, 1, xpos, TRACK_HEIGHT - 5);
    }

    ShowItem::postPaint(painter);
}

void EFXItem::setTimeScale(int val)
{
    ShowItem::setTimeScale(val);
    calculateWidth();
}

void EFXItem::setDuration(quint32 msec, bool stretch)
{
    if (stretch == true)
        m_efx->setDuration(msec);
    else
    {
        if (m_function)
            m_function->setDuration(msec);
        prepareGeometryChange();
        calculateWidth();
        updateTooltip();
    }
}

QString EFXItem::functionName()
{
    if (m_efx)
        return m_efx->name();
    return QString();
}

EFX *EFXItem::getEFX()
{
    return m_efx;
}

void EFXItem::slotEFXChanged(quint32)
{
    prepareGeometryChange();
    if (m_function)
        m_function->setDuration(m_efx->totalDuration());
    calculateWidth();
    updateTooltip();
}

void EFXItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *)
{
    QMenu menu;
    QFont menuFont = qApp->font();
    menuFont.setPixelSize(14);
    menu.setFont(menuFont);

    foreach(QAction *action, getDefaultActions())
        menu.addAction(action);

    menu.exec(QCursor::pos());
}
<commit_msg>Fix crash reported in http://www.qlcplus.org/forum/viewtopic.php?f=5&t=9543<commit_after>/*
  Q Light Controller Plus
  efxitem.cpp

  Copyright (C) Massimo Callegari

  Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

#include <QApplication>
#include <QPainter>
#include <qmath.h>
#include <QDebug>
#include <QMenu>
#include <qmath.h>

#include "efxitem.h"
#include "trackitem.h"
#include "headeritems.h"
#include "audiodecoder.h"

EFXItem::EFXItem(EFX *efx, ShowFunction *func)
    : ShowItem(func)
    , m_efx(efx)
{
    Q_ASSERT(efx != NULL);

    if (func->color().isValid())
        setColor(func->color());
    else
        setColor(ShowFunction::defaultColor(Function::EFX));

    calculateWidth();
    connect(m_efx, SIGNAL(changed(quint32)), this, SLOT(slotEFXChanged(quint32)));
}

void EFXItem::calculateWidth()
{
    int newWidth = 0;
    qint64 efx_duration = m_function->duration();

    if (efx_duration != 0)
        newWidth = ((50/(float)getTimeScale()) * (float)efx_duration) / 1000;
    else
        newWidth = 100;

    if (newWidth < (50 / m_timeScale))
        newWidth = 50 / m_timeScale;
    setWidth(newWidth);
}

void EFXItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(option);
    Q_UNUSED(widget);

    float xpos = 0;
    float timeScale = 50/(float)m_timeScale;
    quint32 efxDuration = m_efx->totalDuration();

    ShowItem::paint(painter, option, widget);

    int loopCount = (efxDuration == 0) ? 0 : qFloor(m_function->duration() / efxDuration);
    for (int i = 0; i < loopCount; i++)
    {
        xpos += ((timeScale * (float)efxDuration) / 1000);
        // draw loop vertical delimiter
        painter->setPen(QPen(Qt::white, 1));
        painter->drawLine(xpos, 1, xpos, TRACK_HEIGHT - 5);
    }

    ShowItem::postPaint(painter);
}

void EFXItem::setTimeScale(int val)
{
    ShowItem::setTimeScale(val);
    calculateWidth();
}

void EFXItem::setDuration(quint32 msec, bool stretch)
{
    if (stretch == true)
        m_efx->setDuration(msec);
    else
    {
        if (m_function)
            m_function->setDuration(msec);
        prepareGeometryChange();
        calculateWidth();
        updateTooltip();
    }
}

QString EFXItem::functionName()
{
    if (m_efx)
        return m_efx->name();
    return QString();
}

EFX *EFXItem::getEFX()
{
    return m_efx;
}

void EFXItem::slotEFXChanged(quint32)
{
    prepareGeometryChange();
    if (m_function)
        m_function->setDuration(m_efx->totalDuration());
    calculateWidth();
    updateTooltip();
}

void EFXItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *)
{
    QMenu menu;
    QFont menuFont = qApp->font();
    menuFont.setPixelSize(14);
    menu.setFont(menuFont);

    foreach(QAction *action, getDefaultActions())
        menu.addAction(action);

    menu.exec(QCursor::pos());
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: salbmp.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: pluby $ $Date: 2000-12-31 20:54:10 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#define _SV_SALBMP_CXX

#ifndef _SV_SALBMP_HXX
#include <salbmp.hxx>
#endif
#ifndef _SV_SALBTYPE_HXX
#include <salbtype.hxx>
#endif

// ==================================================================

SalBitmap::SalBitmap() :
        mhPixMap( 0 ),
        mnBitCount( 0 )
{
}

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

SalBitmap::~SalBitmap()
{
    Destroy();
}

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

BOOL SalBitmap::Create( const Size& rSize, USHORT nBitCount, const BitmapPalette& rPal )
{
    maSize = rSize;
    mnBitCount = nBitCount;
    return TRUE;
}

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

BOOL SalBitmap::Create( const SalBitmap& rSalBitmap )
{
    maSize = rSalBitmap.maSize;
    mnBitCount = 1;
    return TRUE;
}

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

BOOL SalBitmap::Create( const SalBitmap& rSalBmp, SalGraphics* pGraphics )
{
    maSize = rSalBmp.maSize;
    mnBitCount = rSalBmp.mnBitCount;
    return TRUE;
}

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

BOOL SalBitmap::Create( const SalBitmap& rSalBmp, USHORT nNewBitCount )
{
    maSize = rSalBmp.maSize;
    mnBitCount = nNewBitCount;
    return TRUE;
}

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

void SalBitmap::Destroy()
{
    maSize = Size();
    mnBitCount = 0;
}

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

BitmapBuffer* SalBitmap::AcquireBuffer( BOOL bReadOnly )
{
    BitmapBuffer *pBuffer = new BitmapBuffer();

    // Stub code: we have not yet written any interfaces to native bitmaps.
    pBuffer->mnFormat = BMP_FORMAT_BOTTOM_UP | BMP_FORMAT_1BIT_MSB_PAL;
    pBuffer->mnWidth = maSize.Width();
    pBuffer->mnHeight = maSize.Height();
    pBuffer->mnScanlineSize = AlignedWidth4Bytes( pBuffer->mnWidth * mnBitCount );
    pBuffer->mnFormat |= BMP_FORMAT_16BIT_TC_MASK;
    pBuffer->maColorMask = ColorMask( 0x7b00, 0x03e0, 0x001f);
    pBuffer->mpBits = new BYTE[ pBuffer->mnScanlineSize * pBuffer->mnHeight ];

    return pBuffer;
}

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

void SalBitmap::ReleaseBuffer( BitmapBuffer* pBuffer, BOOL bReadOnly )
{
    delete pBuffer;
}
<commit_msg>Initial implementation of SalBitmap class. At this time, only 32 bit pixel depth is supported.<commit_after>/*************************************************************************
 *
 *  $RCSfile: salbmp.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: pluby $ $Date: 2001-01-05 21:18: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): _______________________________________
 *
 *
 ************************************************************************/

#define _SV_SALBMP_CXX

#ifndef _SV_SALBMP_HXX
#include <salbmp.hxx>
#endif
#ifndef _SV_SALBTYPE_HXX
#include <salbtype.hxx>
#endif
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SALVD_HXX
#include <salvd.hxx>
#endif

// ==================================================================

SalBitmap::SalBitmap() :
        mpVirDev( 0 ),
        mnBitCount( 0 )
{
}

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

SalBitmap::~SalBitmap()
{
    Destroy();
}

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

BOOL SalBitmap::Create( const Size& rSize, USHORT nBitCount, const BitmapPalette& rPal )
{
    ImplSVData* pSVData = ImplGetSVData();
    BOOL bRet = FALSE;

    // Stub code: we can only handle 32 bit pixel depth's right now
    nBitCount = 32;

    if ( rSize.Width() && rSize.Height() )
    {
        // Create a SalVirtualDevice
        mpVirDev = pSVData->mpDefInst->CreateVirtualDevice( NULL,
            rSize.Width(), rSize.Height(), nBitCount );

        if ( mpVirDev )
        {
            mnBitCount = nBitCount;
            maSize = rSize;
            bRet = TRUE;
        }
    }

    return bRet;
}

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

BOOL SalBitmap::Create( const SalBitmap& rSalBmp )
{
    BOOL bRet = FALSE;

    if ( Create( rSalBmp, rSalBmp.mnBitCount ) )
        bRet = TRUE;

    return bRet;
}

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

BOOL SalBitmap::Create( const SalBitmap& rSalBmp, SalGraphics* pGraphics )
{
    return Create( rSalBmp );
}

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

BOOL SalBitmap::Create( const SalBitmap& rSalBmp, USHORT nNewBitCount )
{
    BOOL bRet = FALSE;

    if ( Create( rSalBmp.maSize, nNewBitCount, BitmapPalette() ) )
    {
        // Not yet implemented: Copy pixels from rSalBmp.mpVirDev to mpVirDev

        bRet = TRUE;
    }

    return bRet;
}

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

void SalBitmap::Destroy()
{
    ImplSVData* pSVData = ImplGetSVData();

    if ( mpVirDev )
        pSVData->mpDefInst->DestroyVirtualDevice( mpVirDev );

    maSize = Size();
    mnBitCount = 0;
}

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

BitmapBuffer* SalBitmap::AcquireBuffer( BOOL bReadOnly )
{
    BitmapBuffer *pBuffer = NULL;

    if ( mpVirDev )
    {
        // Get the SalGraphics which contains the GWorld we will draw to
        SalGraphics *pGraphics = GetGraphics();

        if ( pGraphics && pGraphics->maGraphicsData.mpCGrafPort )
        {
            PixMapHandle hPixMap = NULL;

            hPixMap = GetPortPixMap( pGraphics->maGraphicsData.mpCGrafPort );

            if ( hPixMap )
            {
                pBuffer = new BitmapBuffer();

                // Lock the GWorld so that the calling functions can write to
                // this buffer
                LockPortBits( pGraphics->maGraphicsData.mpCGrafPort );

                pBuffer->mnBitCount = (**hPixMap).pixelSize;
                pBuffer->mnWidth = mpVirDev->maVirDevData.mnWidth;
                pBuffer->mnHeight = mpVirDev->maVirDevData.mnHeight;
                pBuffer->mnBitCount = (**hPixMap).pixelSize;
                pBuffer->mnScanlineSize = GetPixRowBytes( hPixMap );
                pBuffer->mpBits = (BYTE *)GetPixBaseAddr( hPixMap );
                pBuffer->mnFormat = BMP_FORMAT_TOP_DOWN | BMP_FORMAT_32BIT_TC_MASK;
            }

            // Release the SalGraphics so that others can get a handle to it
            // in future GetGraphics() calls
            ReleaseGraphics( pGraphics );
        }
    }

    return pBuffer;
}

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

void SalBitmap::ReleaseBuffer( BitmapBuffer* pBuffer, BOOL bReadOnly )
{
    SalGraphics *pGraphics = NULL;

    if ( mpVirDev )
    {
        // Get the SalGraphics which contains the GWorld we used as the buffer
        SalGraphics *pGraphics = GetGraphics();

        if ( pGraphics && pGraphics->maGraphicsData.mpCGrafPort )
        {
            // Unlock the GWorld so that this GWorld can be reused
            UnlockPortBits( pGraphics->maGraphicsData.mpCGrafPort );

            // Release the SalGraphics so that others can get a handle to it
            // in future GetGraphics() calls
            ReleaseGraphics( pGraphics );
        }
    }

    if ( pBuffer )
        delete pBuffer;
}

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

SalGraphics* SalBitmap::GetGraphics()
{
    if ( mpVirDev )
        return mpVirDev->GetGraphics();
    else
        return NULL;
}

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

void SalBitmap::ReleaseGraphics( SalGraphics* pGraphics )
{
    if ( mpVirDev )
        mpVirDev->ReleaseGraphics( pGraphics );
}

<|endoftext|>


<commit_before><commit_msg>Don't use uninitialized ImplSplitItem::mnPixSize<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: syschild.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 12:21:44 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"

#ifndef _SV_SVSYS_HXX
#include <svsys.h>
#endif
#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#include <window.hxx>
#ifndef _SV_SALOBJ_HXX
#include <salobj.hxx>
#endif

#ifndef _SV_RC_H
#include <tools/rc.h>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _SV_WIDNOW_H
#include <window.h>
#endif
#ifndef _SV_SVAPP_HXX
#include <svapp.hxx>
#endif
#ifndef _SV_SYSCHILD_HXX
#include <syschild.hxx>
#endif

// =======================================================================

long ImplSysChildProc( void* pInst, SalObject* /* pObject */,
                       USHORT nEvent, const void* /* pEvent */ )
{
    SystemChildWindow* pWindow = (SystemChildWindow*)pInst;
    long nRet = 0;

    ImplDelData aDogTag( pWindow );
    switch ( nEvent )
    {
        case SALOBJ_EVENT_GETFOCUS:
            // Focus holen und zwar so, das alle Handler gerufen
            // werden, als ob dieses Fenster den Focus bekommt,
            // ohne das der Frame den Focus wieder klaut
            pWindow->ImplGetFrameData()->mbSysObjFocus = TRUE;
            pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = TRUE;
            pWindow->ToTop( TOTOP_NOGRABFOCUS );
            if( aDogTag.IsDead() )
                break;
            pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = FALSE;
            pWindow->ImplGetFrameData()->mbInSysObjFocusHdl = TRUE;
            pWindow->GrabFocus();
            if( aDogTag.IsDead() )
                break;
            pWindow->ImplGetFrameData()->mbInSysObjFocusHdl = FALSE;
            break;

        case SALOBJ_EVENT_LOSEFOCUS:
            // Hintenrum einen LoseFocus ausloesen, das der Status
            // der Fenster dem entsprechenden Activate-Status
            // entspricht
            pWindow->ImplGetFrameData()->mbSysObjFocus = FALSE;
            if ( !pWindow->ImplGetFrameData()->mnFocusId )
            {
                pWindow->ImplGetFrameData()->mbStartFocusState = TRUE;
                Application::PostUserEvent( pWindow->ImplGetFrameData()->mnFocusId, LINK( pWindow->ImplGetFrameWindow(), Window, ImplAsyncFocusHdl ) );
            }
            break;

        case SALOBJ_EVENT_TOTOP:
            pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = TRUE;
            if ( !Application::GetFocusWindow() || pWindow->HasChildPathFocus() )
                pWindow->ToTop( TOTOP_NOGRABFOCUS );
            else
                pWindow->ToTop();
            if( aDogTag.IsDead() )
                break;
            pWindow->GrabFocus();
            if( aDogTag.IsDead() )
                break;
            pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = FALSE;
            break;
    }

    return nRet;
}

// =======================================================================

void SystemChildWindow::ImplInitSysChild( Window* pParent, WinBits nStyle, SystemWindowData *pData )
{
    mpWindowImpl->mpSysObj = ImplGetSVData()->mpDefInst->CreateObject( pParent->ImplGetFrame(), pData );

    Window::ImplInit( pParent, nStyle, NULL );

    // Wenn es ein richtiges SysChild ist, dann painten wir auch nicht
    if ( GetSystemData() )
    {
        mpWindowImpl->mpSysObj->SetCallback( this, ImplSysChildProc );
        SetParentClipMode( PARENTCLIPMODE_CLIP );
        SetBackground();
    }
}

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

SystemChildWindow::SystemChildWindow( Window* pParent, WinBits nStyle ) :
    Window( WINDOW_SYSTEMCHILDWINDOW )
{
    ImplInitSysChild( pParent, nStyle, NULL );
}

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

SystemChildWindow::SystemChildWindow( Window* pParent, WinBits nStyle, SystemWindowData *pData ) :
    Window( WINDOW_SYSTEMCHILDWINDOW )
{
    ImplInitSysChild( pParent, nStyle, pData );
}

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

SystemChildWindow::SystemChildWindow( Window* pParent, const ResId& rResId ) :
    Window( WINDOW_SYSTEMCHILDWINDOW )
{
    rResId.SetRT( RSC_WINDOW );
    WinBits nStyle = ImplInitRes( rResId );
    ImplInitSysChild( pParent, nStyle, NULL );
    ImplLoadRes( rResId );

    if ( !(nStyle & WB_HIDE) )
        Show();
}

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

SystemChildWindow::~SystemChildWindow()
{
    Hide();
    if ( mpWindowImpl->mpSysObj )
    {
        ImplGetSVData()->mpDefInst->DestroyObject( mpWindowImpl->mpSysObj );
        mpWindowImpl->mpSysObj = NULL;
    }
}

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

const SystemEnvData* SystemChildWindow::GetSystemData() const
{
    if ( mpWindowImpl->mpSysObj )
        return mpWindowImpl->mpSysObj->GetSystemData();
    else
        return NULL;
}

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

void SystemChildWindow::EnableEraseBackground( BOOL bEnable )
{
    if ( mpWindowImpl->mpSysObj )
        mpWindowImpl->mpSysObj->EnableEraseBackground( bEnable );
}

BOOL SystemChildWindow::IsEraseBackgroundEnabled()
{
    if ( mpWindowImpl->mpSysObj )
        return mpWindowImpl->mpSysObj->IsEraseBackgroundEnabled();
    else
        return FALSE;
}
<commit_msg>INTEGRATION: CWS vgbugs07 (1.9.240); FILE MERGED 2007/06/04 13:29:48 vg 1.9.240.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: syschild.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 20:34:11 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"

#ifndef _SV_SVSYS_HXX
#include <svsys.h>
#endif
#ifndef _SV_SALINST_HXX
#include <vcl/salinst.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <vcl/salframe.hxx>
#endif
#include <vcl/window.hxx>
#ifndef _SV_SALOBJ_HXX
#include <vcl/salobj.hxx>
#endif

#ifndef _SV_RC_H
#include <tools/rc.h>
#endif
#ifndef _SV_SVDATA_HXX
#include <vcl/svdata.hxx>
#endif
#ifndef _SV_WIDNOW_H
#include <window.h>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SV_SYSCHILD_HXX
#include <vcl/syschild.hxx>
#endif

// =======================================================================

long ImplSysChildProc( void* pInst, SalObject* /* pObject */,
                       USHORT nEvent, const void* /* pEvent */ )
{
    SystemChildWindow* pWindow = (SystemChildWindow*)pInst;
    long nRet = 0;

    ImplDelData aDogTag( pWindow );
    switch ( nEvent )
    {
        case SALOBJ_EVENT_GETFOCUS:
            // Focus holen und zwar so, das alle Handler gerufen
            // werden, als ob dieses Fenster den Focus bekommt,
            // ohne das der Frame den Focus wieder klaut
            pWindow->ImplGetFrameData()->mbSysObjFocus = TRUE;
            pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = TRUE;
            pWindow->ToTop( TOTOP_NOGRABFOCUS );
            if( aDogTag.IsDead() )
                break;
            pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = FALSE;
            pWindow->ImplGetFrameData()->mbInSysObjFocusHdl = TRUE;
            pWindow->GrabFocus();
            if( aDogTag.IsDead() )
                break;
            pWindow->ImplGetFrameData()->mbInSysObjFocusHdl = FALSE;
            break;

        case SALOBJ_EVENT_LOSEFOCUS:
            // Hintenrum einen LoseFocus ausloesen, das der Status
            // der Fenster dem entsprechenden Activate-Status
            // entspricht
            pWindow->ImplGetFrameData()->mbSysObjFocus = FALSE;
            if ( !pWindow->ImplGetFrameData()->mnFocusId )
            {
                pWindow->ImplGetFrameData()->mbStartFocusState = TRUE;
                Application::PostUserEvent( pWindow->ImplGetFrameData()->mnFocusId, LINK( pWindow->ImplGetFrameWindow(), Window, ImplAsyncFocusHdl ) );
            }
            break;

        case SALOBJ_EVENT_TOTOP:
            pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = TRUE;
            if ( !Application::GetFocusWindow() || pWindow->HasChildPathFocus() )
                pWindow->ToTop( TOTOP_NOGRABFOCUS );
            else
                pWindow->ToTop();
            if( aDogTag.IsDead() )
                break;
            pWindow->GrabFocus();
            if( aDogTag.IsDead() )
                break;
            pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = FALSE;
            break;
    }

    return nRet;
}

// =======================================================================

void SystemChildWindow::ImplInitSysChild( Window* pParent, WinBits nStyle, SystemWindowData *pData )
{
    mpWindowImpl->mpSysObj = ImplGetSVData()->mpDefInst->CreateObject( pParent->ImplGetFrame(), pData );

    Window::ImplInit( pParent, nStyle, NULL );

    // Wenn es ein richtiges SysChild ist, dann painten wir auch nicht
    if ( GetSystemData() )
    {
        mpWindowImpl->mpSysObj->SetCallback( this, ImplSysChildProc );
        SetParentClipMode( PARENTCLIPMODE_CLIP );
        SetBackground();
    }
}

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

SystemChildWindow::SystemChildWindow( Window* pParent, WinBits nStyle ) :
    Window( WINDOW_SYSTEMCHILDWINDOW )
{
    ImplInitSysChild( pParent, nStyle, NULL );
}

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

SystemChildWindow::SystemChildWindow( Window* pParent, WinBits nStyle, SystemWindowData *pData ) :
    Window( WINDOW_SYSTEMCHILDWINDOW )
{
    ImplInitSysChild( pParent, nStyle, pData );
}

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

SystemChildWindow::SystemChildWindow( Window* pParent, const ResId& rResId ) :
    Window( WINDOW_SYSTEMCHILDWINDOW )
{
    rResId.SetRT( RSC_WINDOW );
    WinBits nStyle = ImplInitRes( rResId );
    ImplInitSysChild( pParent, nStyle, NULL );
    ImplLoadRes( rResId );

    if ( !(nStyle & WB_HIDE) )
        Show();
}

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

SystemChildWindow::~SystemChildWindow()
{
    Hide();
    if ( mpWindowImpl->mpSysObj )
    {
        ImplGetSVData()->mpDefInst->DestroyObject( mpWindowImpl->mpSysObj );
        mpWindowImpl->mpSysObj = NULL;
    }
}

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

const SystemEnvData* SystemChildWindow::GetSystemData() const
{
    if ( mpWindowImpl->mpSysObj )
        return mpWindowImpl->mpSysObj->GetSystemData();
    else
        return NULL;
}

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

void SystemChildWindow::EnableEraseBackground( BOOL bEnable )
{
    if ( mpWindowImpl->mpSysObj )
        mpWindowImpl->mpSysObj->EnableEraseBackground( bEnable );
}

BOOL SystemChildWindow::IsEraseBackgroundEnabled()
{
    if ( mpWindowImpl->mpSysObj )
        return mpWindowImpl->mpSysObj->IsEraseBackgroundEnabled();
    else
        return FALSE;
}
<|endoftext|>