<commit_before>// Copyright (c) 2010 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 "media/tools/player_x11/gles_video_renderer.h"

#include <dlfcn.h>
#include <X11/Xutil.h>
#include <X11/extensions/Xrender.h>
#include <X11/extensions/Xcomposite.h>

#include "media/base/buffers.h"
#include "media/base/pipeline.h"
#include "media/base/filter_host.h"
#include "media/base/yuv_convert.h"

GlesVideoRenderer* GlesVideoRenderer::instance_ = NULL;

GlesVideoRenderer::GlesVideoRenderer(Display* display, Window window)
    : display_(display),
      window_(window),
      new_frame_(false),
      egl_display_(NULL),
      egl_surface_(NULL),
      egl_context_(NULL) {
}

GlesVideoRenderer::~GlesVideoRenderer() {
}

// static
bool GlesVideoRenderer::IsMediaFormatSupported(
    const media::MediaFormat& media_format) {
  int width = 0;
  int height = 0;
  return ParseMediaFormat(media_format, &width, &height);
}

void GlesVideoRenderer::OnStop() {
  // TODO(hclam): Context switching seems to be broek so the following
  // calls may fail. Need to fix them.
  eglMakeCurrent(egl_display_, EGL_NO_SURFACE,
                 EGL_NO_SURFACE, EGL_NO_CONTEXT);
  eglDestroyContext(egl_display_, egl_context_);
  eglDestroySurface(egl_display_, egl_surface_);
}

// Matrix used for the YUV to RGB conversion.
static const float kYUV2RGB[9] = {
  1.f, 1.f, 1.f,
  0.f, -.344f, 1.772f,
  1.403f, -.714f, 0.f,
};

// Vertices for a full screen quad.
static const float kVertices[8] = {
  -1.f, 1.f,
  -1.f, -1.f,
  1.f, 1.f,
  1.f, -1.f,
};

// Texture Coordinates mapping the entire texture.
static const float kTextureCoords[8] = {
  0, 0,
  0, 1,
  1, 0,
  1, 1,
};

// Pass-through vertex shader.
static const char kVertexShader[] =
    "precision highp float; precision highp int;\n"
    "varying vec2 interp_tc;\n"
    "\n"
    "attribute vec4 in_pos;\n"
    "attribute vec2 in_tc;\n"
    "\n"
    "void main() {\n"
    "  interp_tc = in_tc;\n"
    "  gl_Position = in_pos;\n"
    "}\n";

// YUV to RGB pixel shader. Loads a pixel from each plane and pass through the
// matrix.
static const char kFragmentShader[] =
    "precision mediump float; precision mediump int;\n"
    "varying vec2 interp_tc;\n"
    "\n"
    "uniform sampler2D y_tex;\n"
    "uniform sampler2D u_tex;\n"
    "uniform sampler2D v_tex;\n"
    "uniform mat3 yuv2rgb;\n"
    "\n"
    "void main() {\n"
    "  float y = texture2D(y_tex, interp_tc).x;\n"
    "  float u = texture2D(u_tex, interp_tc).r - .5;\n"
    "  float v = texture2D(v_tex, interp_tc).r - .5;\n"
    "  vec3 rgb = yuv2rgb * vec3(y, u, v);\n"
    "  gl_FragColor = vec4(rgb, 1);\n"
    "}\n";

// Buffer size for compile errors.
static const unsigned int kErrorSize = 4096;

bool GlesVideoRenderer::OnInitialize(media::VideoDecoder* decoder) {
  if (!ParseMediaFormat(decoder->media_format(), &width_, &height_))
    return false;

  LOG(INFO) << "Initializing GLES Renderer...";

  // Save this instance.
  DCHECK(!instance_);
  instance_ = this;
  return true;
}

void GlesVideoRenderer::OnFrameAvailable() {
  AutoLock auto_lock(lock_);
  new_frame_ = true;
}

void GlesVideoRenderer::Paint() {
  // Use |new_frame_| to prevent overdraw since Paint() is called more
  // often than needed. It is OK to lock only this flag and we don't
  // want to lock the whole function because this method takes a long
  // time to complete.
  {
    AutoLock auto_lock(lock_);
    if (!new_frame_)
      return;
    new_frame_ = false;
  }

  // Initialize GLES here to avoid context switching. Some drivers doesn't
  // like switching context between threads.
  static bool initialized = false;
  if (!initialized && !InitializeGles()) {
    initialized = true;
    host()->SetError(media::PIPELINE_ERROR_COULD_NOT_RENDER);
    return;
  }
  initialized = true;

  scoped_refptr<media::VideoFrame> video_frame;
  GetCurrentFrame(&video_frame);

  if (!video_frame)
    return;

  // Convert YUV frame to RGB.
  media::VideoSurface frame_in;
  if (video_frame->Lock(&frame_in)) {
    DCHECK(frame_in.format == media::VideoSurface::YV12 ||
           frame_in.format == media::VideoSurface::YV16);
    DCHECK(frame_in.strides[media::VideoSurface::kUPlane] ==
           frame_in.strides[media::VideoSurface::kVPlane]);
    DCHECK(frame_in.planes == media::VideoSurface::kNumYUVPlanes);

    for (unsigned int i = 0; i < media::VideoSurface::kNumYUVPlanes; ++i) {
      unsigned int width = (i == media::VideoSurface::kYPlane) ?
          frame_in.width : frame_in.width / 2;
      unsigned int height = (i == media::VideoSurface::kYPlane ||
                             frame_in.format == media::VideoSurface::YV16) ?
          frame_in.height : frame_in.height / 2;
      glActiveTexture(GL_TEXTURE0 + i);
      // No GL_UNPACK_ROW_LENGTH in GLES2.
      // glPixelStorei(GL_UNPACK_ROW_LENGTH, frame_in.strides[i]);
      glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, width, height, 0,
                   GL_LUMINANCE, GL_UNSIGNED_BYTE, frame_in.data[i]);
    }
    video_frame->Unlock();
  } else {
    NOTREACHED();
  }

  glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
  eglSwapBuffers(egl_display_, egl_surface_);
}

bool GlesVideoRenderer::InitializeGles() {
  // Resize the window to fit that of the video.
  XResizeWindow(display_, window_, width_, height_);

  egl_display_ = eglGetDisplay(display_);
  if (eglGetError() != EGL_SUCCESS) {
    DLOG(ERROR) << "eglGetDisplay failed.";
    return false;
  }

  EGLint major;
  EGLint minor;
  if (!eglInitialize(egl_display_, &major, &minor)) {
    DLOG(ERROR) << "eglInitialize failed.";
    return false;
  }
  DLOG(INFO) << "EGL vendor:" << eglQueryString(egl_display_, EGL_VENDOR);
  DLOG(INFO) << "EGL version:" << eglQueryString(egl_display_, EGL_VERSION);
  DLOG(INFO) << "EGL extensions:"
             << eglQueryString(egl_display_, EGL_EXTENSIONS);
  DLOG(INFO) << "EGL client apis:"
             << eglQueryString(egl_display_, EGL_CLIENT_APIS);

  EGLint attribs[] = {
    EGL_RED_SIZE,       5,
    EGL_GREEN_SIZE,     6,
    EGL_BLUE_SIZE,      5,
    EGL_DEPTH_SIZE,     16,
    EGL_STENCIL_SIZE,   0,
    EGL_SURFACE_TYPE,   EGL_WINDOW_BIT,
    EGL_NONE
  };

  EGLint num_configs = -1;
  if (!eglGetConfigs(egl_display_, NULL, 0, &num_configs)) {
    DLOG(ERROR) << "eglGetConfigs failed.";
    return false;
  }

  EGLConfig config;
  if (!eglChooseConfig(egl_display_, attribs, &config, 1, &num_configs)) {
    DLOG(ERROR) << "eglChooseConfig failed.";
    return false;
  }

  EGLint red_size, green_size, blue_size, alpha_size, depth_size, stencil_size;
  eglGetConfigAttrib(egl_display_, config, EGL_RED_SIZE, &red_size);
  eglGetConfigAttrib(egl_display_, config, EGL_GREEN_SIZE, &green_size);
  eglGetConfigAttrib(egl_display_, config, EGL_BLUE_SIZE, &blue_size);
  eglGetConfigAttrib(egl_display_, config, EGL_ALPHA_SIZE, &alpha_size);
  eglGetConfigAttrib(egl_display_, config, EGL_DEPTH_SIZE, &depth_size);
  eglGetConfigAttrib(egl_display_, config, EGL_STENCIL_SIZE, &stencil_size);
  DLOG(INFO) << "R,G,B,A: " << red_size << "," << green_size
             << "," << blue_size << "," << alpha_size << " bits";
  DLOG(INFO) << "Depth: " << depth_size << " bits, Stencil:" << stencil_size
             << "bits";

  egl_surface_ = eglCreateWindowSurface(egl_display_, config, window_, NULL);
  if (!egl_surface_) {
    DLOG(ERROR) << "eglCreateWindowSurface failed.";
    return false;
  }

  egl_context_ = eglCreateContext(egl_display_, config, NULL, NULL);
  if (!egl_context_) {
    DLOG(ERROR) << "eglCreateContext failed.";
    eglDestroySurface(egl_display_, egl_surface_);
    return false;
  }

  if (eglMakeCurrent(egl_display_, egl_surface_,
                     egl_surface_, egl_context_) == EGL_FALSE) {
    eglDestroyContext(egl_display_, egl_context_);
    eglDestroySurface(egl_display_, egl_surface_);
    egl_display_ = NULL;
    egl_surface_ = NULL;
    egl_context_ = NULL;
    return false;
  }

  EGLint width;
  EGLint height;
  eglQuerySurface(egl_display_, egl_surface_, EGL_WIDTH, &width);
  eglQuerySurface(egl_display_, egl_surface_, EGL_HEIGHT, &height);
  glViewport(0, 0, width_, height_);

  // Create 3 textures, one for each plane, and bind them to different
  // texture units.
  glGenTextures(media::VideoSurface::kNumYUVPlanes, textures_);

  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, textures_[0]);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glEnable(GL_TEXTURE_2D);

  glActiveTexture(GL_TEXTURE1);
  glBindTexture(GL_TEXTURE_2D, textures_[1]);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glEnable(GL_TEXTURE_2D);

  glActiveTexture(GL_TEXTURE2);
  glBindTexture(GL_TEXTURE_2D, textures_[2]);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glEnable(GL_TEXTURE_2D);

  GLuint program_ = glCreateProgram();

  // Create our YUV->RGB shader.
  GLuint vertex_shader_ = glCreateShader(GL_VERTEX_SHADER);
  const char* vs_source = kVertexShader;
  int vs_size = sizeof(kVertexShader);
  glShaderSource(vertex_shader_, 1, &vs_source, &vs_size);
  glCompileShader(vertex_shader_);
  int result = GL_FALSE;
  glGetShaderiv(vertex_shader_, GL_COMPILE_STATUS, &result);
  if (!result) {
    char log[kErrorSize];
    int len;
    glGetShaderInfoLog(vertex_shader_, kErrorSize - 1, &len, log);
    log[kErrorSize - 1] = 0;
    LOG(FATAL) << log;
  }
  glAttachShader(program_, vertex_shader_);

  GLuint fragment_shader_ = glCreateShader(GL_FRAGMENT_SHADER);
  const char* ps_source = kFragmentShader;
  int ps_size = sizeof(kFragmentShader);
  glShaderSource(fragment_shader_, 1, &ps_source, &ps_size);
  glCompileShader(fragment_shader_);
  result = GL_FALSE;
  glGetShaderiv(fragment_shader_, GL_COMPILE_STATUS, &result);
  if (!result) {
    char log[kErrorSize];
    int len;
    glGetShaderInfoLog(fragment_shader_, kErrorSize - 1, &len, log);
    log[kErrorSize - 1] = 0;
    LOG(FATAL) << log;
  }
  glAttachShader(program_, fragment_shader_);

  glLinkProgram(program_);
  result = GL_FALSE;
  glGetProgramiv(program_, GL_LINK_STATUS, &result);
  if (!result) {
    char log[kErrorSize];
    int len;
    glGetProgramInfoLog(program_, kErrorSize - 1, &len, log);
    log[kErrorSize - 1] = 0;
    LOG(FATAL) << log;
  }
  glUseProgram(program_);

  // Bind parameters.
  glUniform1i(glGetUniformLocation(program_, "y_tex"), 0);
  glUniform1i(glGetUniformLocation(program_, "u_tex"), 1);
  glUniform1i(glGetUniformLocation(program_, "v_tex"), 2);
  int yuv2rgb_location = glGetUniformLocation(program_, "yuv2rgb");
  glUniformMatrix3fv(yuv2rgb_location, 1, GL_FALSE, kYUV2RGB);

  int pos_location = glGetAttribLocation(program_, "in_pos");
  glEnableVertexAttribArray(pos_location);
  glVertexAttribPointer(pos_location, 2, GL_FLOAT, GL_FALSE, 0, kVertices);

  int tc_location = glGetAttribLocation(program_, "in_tc");
  glEnableVertexAttribArray(tc_location);
  glVertexAttribPointer(tc_location, 2, GL_FLOAT, GL_FALSE, 0,
                        kTextureCoords);

  // We are getting called on a thread. Release the context so that it can be
  // made current on the main thread.
  // TODO(hclam): Fix this if neccessary. Currently the following call fails
  // for some drivers.
  // eglMakeCurrent(egl_display_, EGL_NO_SURFACE,
  //                EGL_NO_SURFACE, EGL_NO_CONTEXT);
  return true;
}
<commit_msg>gles2: fix stride support<commit_after>// Copyright (c) 2010 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 "media/tools/player_x11/gles_video_renderer.h"

#include <dlfcn.h>
#include <X11/Xutil.h>
#include <X11/extensions/Xrender.h>
#include <X11/extensions/Xcomposite.h>

#include "media/base/buffers.h"
#include "media/base/pipeline.h"
#include "media/base/filter_host.h"
#include "media/base/yuv_convert.h"

GlesVideoRenderer* GlesVideoRenderer::instance_ = NULL;

GlesVideoRenderer::GlesVideoRenderer(Display* display, Window window)
    : display_(display),
      window_(window),
      new_frame_(false),
      egl_display_(NULL),
      egl_surface_(NULL),
      egl_context_(NULL) {
}

GlesVideoRenderer::~GlesVideoRenderer() {
}

// static
bool GlesVideoRenderer::IsMediaFormatSupported(
    const media::MediaFormat& media_format) {
  int width = 0;
  int height = 0;
  return ParseMediaFormat(media_format, &width, &height);
}

void GlesVideoRenderer::OnStop() {
  // TODO(hclam): Context switching seems to be broek so the following
  // calls may fail. Need to fix them.
  eglMakeCurrent(egl_display_, EGL_NO_SURFACE,
                 EGL_NO_SURFACE, EGL_NO_CONTEXT);
  eglDestroyContext(egl_display_, egl_context_);
  eglDestroySurface(egl_display_, egl_surface_);
}

// Matrix used for the YUV to RGB conversion.
static const float kYUV2RGB[9] = {
  1.f, 1.f, 1.f,
  0.f, -.344f, 1.772f,
  1.403f, -.714f, 0.f,
};

// Vertices for a full screen quad.
static const float kVertices[8] = {
  -1.f, 1.f,
  -1.f, -1.f,
  1.f, 1.f,
  1.f, -1.f,
};

// Texture Coordinates mapping the entire texture.
static const float kTextureCoords[8] = {
  0, 0,
  0, 1,
  1, 0,
  1, 1,
};

// Pass-through vertex shader.
static const char kVertexShader[] =
    "precision highp float; precision highp int;\n"
    "varying vec2 interp_tc;\n"
    "\n"
    "attribute vec4 in_pos;\n"
    "attribute vec2 in_tc;\n"
    "\n"
    "void main() {\n"
    "  interp_tc = in_tc;\n"
    "  gl_Position = in_pos;\n"
    "}\n";

// YUV to RGB pixel shader. Loads a pixel from each plane and pass through the
// matrix.
static const char kFragmentShader[] =
    "precision mediump float; precision mediump int;\n"
    "varying vec2 interp_tc;\n"
    "\n"
    "uniform sampler2D y_tex;\n"
    "uniform sampler2D u_tex;\n"
    "uniform sampler2D v_tex;\n"
    "uniform mat3 yuv2rgb;\n"
    "\n"
    "void main() {\n"
    "  float y = texture2D(y_tex, interp_tc).x;\n"
    "  float u = texture2D(u_tex, interp_tc).r - .5;\n"
    "  float v = texture2D(v_tex, interp_tc).r - .5;\n"
    "  vec3 rgb = yuv2rgb * vec3(y, u, v);\n"
    "  gl_FragColor = vec4(rgb, 1);\n"
    "}\n";

// Buffer size for compile errors.
static const unsigned int kErrorSize = 4096;

bool GlesVideoRenderer::OnInitialize(media::VideoDecoder* decoder) {
  if (!ParseMediaFormat(decoder->media_format(), &width_, &height_))
    return false;

  LOG(INFO) << "Initializing GLES Renderer...";

  // Save this instance.
  DCHECK(!instance_);
  instance_ = this;
  return true;
}

void GlesVideoRenderer::OnFrameAvailable() {
  AutoLock auto_lock(lock_);
  new_frame_ = true;
}

void GlesVideoRenderer::Paint() {
  // Use |new_frame_| to prevent overdraw since Paint() is called more
  // often than needed. It is OK to lock only this flag and we don't
  // want to lock the whole function because this method takes a long
  // time to complete.
  {
    AutoLock auto_lock(lock_);
    if (!new_frame_)
      return;
    new_frame_ = false;
  }

  // Initialize GLES here to avoid context switching. Some drivers doesn't
  // like switching context between threads.
  static bool initialized = false;
  if (!initialized && !InitializeGles()) {
    initialized = true;
    host()->SetError(media::PIPELINE_ERROR_COULD_NOT_RENDER);
    return;
  }
  initialized = true;

  scoped_refptr<media::VideoFrame> video_frame;
  GetCurrentFrame(&video_frame);

  if (!video_frame)
    return;

  // Convert YUV frame to RGB.
  media::VideoSurface frame_in;
  if (video_frame->Lock(&frame_in)) {
    DCHECK(frame_in.format == media::VideoSurface::YV12 ||
           frame_in.format == media::VideoSurface::YV16);
    DCHECK(frame_in.strides[media::VideoSurface::kUPlane] ==
           frame_in.strides[media::VideoSurface::kVPlane]);
    DCHECK(frame_in.planes == media::VideoSurface::kNumYUVPlanes);

    for (unsigned int i = 0; i < media::VideoSurface::kNumYUVPlanes; ++i) {
      unsigned int width = (i == media::VideoSurface::kYPlane) ?
          frame_in.width : frame_in.width / 2;
      unsigned int height = (i == media::VideoSurface::kYPlane ||
                             frame_in.format == media::VideoSurface::YV16) ?
          frame_in.height : frame_in.height / 2;
      glActiveTexture(GL_TEXTURE0 + i);
      // GLES2 supports a fixed set of unpack alignments that should match most
      // of the time what ffmpeg outputs.
      // TODO(piman): check if it is more efficient to prefer higher
      // alignments.
      unsigned int stride = frame_in.strides[i];
      uint8* data = frame_in.data[i];
      if (stride == width) {
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
      } else if (stride == ((width + 1) & ~1)) {
        glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
      } else if (stride == ((width + 3) & ~3)) {
        glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
      } else if (stride == ((width + 7) & ~7)) {
        glPixelStorei(GL_UNPACK_ALIGNMENT, 8);
      } else {
        // Otherwise do it line-by-line.
        glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, width, height, 0,
                     GL_LUMINANCE, GL_UNSIGNED_BYTE, NULL);
        for (unsigned int y = 0; y < height; ++y) {
          glTexSubImage2D(GL_TEXTURE_2D, 0, 0, y, width, 1,
                          GL_LUMINANCE, GL_UNSIGNED_BYTE, data);
          data += stride;
        }
        continue;
      }
      glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, width, height, 0,
                   GL_LUMINANCE, GL_UNSIGNED_BYTE, data);
    }
    video_frame->Unlock();
  } else {
    NOTREACHED();
  }

  glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
  eglSwapBuffers(egl_display_, egl_surface_);
}

bool GlesVideoRenderer::InitializeGles() {
  // Resize the window to fit that of the video.
  XResizeWindow(display_, window_, width_, height_);

  egl_display_ = eglGetDisplay(display_);
  if (eglGetError() != EGL_SUCCESS) {
    DLOG(ERROR) << "eglGetDisplay failed.";
    return false;
  }

  EGLint major;
  EGLint minor;
  if (!eglInitialize(egl_display_, &major, &minor)) {
    DLOG(ERROR) << "eglInitialize failed.";
    return false;
  }
  DLOG(INFO) << "EGL vendor:" << eglQueryString(egl_display_, EGL_VENDOR);
  DLOG(INFO) << "EGL version:" << eglQueryString(egl_display_, EGL_VERSION);
  DLOG(INFO) << "EGL extensions:"
             << eglQueryString(egl_display_, EGL_EXTENSIONS);
  DLOG(INFO) << "EGL client apis:"
             << eglQueryString(egl_display_, EGL_CLIENT_APIS);

  EGLint attribs[] = {
    EGL_RED_SIZE,       5,
    EGL_GREEN_SIZE,     6,
    EGL_BLUE_SIZE,      5,
    EGL_DEPTH_SIZE,     16,
    EGL_STENCIL_SIZE,   0,
    EGL_SURFACE_TYPE,   EGL_WINDOW_BIT,
    EGL_NONE
  };

  EGLint num_configs = -1;
  if (!eglGetConfigs(egl_display_, NULL, 0, &num_configs)) {
    DLOG(ERROR) << "eglGetConfigs failed.";
    return false;
  }

  EGLConfig config;
  if (!eglChooseConfig(egl_display_, attribs, &config, 1, &num_configs)) {
    DLOG(ERROR) << "eglChooseConfig failed.";
    return false;
  }

  EGLint red_size, green_size, blue_size, alpha_size, depth_size, stencil_size;
  eglGetConfigAttrib(egl_display_, config, EGL_RED_SIZE, &red_size);
  eglGetConfigAttrib(egl_display_, config, EGL_GREEN_SIZE, &green_size);
  eglGetConfigAttrib(egl_display_, config, EGL_BLUE_SIZE, &blue_size);
  eglGetConfigAttrib(egl_display_, config, EGL_ALPHA_SIZE, &alpha_size);
  eglGetConfigAttrib(egl_display_, config, EGL_DEPTH_SIZE, &depth_size);
  eglGetConfigAttrib(egl_display_, config, EGL_STENCIL_SIZE, &stencil_size);
  DLOG(INFO) << "R,G,B,A: " << red_size << "," << green_size
             << "," << blue_size << "," << alpha_size << " bits";
  DLOG(INFO) << "Depth: " << depth_size << " bits, Stencil:" << stencil_size
             << "bits";

  egl_surface_ = eglCreateWindowSurface(egl_display_, config, window_, NULL);
  if (!egl_surface_) {
    DLOG(ERROR) << "eglCreateWindowSurface failed.";
    return false;
  }

  egl_context_ = eglCreateContext(egl_display_, config, NULL, NULL);
  if (!egl_context_) {
    DLOG(ERROR) << "eglCreateContext failed.";
    eglDestroySurface(egl_display_, egl_surface_);
    return false;
  }

  if (eglMakeCurrent(egl_display_, egl_surface_,
                     egl_surface_, egl_context_) == EGL_FALSE) {
    eglDestroyContext(egl_display_, egl_context_);
    eglDestroySurface(egl_display_, egl_surface_);
    egl_display_ = NULL;
    egl_surface_ = NULL;
    egl_context_ = NULL;
    return false;
  }

  EGLint width;
  EGLint height;
  eglQuerySurface(egl_display_, egl_surface_, EGL_WIDTH, &width);
  eglQuerySurface(egl_display_, egl_surface_, EGL_HEIGHT, &height);
  glViewport(0, 0, width_, height_);

  // Create 3 textures, one for each plane, and bind them to different
  // texture units.
  glGenTextures(media::VideoSurface::kNumYUVPlanes, textures_);

  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, textures_[0]);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glEnable(GL_TEXTURE_2D);

  glActiveTexture(GL_TEXTURE1);
  glBindTexture(GL_TEXTURE_2D, textures_[1]);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glEnable(GL_TEXTURE_2D);

  glActiveTexture(GL_TEXTURE2);
  glBindTexture(GL_TEXTURE_2D, textures_[2]);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glEnable(GL_TEXTURE_2D);

  GLuint program_ = glCreateProgram();

  // Create our YUV->RGB shader.
  GLuint vertex_shader_ = glCreateShader(GL_VERTEX_SHADER);
  const char* vs_source = kVertexShader;
  int vs_size = sizeof(kVertexShader);
  glShaderSource(vertex_shader_, 1, &vs_source, &vs_size);
  glCompileShader(vertex_shader_);
  int result = GL_FALSE;
  glGetShaderiv(vertex_shader_, GL_COMPILE_STATUS, &result);
  if (!result) {
    char log[kErrorSize];
    int len;
    glGetShaderInfoLog(vertex_shader_, kErrorSize - 1, &len, log);
    log[kErrorSize - 1] = 0;
    LOG(FATAL) << log;
  }
  glAttachShader(program_, vertex_shader_);

  GLuint fragment_shader_ = glCreateShader(GL_FRAGMENT_SHADER);
  const char* ps_source = kFragmentShader;
  int ps_size = sizeof(kFragmentShader);
  glShaderSource(fragment_shader_, 1, &ps_source, &ps_size);
  glCompileShader(fragment_shader_);
  result = GL_FALSE;
  glGetShaderiv(fragment_shader_, GL_COMPILE_STATUS, &result);
  if (!result) {
    char log[kErrorSize];
    int len;
    glGetShaderInfoLog(fragment_shader_, kErrorSize - 1, &len, log);
    log[kErrorSize - 1] = 0;
    LOG(FATAL) << log;
  }
  glAttachShader(program_, fragment_shader_);

  glLinkProgram(program_);
  result = GL_FALSE;
  glGetProgramiv(program_, GL_LINK_STATUS, &result);
  if (!result) {
    char log[kErrorSize];
    int len;
    glGetProgramInfoLog(program_, kErrorSize - 1, &len, log);
    log[kErrorSize - 1] = 0;
    LOG(FATAL) << log;
  }
  glUseProgram(program_);

  // Bind parameters.
  glUniform1i(glGetUniformLocation(program_, "y_tex"), 0);
  glUniform1i(glGetUniformLocation(program_, "u_tex"), 1);
  glUniform1i(glGetUniformLocation(program_, "v_tex"), 2);
  int yuv2rgb_location = glGetUniformLocation(program_, "yuv2rgb");
  glUniformMatrix3fv(yuv2rgb_location, 1, GL_FALSE, kYUV2RGB);

  int pos_location = glGetAttribLocation(program_, "in_pos");
  glEnableVertexAttribArray(pos_location);
  glVertexAttribPointer(pos_location, 2, GL_FLOAT, GL_FALSE, 0, kVertices);

  int tc_location = glGetAttribLocation(program_, "in_tc");
  glEnableVertexAttribArray(tc_location);
  glVertexAttribPointer(tc_location, 2, GL_FLOAT, GL_FALSE, 0,
                        kTextureCoords);

  // We are getting called on a thread. Release the context so that it can be
  // made current on the main thread.
  // TODO(hclam): Fix this if neccessary. Currently the following call fails
  // for some drivers.
  // eglMakeCurrent(egl_display_, EGL_NO_SURFACE,
  //                EGL_NO_SURFACE, EGL_NO_CONTEXT);
  return true;
}
<|endoftext|>


<commit_before>// -*- c-basic-offset: 2; related-file-name: "" -*-
/*
 * @(#)$Id$
 *
 *
 * This file is distributed under the terms in the attached LICENSE file.
 * If you do not find this file, copies can be found by writing to:
 * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300,
 * Berkeley, CA, 94704.  Attention:  Intel License Inquiry.
 * Or
 * UC Berkeley EECS Computer Science Division, 387 Soda Hall #1776,
 * Berkeley, CA,  94707. Attention: P2 Group.
 *
 * DESCRIPTION: Overlog based on new planner
 *
 */

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

#include "ol_lexer.h"
#include "ol_context.h"
#include "eca_context.h"
#include "localize_context.h"
#include "plmb_confgen.h"
#include "tableStore.h"
#include "udp.h"
#include "planner.h"
#include "ruleStrand.h"

#include "dot.h"

extern int ol_parser_debug;

int main(int argc, char **argv)
{
  LoggerI::Level level = LoggerI::NONE;
  PlumberPtr plumber(new Plumber(level));
  std::cout << "TestPlanner\n";
  boost::shared_ptr< OL_Context > ctxt(new OL_Context());
  bool route = false;
  bool builtin = false;
  string filename("");

  //PlumberPtr plumber(new Plumber());

  for( int i=1; i<argc; i++) {
    std::string arg(argv[i]);

    if (arg == "-d") {
      ol_parser_debug = 1;
    } else if (arg == "-h") {
      std::cerr << "Usage: " << argv[0] << "{option|filename}+\n"
		<< "\t-c: canonical form (used for builtin tests)\n"
		<< "\t-d: turn on parser debugging\n"
		<< "\t-r: try to instantiate a plumber config\n"
                << "\t-g: produce a DOT graph spec\n"
		<< "\t-h: print this help text\n"
		<< "\t- : read from stdin\n";
      exit(0);
    } else if (arg == "-c") {
      builtin = true;
    } else if (arg == "-r") {
      route = true;
      builtin = false;
    } else if (arg == "-") {
      ctxt->parse_stream(&std::cin);
    } else if (arg == "-g") {

      Plumber::DataflowPtr conf(new Plumber::Dataflow("overlog"));
      filename = argv[i+1];
      std::ifstream istr(filename.c_str());
      ctxt->parse_stream(&istr);

      boost::shared_ptr< TableStore > tableStore(new TableStore(ctxt.get()));
      tableStore->initTables();

      boost::shared_ptr< Localize_Context > lctxt(new Localize_Context());
      lctxt->rewrite(ctxt.get(), tableStore.get());

      boost::shared_ptr< ECA_Context > ectxt(new ECA_Context());
      ectxt->rewrite(lctxt.get(), tableStore.get());

      boost::shared_ptr< Planner > planner(new Planner(conf, tableStore.get(), false, "127.0.0.1:10000", "0"));
      boost::shared_ptr< Udp > udp(new Udp("Udp", 10000));

      std::vector<RuleStrand*>
      ruleStrands = planner->generateRuleStrands(ectxt);

      planner->setupNetwork(udp);
      planner->registerAllRuleStrands(ruleStrands);

      if (plumber->install(conf) == 0) {
        std::cout << "Correctly initialized network of reachability flows.\n";
      } else {
        std::cout << "** Failed to initialize correct spec\n";
      }
      plumber->toDot("overlog.dot");
      exit (0);
    } else {
      filename = argv[i];
      std::ifstream istr(argv[i]);
      ctxt->parse_stream(&istr);
      }
  }

  if (builtin) {
    std::cerr << ctxt->toString();
    std::cerr.flush();
    std::cout << "OK\n";
    std::cout.flush();
  }

  std::cout << "Finish parsing (functors / tableInfos) "
	    << ctxt->getRules()->size()
	    << " " << ctxt->getTableInfos()->size() << "\n";

  std::cout << ctxt->toString() << "\n";

  if (route) {
    Plumber::DataflowPtr conf(new Plumber::Dataflow("overlog"));
    boost::shared_ptr< TableStore > tableStore(new TableStore(ctxt.get()));
    tableStore->initTables();

    FILE* strandOutput = fopen((filename + ".strand").c_str(), "w");
    FILE* ecaOutput = fopen((filename + ".eca").c_str(), "w");
    FILE* localOutput = fopen((filename + ".local").c_str(), "w");

    boost::shared_ptr< Localize_Context > lctxt(new Localize_Context());
    lctxt->rewrite(ctxt.get(), tableStore.get());
    fprintf(localOutput, lctxt->toString().c_str());
    fclose(localOutput);

    boost::shared_ptr< ECA_Context > ectxt(new ECA_Context());
    ectxt->rewrite(lctxt.get(), tableStore.get());
    fprintf(ecaOutput, lctxt->toString().c_str());
    fclose(ecaOutput);

    boost::shared_ptr< Planner > planner(new Planner(conf, tableStore.get(), false, "127.0.0.1:10000", "0"));
    boost::shared_ptr< Udp > udp(new Udp("Udp", 10000));
    std::vector<RuleStrand*> ruleStrands = planner->generateRuleStrands(ectxt);

    for (unsigned k = 0; k < ruleStrands.size(); k++) {
      std::cout << ruleStrands.at(k)->toString();
      fprintf(strandOutput, ruleStrands.at(k)->toString().c_str());
    }
    fclose(strandOutput);

    planner->setupNetwork(udp);
    planner->registerAllRuleStrands(ruleStrands);
    std::cout << planner->getNetPlanner()->toString() << "\n";

    if (plumber->install(conf) == 0) {
      std::cout << "Correctly initialized network of reachability flows.\n";
    } else {
      std::cout << "** Failed to initialize correct spec\n";
    }
    std::cout << "Done.\n";

  }

  return 0;
}
<commit_msg>overlog with new planner<commit_after>// -*- c-basic-offset: 2; related-file-name: "" -*-
/*
 * @(#)$Id$
 *
 *
 * This file is distributed under the terms in the attached LICENSE file.
 * If you do not find this file, copies can be found by writing to:
 * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300,
 * Berkeley, CA, 94704.  Attention:  Intel License Inquiry.
 * Or
 * UC Berkeley EECS Computer Science Division, 387 Soda Hall #1776,
 * Berkeley, CA,  94707. Attention: P2 Group.
 *
 * DESCRIPTION: Overlog based on new planner
 *
 */

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

#include "ol_lexer.h"
#include "ol_context.h"
#include "eca_context.h"
#include "localize_context.h"
#include "plmb_confgen.h"
#include "tableStore.h"
#include "udp.h"
#include "planner.h"
#include "ruleStrand.h"

#include "dot.h"

extern int ol_parser_debug;

int main(int argc, char **argv)
{
  LoggerI::Level level = LoggerI::NONE;
  PlumberPtr plumber(new Plumber(level));
  std::cout << "TestPlanner\n";
  boost::shared_ptr< OL_Context > ctxt(new OL_Context());
  bool route = false;
  bool builtin = false;
  string filename("");

  //PlumberPtr plumber(new Plumber());

  for( int i=1; i<argc; i++) {
    std::string arg(argv[i]);

    if (arg == "-d") {
      ol_parser_debug = 1;
    } else if (arg == "-h") {
      std::cerr << "Usage: " << argv[0] << "{option|filename}+\n"
		<< "\t-c: canonical form (used for builtin tests)\n"
		<< "\t-d: turn on parser debugging\n"
		<< "\t-r: try to instantiate a plumber config\n"
                << "\t-g: produce a DOT graph spec\n"
		<< "\t-h: print this help text\n"
		<< "\t- : read from stdin\n";
      exit(0);
    } else if (arg == "-c") {
      builtin = true;
    } else if (arg == "-r") {
      route = true;
      builtin = false;
    } else if (arg == "-") {
      ctxt->parse_stream(&std::cin);
    } else if (arg == "-g") {

      Plumber::DataflowPtr conf(new Plumber::Dataflow("overlog"));
      filename = argv[i+1];
      std::ifstream istr(filename.c_str());
      ctxt->parse_stream(&istr);

      boost::shared_ptr< TableStore > tableStore(new TableStore(ctxt.get()));
      tableStore->initTables();

      boost::shared_ptr< Localize_Context > lctxt(new Localize_Context());
      lctxt->rewrite(ctxt.get(), tableStore.get());

      boost::shared_ptr< ECA_Context > ectxt(new ECA_Context());
      ectxt->rewrite(lctxt.get(), tableStore.get());

      boost::shared_ptr< Planner > planner(new Planner(conf, tableStore.get(), false, "127.0.0.1:10000", "0"));
      boost::shared_ptr< Udp > udp(new Udp("Udp", 12345));

      std::vector<RuleStrand*>
      ruleStrands = planner->generateRuleStrands(ectxt);

      planner->setupNetwork(udp);
      planner->registerAllRuleStrands(ruleStrands);

      if (plumber->install(conf) == 0) {
        std::cout << "Correctly initialized network of reachability flows.\n";
      } else {
        std::cout << "** Failed to initialize correct spec\n";
      }
      plumber->toDot("overlog.dot");
      exit (0);
    } else {
      filename = argv[i];
      std::ifstream istr(argv[i]);
      ctxt->parse_stream(&istr);
      }
  }

  if (builtin) {
    std::cerr << ctxt->toString();
    std::cerr.flush();
    std::cout << "OK\n";
    std::cout.flush();
  }

  std::cout << "Finish parsing (functors / tableInfos) "
	    << ctxt->getRules()->size()
	    << " " << ctxt->getTableInfos()->size() << "\n";

  std::cout << ctxt->toString() << "\n";

  if (route) {
    Plumber::DataflowPtr conf(new Plumber::Dataflow("overlog"));
    boost::shared_ptr< TableStore > tableStore(new TableStore(ctxt.get()));
    tableStore->initTables();

    FILE* strandOutput = fopen((filename + ".strand").c_str(), "w");
    FILE* ecaOutput = fopen((filename + ".eca").c_str(), "w");
    FILE* localOutput = fopen((filename + ".local").c_str(), "w");

    boost::shared_ptr< Localize_Context > lctxt(new Localize_Context());
    lctxt->rewrite(ctxt.get(), tableStore.get());
    fprintf(localOutput, lctxt->toString().c_str());
    fclose(localOutput);

    boost::shared_ptr< ECA_Context > ectxt(new ECA_Context());
    ectxt->rewrite(lctxt.get(), tableStore.get());
    fprintf(ecaOutput, ectxt->toString().c_str());
    fclose(ecaOutput);

    boost::shared_ptr< Planner > planner(new Planner(conf, tableStore.get(), false, "127.0.0.1:10000", "0"));
    boost::shared_ptr< Udp > udp(new Udp("Udp", 12345));
    std::vector<RuleStrand*> ruleStrands = planner->generateRuleStrands(ectxt);

    for (unsigned k = 0; k < ruleStrands.size(); k++) {
      std::cout << ruleStrands.at(k)->toString();
      fprintf(strandOutput, ruleStrands.at(k)->toString().c_str());
    }
    fclose(strandOutput);

    planner->setupNetwork(udp);
    planner->registerAllRuleStrands(ruleStrands);
    std::cout << planner->getNetPlanner()->toString() << "\n";

    if (plumber->install(conf) == 0) {
      std::cout << "Correctly initialized network of reachability flows.\n";
    } else {
      std::cout << "** Failed to initialize correct spec\n";
    }
    std::cout << "Done.\n";

  }

  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2018-2019 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// Created by tom on 2/11/18.
//

<commit_msg>[Cleanup][Tests] Remove crazy useful unittest created by "Tom"<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <map>

#include <TROOT.h>
#include <TFile.h>
#include <TTree.h>
#include <TString.h>

#include "kTracker/SRawEvent.h"
#include "kTracker/SRecEvent.h"

#include "DataStruct.h"

using namespace std;

int main(int argc, char* argv[])
{
    //name of the TTree
    TString treename = argv[3];

    // input data structure
    SRecEvent* recEvent = new SRecEvent;

    TFile* dataFile = new TFile(argv[1], "READ");
    TTree* dataTree = (TTree*)dataFile->Get(treename.Data());

    dataTree->SetBranchAddress("recEvent", &recEvent);

    //check if raw event exists
    bool mcdata = false;
    bool mixdata = treename.Contains("mix") || treename.Contains("pp") || treename.Contains("mm");
    SRawEvent* rawEvent;
    SRawMCEvent* rawMCEvent;
    if(dataTree->FindBranch("rawEvent") != NULL)
    {
        if(TString(dataTree->FindBranch("rawEvent")->GetClassName()) == "SRawMCEvent")
        {
            rawMCEvent = new SRawMCEvent;
            dataTree->SetBranchAddress("rawEvent", &rawMCEvent);
            mcdata = true;
        }
        else
        {
            rawEvent = new SRawEvent;
            dataTree->SetBranchAddress("rawEvent", &rawEvent);
        }
    }

    // output data structure
    Dimuon* p_dimuon = new Dimuon; Dimuon& dimuon = *p_dimuon;
    Spill* p_spill = new Spill; Spill& spill = *p_spill;
    Event* p_event = new Event; Event& event = *p_event;
    Track* p_posTrack = new Track; Track& posTrack = *p_posTrack;
    Track* p_negTrack = new Track; Track& negTrack = *p_negTrack;

    TFile* saveFile = new TFile(argv[2], "recreate");
    TTree* saveTree = new TTree("save", "save");

    saveTree->Branch("dimuon", &p_dimuon, 256000, 99);
    saveTree->Branch("event", &p_event, 256000, 99);
    saveTree->Branch("spill", &p_spill, 256000, 99);
    saveTree->Branch("posTrack", &p_posTrack, 256000, 99);
    saveTree->Branch("negTrack", &p_negTrack, 256000, 99);

    //Initialize spill information accordingly
    spill.skipflag = mcdata || mixdata;
    map<int, Spill> spillBank;
    if(!spill.skipflag && argc > 4)
    {
        TFile* spillFile = new TFile(argv[4]);
        TTree* spillTree = (TTree*)spillFile->Get("save");

        spillTree->SetBranchAddress("spill", &p_spill);

        for(int i = 0; i < spillTree->GetEntries(); ++i)
        {
            spillTree->GetEntry(i);
            spillBank.insert(map<int, Spill>::value_type(spill.spillID, spill));
        }
    }

    //start reading data
    int nDimuons = 0;
    double x_dummy, y_dummy, z_dummy;
    bool badSpillFlag = false;
    for(int i = 0; i < dataTree->GetEntries(); ++i)
    {
        dataTree->GetEntry(i);
        if(i % 1000 == 0)
        {
            cout << "Converting " << i << "/" << dataTree->GetEntries() << endl;
        }

        //general event level info
        event.runID = recEvent->getRunID();
        event.spillID = recEvent->getSpillID();
        event.eventID = recEvent->getEventID();
        event.status = recEvent->getRecStatus();
        if(mcdata)
        {
            event.MATRIX1 = rawMCEvent->isEmuTriggered() ? 1 : -1;
            event.weight = rawMCEvent->weight;
            event.intensity = 1.;
        }
        else if(mixdata)
        {
            event.MATRIX1 = 1;
            event.weight = 1.;
            event.intensity = 1.;
        }
        else
        {
            event.MATRIX1 = recEvent->isTriggeredBy(SRawEvent::MATRIX1) ? 1 : -1;
            event.weight = 1.;
            event.intensity = rawEvent->getIntensity();
        }

        //spill level information
        if(!spill.skipflag && event.spillID != spill.spillID)
        {
            badSpillFlag = false;
            if(!spillBank.empty())
            {
                if(spillBank.find(recEvent->getSpillID()) == spillBank.end())
                {
                    event.log("spillID does not exist!");
                    badSpillFlag = true;
                }
                else
                {
                    spill = spillBank[recEvent->getSpillID()];
                }
            }
        }
        else
        {
            spill.spillID = recEvent->getSpillID();
            spill.targetPos = recEvent->getTargetPos();
            spill.TARGPOS_CONTROL = recEvent->getTargetPos();
        }
        if(badSpillFlag) continue;

        for(int j = 0; j < recEvent->getNDimuons(); ++j)
        {
            ++nDimuons;
            SRecDimuon recDimuon = recEvent->getDimuon(j);

            dimuon.dimuonID = nDimuons;
            dimuon.posTrackID = recDimuon.trackID_pos;
            dimuon.negTrackID = recDimuon.trackID_neg;
            dimuon.px1 = recDimuon.p_pos.Px();
            dimuon.py1 = recDimuon.p_pos.Py();
            dimuon.pz1 = recDimuon.p_pos.Pz();
            dimuon.px2 = recDimuon.p_neg.Px();
            dimuon.py2 = recDimuon.p_neg.Py();
            dimuon.pz2 = recDimuon.p_neg.Pz();
            dimuon.dx  = recDimuon.vtx.X();
            dimuon.dy  = recDimuon.vtx.Y();
            dimuon.dz  = recDimuon.vtx.Z();
            dimuon.dpx = dimuon.px1 + dimuon.px2;
            dimuon.dpy = dimuon.py1 + dimuon.py2;
            dimuon.dpz = dimuon.pz1 + dimuon.pz2;
            dimuon.mass  = recDimuon.mass;
            dimuon.xF    = recDimuon.xF;
            dimuon.x1    = recDimuon.x1;
            dimuon.x2    = recDimuon.x2;
            dimuon.pT    = recDimuon.pT;
            dimuon.costh = recDimuon.costh;
            dimuon.phi   = recDimuon.phi;
            dimuon.chisq_dimuon    = recDimuon.chisq_kf;
            dimuon.trackSeparation = recDimuon.vtx_pos.Z() - recDimuon.vtx_neg.Z();

            //if(!dimuon.goodDimuon()) continue;
            if(dimuon.mass < 0.5 || dimuon.mass > 10. || dimuon.chisq_dimuon > 25. || dimuon.x1 < 0. || dimuon.x1 > 1.
               || dimuon.x2 < 0. || dimuon.x2 > 1. || dimuon.xF < -1. || dimuon.xF > 1. || fabs(dimuon.dx) > 2.
               || fabs(dimuon.dy) > 2. || dimuon.dz < -300. || dimuon.dz > 300. || fabs(dimuon.dpx) > 3.
               || fabs(dimuon.dpy) > 3. || dimuon.dpz < 30. || dimuon.dpz > 120. || fabs(dimuon.trackSeparation) > 300.) continue;

            SRecTrack recPosTrack = recEvent->getTrack(dimuon.posTrackID);
            posTrack.trackID   = recDimuon.trackID_pos;
            posTrack.charge    = 1;
            posTrack.nHits     = recPosTrack.getNHits();
            posTrack.nHitsSt1  = recPosTrack.getNHitsInStation(1);
            posTrack.nHitsSt2  = recPosTrack.getNHitsInStation(2);
            posTrack.nHitsSt3  = recPosTrack.getNHitsInStation(3);
            posTrack.nHitsSt4H = recPosTrack.getNHitsInPTY();
            posTrack.nHitsSt4V = recPosTrack.getNHitsInPTX();
            posTrack.chisq        = recPosTrack.getChisq();
            posTrack.chisq_dump   = recPosTrack.getChisqDump();
            posTrack.chisq_target = recPosTrack.getChisqTarget();
            posTrack.chisq_upstream = recPosTrack.getChisqUpstream();
            recPosTrack.getExpPositionFast(600., x_dummy, y_dummy);
            posTrack.x1 = x_dummy;
            posTrack.y1 = y_dummy;
            posTrack.z1 = 600.;
            recPosTrack.getExpPositionFast(1910., x_dummy, y_dummy);
            posTrack.x3 = x_dummy;
            posTrack.y3 = y_dummy;
            posTrack.z3 = 1910.;
            posTrack.x0 = recPosTrack.getVtxPar(0);
            posTrack.y0 = recPosTrack.getVtxPar(1);
            posTrack.z0 = recPosTrack.getVtxPar(2);
            posTrack.xT = recPosTrack.getTargetPos().X();
            posTrack.yT = recPosTrack.getTargetPos().Y();
            posTrack.zT = recPosTrack.getTargetPos().Z();
            posTrack.xD = recPosTrack.getDumpPos().X();
            posTrack.yD = recPosTrack.getDumpPos().Y();
            posTrack.zD = recPosTrack.getDumpPos().Z();
            recPosTrack.getExpMomentumFast(600., x_dummy, y_dummy, z_dummy);
            posTrack.px1 = x_dummy;
            posTrack.py1 = y_dummy;
            posTrack.pz1 = z_dummy;
            recPosTrack.getExpMomentumFast(1910., x_dummy, y_dummy, z_dummy);
            posTrack.px3 = x_dummy;
            posTrack.py3 = y_dummy;
            posTrack.pz3 = z_dummy;
            recPosTrack.getMomentumVertex(x_dummy, y_dummy, z_dummy);
            posTrack.px0 = x_dummy;
            posTrack.py0 = y_dummy;
            posTrack.pz0 = z_dummy;
            posTrack.pxT = recPosTrack.getTargetMom().X();
            posTrack.pyT = recPosTrack.getTargetMom().Y();
            posTrack.pzT = recPosTrack.getTargetMom().Z();
            posTrack.pxD = recPosTrack.getDumpMom().X();
            posTrack.pyD = recPosTrack.getDumpMom().Y();
            posTrack.pzD = recPosTrack.getDumpMom().Z();
            posTrack.roadID = recPosTrack.getTriggerRoad();
            posTrack.tx_PT  = recPosTrack.getPTSlopeX();
            posTrack.ty_PT  = recPosTrack.getPTSlopeY();
            posTrack.thbend = atan(posTrack.px3/posTrack.pz3) - atan(posTrack.px1/posTrack.pz1);
            posTrack.pxv = recDimuon.p_pos.Px();
            posTrack.pyv = recDimuon.p_pos.Py();
            posTrack.pzv = recDimuon.p_pos.Pz();

            SRecTrack recNegTrack = recEvent->getTrack(dimuon.negTrackID);
            negTrack.trackID   = recDimuon.trackID_neg;
            negTrack.charge    = 1;
            negTrack.nHits     = recNegTrack.getNHits();
            negTrack.nHitsSt1  = recNegTrack.getNHitsInStation(1);
            negTrack.nHitsSt2  = recNegTrack.getNHitsInStation(2);
            negTrack.nHitsSt3  = recNegTrack.getNHitsInStation(3);
            negTrack.nHitsSt4H = recNegTrack.getNHitsInPTY();
            negTrack.nHitsSt4V = recNegTrack.getNHitsInPTX();
            negTrack.chisq        = recNegTrack.getChisq();
            negTrack.chisq_dump   = recNegTrack.getChisqDump();
            negTrack.chisq_target = recNegTrack.getChisqTarget();
            negTrack.chisq_upstream = recNegTrack.getChisqUpstream();
            recNegTrack.getExpPositionFast(600., x_dummy, y_dummy);
            negTrack.x1 = x_dummy;
            negTrack.y1 = y_dummy;
            negTrack.z1 = 600.;
            recNegTrack.getExpPositionFast(1910., x_dummy, y_dummy);
            negTrack.x3 = x_dummy;
            negTrack.y3 = y_dummy;
            negTrack.z3 = 1910.;
            negTrack.x0 = recNegTrack.getVtxPar(0);
            negTrack.y0 = recNegTrack.getVtxPar(1);
            negTrack.z0 = recNegTrack.getVtxPar(2);
            negTrack.xT = recNegTrack.getTargetPos().X();
            negTrack.yT = recNegTrack.getTargetPos().Y();
            negTrack.zT = recNegTrack.getTargetPos().Z();
            negTrack.xD = recNegTrack.getDumpPos().X();
            negTrack.yD = recNegTrack.getDumpPos().Y();
            negTrack.zD = recNegTrack.getDumpPos().Z();
            recNegTrack.getExpMomentumFast(600., x_dummy, y_dummy, z_dummy);
            negTrack.px1 = x_dummy;
            negTrack.py1 = y_dummy;
            negTrack.pz1 = z_dummy;
            recNegTrack.getExpMomentumFast(1910., x_dummy, y_dummy, z_dummy);
            negTrack.px3 = x_dummy;
            negTrack.py3 = y_dummy;
            negTrack.pz3 = z_dummy;
            recNegTrack.getMomentumVertex(x_dummy, y_dummy, z_dummy);
            negTrack.px0 = x_dummy;
            negTrack.py0 = y_dummy;
            negTrack.pz0 = z_dummy;
            negTrack.pxT = recNegTrack.getTargetMom().X();
            negTrack.pyT = recNegTrack.getTargetMom().Y();
            negTrack.pzT = recNegTrack.getTargetMom().Z();
            negTrack.pxD = recNegTrack.getDumpMom().X();
            negTrack.pyD = recNegTrack.getDumpMom().Y();
            negTrack.pzD = recNegTrack.getDumpMom().Z();
            negTrack.roadID = recNegTrack.getTriggerRoad();
            negTrack.tx_PT  = recNegTrack.getPTSlopeX();
            negTrack.ty_PT  = recNegTrack.getPTSlopeY();
            negTrack.thbend = atan(negTrack.px3/negTrack.pz3) - atan(negTrack.px1/negTrack.pz1);
            negTrack.pxv = recDimuon.p_neg.Px();
            negTrack.pyv = recDimuon.p_neg.Py();
            negTrack.pzv = recDimuon.p_neg.Pz();

            saveTree->Fill();
        }

        recEvent->clear();
    }

    saveFile->cd();
    saveTree->Write();
    saveFile->Close();

    return EXIT_SUCCESS;
}
<commit_msg>Minor update to let kTrackerResReader also read in full QIE info<commit_after>#include <iostream>
#include <map>

#include <TROOT.h>
#include <TFile.h>
#include <TTree.h>
#include <TString.h>

#include "kTracker/SRawEvent.h"
#include "kTracker/SRecEvent.h"

#include "DataStruct.h"

using namespace std;

int main(int argc, char* argv[])
{
    //name of the TTree
    TString treename = argv[3];

    // input data structure
    SRecEvent* recEvent = new SRecEvent;

    TFile* dataFile = new TFile(argv[1], "READ");
    TTree* dataTree = (TTree*)dataFile->Get(treename.Data());

    dataTree->SetBranchAddress("recEvent", &recEvent);

    //check if raw event exists
    bool mcdata = false;
    bool mixdata = treename.Contains("mix") || treename.Contains("pp") || treename.Contains("mm");
    SRawEvent* rawEvent;
    SRawMCEvent* rawMCEvent;
    if(dataTree->FindBranch("rawEvent") != NULL)
    {
        if(TString(dataTree->FindBranch("rawEvent")->GetClassName()) == "SRawMCEvent")
        {
            rawMCEvent = new SRawMCEvent;
            dataTree->SetBranchAddress("rawEvent", &rawMCEvent);
            mcdata = true;
        }
        else
        {
            rawEvent = new SRawEvent;
            dataTree->SetBranchAddress("rawEvent", &rawEvent);
        }
    }

    // output data structure
    Dimuon* p_dimuon = new Dimuon; Dimuon& dimuon = *p_dimuon;
    Spill* p_spill = new Spill; Spill& spill = *p_spill;
    Event* p_event = new Event; Event& event = *p_event;
    Track* p_posTrack = new Track; Track& posTrack = *p_posTrack;
    Track* p_negTrack = new Track; Track& negTrack = *p_negTrack;

    TFile* saveFile = new TFile(argv[2], "recreate");
    TTree* saveTree = new TTree("save", "save");

    saveTree->Branch("dimuon", &p_dimuon, 256000, 99);
    saveTree->Branch("event", &p_event, 256000, 99);
    saveTree->Branch("spill", &p_spill, 256000, 99);
    saveTree->Branch("posTrack", &p_posTrack, 256000, 99);
    saveTree->Branch("negTrack", &p_negTrack, 256000, 99);

    //Initialize spill information accordingly
    spill.skipflag = mcdata || mixdata;
    map<int, Spill> spillBank;
    if(!spill.skipflag && argc > 4)
    {
        TFile* spillFile = new TFile(argv[4]);
        TTree* spillTree = (TTree*)spillFile->Get("save");

        spillTree->SetBranchAddress("spill", &p_spill);

        for(int i = 0; i < spillTree->GetEntries(); ++i)
        {
            spillTree->GetEntry(i);
            spillBank.insert(map<int, Spill>::value_type(spill.spillID, spill));
        }
    }

    //start reading data
    int nDimuons = 0;
    double x_dummy, y_dummy, z_dummy;
    bool badSpillFlag = false;
    for(int i = 0; i < dataTree->GetEntries(); ++i)
    {
        dataTree->GetEntry(i);
        if(i % 1000 == 0)
        {
            cout << "Converting " << i << "/" << dataTree->GetEntries() << endl;
        }

        //general event level info
        event.runID = recEvent->getRunID();
        event.spillID = recEvent->getSpillID();
        event.eventID = recEvent->getEventID();
        event.status = recEvent->getRecStatus();
        if(mcdata)
        {
            event.MATRIX1 = rawMCEvent->isEmuTriggered() ? 1 : -1;
            event.weight = rawMCEvent->weight;
            event.intensity[16] = 1.;
        }
        else if(mixdata)
        {
            event.MATRIX1 = 1;
            event.weight = 1.;
            event.intensity[16] = 1.;
        }
        else
        {
            event.MATRIX1 = recEvent->isTriggeredBy(SRawEvent::MATRIX1) ? 1 : -1;
            event.weight = 1.;
            for(int j = -16; j <= 16; ++j) event.intensity[i+16] = rawEvent->getIntensity(i);
        }

        //spill level information
        if(!spill.skipflag && event.spillID != spill.spillID)
        {
            badSpillFlag = false;
            if(!spillBank.empty())
            {
                if(spillBank.find(recEvent->getSpillID()) == spillBank.end())
                {
                    event.log("spillID does not exist!");
                    badSpillFlag = true;
                }
                else
                {
                    spill = spillBank[recEvent->getSpillID()];
                }
            }
        }
        else
        {
            spill.spillID = recEvent->getSpillID();
            spill.targetPos = recEvent->getTargetPos();
            spill.TARGPOS_CONTROL = recEvent->getTargetPos();
        }
        if(badSpillFlag) continue;

        for(int j = 0; j < recEvent->getNDimuons(); ++j)
        {
            ++nDimuons;
            SRecDimuon recDimuon = recEvent->getDimuon(j);

            dimuon.dimuonID = nDimuons;
            dimuon.posTrackID = recDimuon.trackID_pos;
            dimuon.negTrackID = recDimuon.trackID_neg;
            dimuon.px1 = recDimuon.p_pos.Px();
            dimuon.py1 = recDimuon.p_pos.Py();
            dimuon.pz1 = recDimuon.p_pos.Pz();
            dimuon.px2 = recDimuon.p_neg.Px();
            dimuon.py2 = recDimuon.p_neg.Py();
            dimuon.pz2 = recDimuon.p_neg.Pz();
            dimuon.dx  = recDimuon.vtx.X();
            dimuon.dy  = recDimuon.vtx.Y();
            dimuon.dz  = recDimuon.vtx.Z();
            dimuon.dpx = dimuon.px1 + dimuon.px2;
            dimuon.dpy = dimuon.py1 + dimuon.py2;
            dimuon.dpz = dimuon.pz1 + dimuon.pz2;
            dimuon.mass  = recDimuon.mass;
            dimuon.xF    = recDimuon.xF;
            dimuon.x1    = recDimuon.x1;
            dimuon.x2    = recDimuon.x2;
            dimuon.pT    = recDimuon.pT;
            dimuon.costh = recDimuon.costh;
            dimuon.phi   = recDimuon.phi;
            dimuon.chisq_dimuon    = recDimuon.chisq_kf;
            dimuon.trackSeparation = recDimuon.vtx_pos.Z() - recDimuon.vtx_neg.Z();

            //if(!dimuon.goodDimuon()) continue;
            if(dimuon.mass < 0.5 || dimuon.mass > 10. || dimuon.chisq_dimuon > 25. || dimuon.x1 < 0. || dimuon.x1 > 1.
               || dimuon.x2 < 0. || dimuon.x2 > 1. || dimuon.xF < -1. || dimuon.xF > 1. || fabs(dimuon.dx) > 2.
               || fabs(dimuon.dy) > 2. || dimuon.dz < -300. || dimuon.dz > 300. || fabs(dimuon.dpx) > 3.
               || fabs(dimuon.dpy) > 3. || dimuon.dpz < 30. || dimuon.dpz > 120. || fabs(dimuon.trackSeparation) > 300.) continue;

            SRecTrack recPosTrack = recEvent->getTrack(dimuon.posTrackID);
            posTrack.trackID   = recDimuon.trackID_pos;
            posTrack.charge    = 1;
            posTrack.nHits     = recPosTrack.getNHits();
            posTrack.nHitsSt1  = recPosTrack.getNHitsInStation(1);
            posTrack.nHitsSt2  = recPosTrack.getNHitsInStation(2);
            posTrack.nHitsSt3  = recPosTrack.getNHitsInStation(3);
            posTrack.nHitsSt4H = recPosTrack.getNHitsInPTY();
            posTrack.nHitsSt4V = recPosTrack.getNHitsInPTX();
            posTrack.chisq        = recPosTrack.getChisq();
            posTrack.chisq_dump   = recPosTrack.getChisqDump();
            posTrack.chisq_target = recPosTrack.getChisqTarget();
            posTrack.chisq_upstream = recPosTrack.getChisqUpstream();
            recPosTrack.getExpPositionFast(600., x_dummy, y_dummy);
            posTrack.x1 = x_dummy;
            posTrack.y1 = y_dummy;
            posTrack.z1 = 600.;
            recPosTrack.getExpPositionFast(1910., x_dummy, y_dummy);
            posTrack.x3 = x_dummy;
            posTrack.y3 = y_dummy;
            posTrack.z3 = 1910.;
            posTrack.x0 = recPosTrack.getVtxPar(0);
            posTrack.y0 = recPosTrack.getVtxPar(1);
            posTrack.z0 = recPosTrack.getVtxPar(2);
            posTrack.xT = recPosTrack.getTargetPos().X();
            posTrack.yT = recPosTrack.getTargetPos().Y();
            posTrack.zT = recPosTrack.getTargetPos().Z();
            posTrack.xD = recPosTrack.getDumpPos().X();
            posTrack.yD = recPosTrack.getDumpPos().Y();
            posTrack.zD = recPosTrack.getDumpPos().Z();
            recPosTrack.getExpMomentumFast(600., x_dummy, y_dummy, z_dummy);
            posTrack.px1 = x_dummy;
            posTrack.py1 = y_dummy;
            posTrack.pz1 = z_dummy;
            recPosTrack.getExpMomentumFast(1910., x_dummy, y_dummy, z_dummy);
            posTrack.px3 = x_dummy;
            posTrack.py3 = y_dummy;
            posTrack.pz3 = z_dummy;
            recPosTrack.getMomentumVertex(x_dummy, y_dummy, z_dummy);
            posTrack.px0 = x_dummy;
            posTrack.py0 = y_dummy;
            posTrack.pz0 = z_dummy;
            posTrack.pxT = recPosTrack.getTargetMom().X();
            posTrack.pyT = recPosTrack.getTargetMom().Y();
            posTrack.pzT = recPosTrack.getTargetMom().Z();
            posTrack.pxD = recPosTrack.getDumpMom().X();
            posTrack.pyD = recPosTrack.getDumpMom().Y();
            posTrack.pzD = recPosTrack.getDumpMom().Z();
            posTrack.roadID = recPosTrack.getTriggerRoad();
            posTrack.tx_PT  = recPosTrack.getPTSlopeX();
            posTrack.ty_PT  = recPosTrack.getPTSlopeY();
            posTrack.thbend = atan(posTrack.px3/posTrack.pz3) - atan(posTrack.px1/posTrack.pz1);
            posTrack.pxv = recDimuon.p_pos.Px();
            posTrack.pyv = recDimuon.p_pos.Py();
            posTrack.pzv = recDimuon.p_pos.Pz();

            SRecTrack recNegTrack = recEvent->getTrack(dimuon.negTrackID);
            negTrack.trackID   = recDimuon.trackID_neg;
            negTrack.charge    = 1;
            negTrack.nHits     = recNegTrack.getNHits();
            negTrack.nHitsSt1  = recNegTrack.getNHitsInStation(1);
            negTrack.nHitsSt2  = recNegTrack.getNHitsInStation(2);
            negTrack.nHitsSt3  = recNegTrack.getNHitsInStation(3);
            negTrack.nHitsSt4H = recNegTrack.getNHitsInPTY();
            negTrack.nHitsSt4V = recNegTrack.getNHitsInPTX();
            negTrack.chisq        = recNegTrack.getChisq();
            negTrack.chisq_dump   = recNegTrack.getChisqDump();
            negTrack.chisq_target = recNegTrack.getChisqTarget();
            negTrack.chisq_upstream = recNegTrack.getChisqUpstream();
            recNegTrack.getExpPositionFast(600., x_dummy, y_dummy);
            negTrack.x1 = x_dummy;
            negTrack.y1 = y_dummy;
            negTrack.z1 = 600.;
            recNegTrack.getExpPositionFast(1910., x_dummy, y_dummy);
            negTrack.x3 = x_dummy;
            negTrack.y3 = y_dummy;
            negTrack.z3 = 1910.;
            negTrack.x0 = recNegTrack.getVtxPar(0);
            negTrack.y0 = recNegTrack.getVtxPar(1);
            negTrack.z0 = recNegTrack.getVtxPar(2);
            negTrack.xT = recNegTrack.getTargetPos().X();
            negTrack.yT = recNegTrack.getTargetPos().Y();
            negTrack.zT = recNegTrack.getTargetPos().Z();
            negTrack.xD = recNegTrack.getDumpPos().X();
            negTrack.yD = recNegTrack.getDumpPos().Y();
            negTrack.zD = recNegTrack.getDumpPos().Z();
            recNegTrack.getExpMomentumFast(600., x_dummy, y_dummy, z_dummy);
            negTrack.px1 = x_dummy;
            negTrack.py1 = y_dummy;
            negTrack.pz1 = z_dummy;
            recNegTrack.getExpMomentumFast(1910., x_dummy, y_dummy, z_dummy);
            negTrack.px3 = x_dummy;
            negTrack.py3 = y_dummy;
            negTrack.pz3 = z_dummy;
            recNegTrack.getMomentumVertex(x_dummy, y_dummy, z_dummy);
            negTrack.px0 = x_dummy;
            negTrack.py0 = y_dummy;
            negTrack.pz0 = z_dummy;
            negTrack.pxT = recNegTrack.getTargetMom().X();
            negTrack.pyT = recNegTrack.getTargetMom().Y();
            negTrack.pzT = recNegTrack.getTargetMom().Z();
            negTrack.pxD = recNegTrack.getDumpMom().X();
            negTrack.pyD = recNegTrack.getDumpMom().Y();
            negTrack.pzD = recNegTrack.getDumpMom().Z();
            negTrack.roadID = recNegTrack.getTriggerRoad();
            negTrack.tx_PT  = recNegTrack.getPTSlopeX();
            negTrack.ty_PT  = recNegTrack.getPTSlopeY();
            negTrack.thbend = atan(negTrack.px3/negTrack.pz3) - atan(negTrack.px1/negTrack.pz1);
            negTrack.pxv = recDimuon.p_neg.Px();
            negTrack.pyv = recDimuon.p_neg.Py();
            negTrack.pzv = recDimuon.p_neg.Pz();

            saveTree->Fill();
        }

        recEvent->clear();
    }

    saveFile->cd();
    saveTree->Write();
    saveFile->Close();

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 *  fontcolour.cpp  -  font and colour chooser widget
 *  Program:  kalarm
 *  (C) 2001 by David Jarvie  software@astrojar.org.uk
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <qobjectlist.h>
#include <qwidget.h>
#include <qgroupbox.h>
#include <qlabel.h>
#include <qlayout.h>

#include <kdialog.h>
#include <kglobal.h>
#include <klocale.h>

#include "fontcolour.h"
#include "fontcolour.moc"

FontColourChooser::FontColourChooser(QWidget *parent, const char *name,
	       bool onlyFixed, const QStringList &fontList,
	       bool makeFrame, const QString& frameLabel, bool fg, int visibleListSize)
	: QWidget(parent, name)
{
	QVBoxLayout* topLayout = new QVBoxLayout(this, 0, KDialog::spacingHint());
	QWidget* page = this;
	if (makeFrame)
	{
		page = new QGroupBox(i18n(frameLabel), this);
		topLayout->addWidget(page);
		topLayout = new QVBoxLayout(page, KDialog::marginHint(), KDialog::spacingHint());
		topLayout->addSpacing(fontMetrics().lineSpacing()/2);
	}

	QGridLayout* grid = new QGridLayout(topLayout, (fg ? 3 : 2), 2);
	grid->addRowSpacing(0, KDialog::marginHint());
	int gridRow = 1;

	QLabel* label;
	if (fg)
	{
		label = new QLabel(i18n("Default foreground color:"), page);
		grid->addWidget(label, gridRow, 0, AlignRight);
		label->setFixedSize(label->sizeHint());
		m_fgColourButton = new ColourCombo(page);
		grid->addWidget(m_fgColourButton, gridRow, 1, AlignRight);
		connect(m_fgColourButton, SIGNAL(activated(const QString&)), SLOT(setSampleColour()));
		++gridRow;
	}

	label = new QLabel(i18n("Default background color:"), page);
	label->setMinimumSize(label->sizeHint());
	grid->addWidget(label, gridRow, 0);
	m_bgColourButton = new ColourCombo(page);
	m_bgColourButton->setMinimumSize(m_bgColourButton->sizeHint());
	grid->addWidget(m_bgColourButton, gridRow, 1, AlignRight);
	connect(m_bgColourButton, SIGNAL(activated(const QString&)), SLOT(setSampleColour()));

	m_fontChooser = new KFontChooser(page, name, onlyFixed, fontList, false, visibleListSize);
	topLayout->addWidget(m_fontChooser);
}

FontColourChooser::~FontColourChooser()
{
}

void FontColourChooser::setFgColour(const QColor& colour)
{
	if (m_fgColourButton)
	{
		m_fgColourButton->setColour(colour);
		m_fontChooser->setColor(colour);
	}
}

void FontColourChooser::setBgColour(const QColor& colour)
{
	m_bgColourButton->setColour(colour);
	m_fontChooser->setBackgroundColor(colour);
}

void FontColourChooser::setSampleColour()
{
	QColor bg = m_bgColourButton->color();
	m_fontChooser->setBackgroundColor(bg);
	QColor fg = fgColour();
	m_fontChooser->setColor(fg);
}

QColor FontColourChooser::fgColour() const
{
	QColor bg = m_bgColourButton->color();
	QPalette pal(bg, bg);
	return pal.color(QPalette::Active, QColorGroup::Text);
}
<commit_msg>Better label text<commit_after>/*
 *  fontcolour.cpp  -  font and colour chooser widget
 *  Program:  kalarm
 *  (C) 2001, 2002 by David Jarvie  software@astrojar.org.uk
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <qobjectlist.h>
#include <qwidget.h>
#include <qgroupbox.h>
#include <qlabel.h>
#include <qlayout.h>

#include <kdialog.h>
#include <kglobal.h>
#include <klocale.h>

#include "fontcolour.moc"

FontColourChooser::FontColourChooser(QWidget *parent, const char *name,
          bool onlyFixed, const QStringList &fontList,
          bool makeFrame, const QString& frameLabel, bool fg, int visibleListSize)
   : QWidget(parent, name)
{
   QVBoxLayout* topLayout = new QVBoxLayout(this, 0, KDialog::spacingHint());
   QWidget* page = this;
   if (makeFrame)
   {
      page = new QGroupBox(i18n(frameLabel), this);
      topLayout->addWidget(page);
      topLayout = new QVBoxLayout(page, KDialog::marginHint(), KDialog::spacingHint());
      topLayout->addSpacing(fontMetrics().lineSpacing()/2);
   }

   QGridLayout* grid = new QGridLayout(topLayout, (fg ? 3 : 2), 2);
   grid->addRowSpacing(0, KDialog::marginHint());
   int gridRow = 1;

   QLabel* label;
   if (fg)
   {
      label = new QLabel(i18n("Foreground color:"), page);
      grid->addWidget(label, gridRow, 0, AlignRight);
      label->setFixedSize(label->sizeHint());
      m_fgColourButton = new ColourCombo(page);
      grid->addWidget(m_fgColourButton, gridRow, 1, AlignRight);
      connect(m_fgColourButton, SIGNAL(activated(const QString&)), SLOT(setSampleColour()));
      ++gridRow;
   }

   label = new QLabel(i18n("Background color:"), page);
   label->setMinimumSize(label->sizeHint());
   grid->addWidget(label, gridRow, 0);
   m_bgColourButton = new ColourCombo(page);
   m_bgColourButton->setMinimumSize(m_bgColourButton->sizeHint());
   grid->addWidget(m_bgColourButton, gridRow, 1, AlignRight);
   connect(m_bgColourButton, SIGNAL(activated(const QString&)), SLOT(setSampleColour()));

   m_fontChooser = new KFontChooser(page, name, onlyFixed, fontList, false, visibleListSize);
   topLayout->addWidget(m_fontChooser);
}

FontColourChooser::~FontColourChooser()
{
}

void FontColourChooser::setFgColour(const QColor& colour)
{
   if (m_fgColourButton)
   {
      m_fgColourButton->setColour(colour);
      m_fontChooser->setColor(colour);
   }
}

void FontColourChooser::setBgColour(const QColor& colour)
{
   m_bgColourButton->setColour(colour);
   m_fontChooser->setBackgroundColor(colour);
}

void FontColourChooser::setSampleColour()
{
   QColor bg = m_bgColourButton->color();
   m_fontChooser->setBackgroundColor(bg);
   QColor fg = fgColour();
   m_fontChooser->setColor(fg);
}

QColor FontColourChooser::fgColour() const
{
   QColor bg = m_bgColourButton->color();
   QPalette pal(bg, bg);
   return pal.color(QPalette::Active, QColorGroup::Text);
}
<|endoftext|>


<commit_before>/* This file is part of the KDE project
   Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org>
   Copyright (C) 2002 Joseph Wenninger <jowenn@kde.org>

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

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

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

#include "kateapp.h"

#include <kate_export.h>
#include <KLocale>
#include <KCmdLineArgs>
#include <KAboutData>
#include <KStartupInfo>
#include <kdebug.h>

#include <QTextCodec>
#include <QByteArray>
#include <QCoreApplication>
#include <QDBusMessage>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QDBusReply>
#include <QVariant>

class KateWaiter : public QObject {
  Q_OBJECT

  private:
    QCoreApplication *m_app;

  public:
    KateWaiter (QCoreApplication *app) : QObject (app), m_app (app) {
    }

  public Q_SLOTS:
    void exiting () {
      m_app->quit ();
    }
};

extern "C" KDE_EXPORT int kdemain( int argc, char **argv )
{
  // here we go, construct the Kate version
  QByteArray kateVersion = KateApp::kateVersion().toLatin1();

  KAboutData aboutData ("kate", 0, ki18n("Kate"), kateVersion,
                        ki18n( "Kate - Advanced Text Editor" ), KAboutData::License_LGPL_V2,
                        ki18n( "(c) 2000-2005 The Kate Authors" ), KLocalizedString(), "http://www.kate-editor.org");
  aboutData.setOrganizationDomain("kde.org");
  aboutData.addAuthor (ki18n("Christoph Cullmann"), ki18n("Maintainer"), "cullmann@kde.org", "http://www.babylon2k.de");
  aboutData.addAuthor (ki18n("Anders Lund"), ki18n("Core Developer"), "anders@alweb.dk", "http://www.alweb.dk");
  aboutData.addAuthor (ki18n("Joseph Wenninger"), ki18n("Core Developer"), "jowenn@kde.org", "http://stud3.tuwien.ac.at/~e9925371");
  aboutData.addAuthor (ki18n("Hamish Rodda"), ki18n("Core Developer"), "rodda@kde.org");
  aboutData.addAuthor (ki18n("Dominik Haumann"), ki18n("Developer & Highlight wizard"), "dhdev@gmx.de");
  aboutData.addAuthor (ki18n("Waldo Bastian"), ki18n( "The cool buffersystem" ), "bastian@kde.org" );
  aboutData.addAuthor (ki18n("Charles Samuels"), ki18n("The Editing Commands"), "charles@kde.org");
  aboutData.addAuthor (ki18n("Matt Newell"), ki18n("Testing, ..."), "newellm@proaxis.com");
  aboutData.addAuthor (ki18n("Michael Bartl"), ki18n("Former Core Developer"), "michael.bartl1@chello.at");
  aboutData.addAuthor (ki18n("Michael McCallum"), ki18n("Core Developer"), "gholam@xtra.co.nz");
  aboutData.addAuthor (ki18n("Jochen Wilhemly"), ki18n( "KWrite Author" ), "digisnap@cs.tu-berlin.de" );
  aboutData.addAuthor (ki18n("Michael Koch"), ki18n("KWrite port to KParts"), "koch@kde.org");
  aboutData.addAuthor (ki18n("Christian Gebauer"), KLocalizedString(), "gebauer@kde.org" );
  aboutData.addAuthor (ki18n("Simon Hausmann"), KLocalizedString(), "hausmann@kde.org" );
  aboutData.addAuthor (ki18n("Glen Parker"), ki18n("KWrite Undo History, Kspell integration"), "glenebob@nwlink.com");
  aboutData.addAuthor (ki18n("Scott Manson"), ki18n("KWrite XML Syntax highlighting support"), "sdmanson@alltel.net");
  aboutData.addAuthor (ki18n("John Firebaugh"), ki18n("Patches and more"), "jfirebaugh@kde.org");

  aboutData.addCredit (ki18n("Matteo Merli"), ki18n("Highlighting for RPM Spec-Files, Perl, Diff and more"), "merlim@libero.it");
  aboutData.addCredit (ki18n("Rocky Scaletta"), ki18n("Highlighting for VHDL"), "rocky@purdue.edu");
  aboutData.addCredit (ki18n("Yury Lebedev"), ki18n("Highlighting for SQL"));
  aboutData.addCredit (ki18n("Chris Ross"), ki18n("Highlighting for Ferite"));
  aboutData.addCredit (ki18n("Nick Roux"), ki18n("Highlighting for ILERPG"));
  aboutData.addCredit (ki18n("Carsten Niehaus"), ki18n("Highlighting for LaTeX"));
  aboutData.addCredit (ki18n("Per Wigren"), ki18n("Highlighting for Makefiles, Python"));
  aboutData.addCredit (ki18n("Jan Fritz"), ki18n("Highlighting for Python"));
  aboutData.addCredit (ki18n("Daniel Naber"));
  aboutData.addCredit (ki18n("Roland Pabel"), ki18n("Highlighting for Scheme"));
  aboutData.addCredit (ki18n("Cristi Dumitrescu"), ki18n("PHP Keyword/Datatype list"));
  aboutData.addCredit (ki18n("Carsten Pfeiffer"), ki18n("Very nice help"));
  aboutData.addCredit (ki18n("All people who have contributed and I have forgotten to mention"));

  // command line args init and co
  KCmdLineArgs::init (argc, argv, &aboutData);

  KCmdLineOptions options;
  options.add("s");
  options.add("start <name>", ki18n("Start Kate with a given session"));
  options.add("n");
  options.add("new", ki18n("Force start of a new kate instance"));
  options.add("b");
  options.add("block", ki18n("If using an already running kate instance, block until it exits"));
  options.add("p");
  options.add("pid <pid>", ki18n("Only try to reuse kate instance with this pid"));
  options.add("e");
  options.add("encoding <name>", ki18n("Set encoding for the file to open"));
  options.add("l");
  options.add("line <line>", ki18n("Navigate to this line"));
  options.add("c");
  options.add("column <column>", ki18n("Navigate to this column"));
  options.add("i");
  options.add("stdin", ki18n("Read the contents of stdin"));
  options.add("u");
  options.add("use", ki18n("Reuse existing Kate instance, default, only for compatiblity"));
  options.add("+[URL]", ki18n("Document to open"));
  KCmdLineArgs::addCmdLineOptions (options);
  KCmdLineArgs::addTempFileOption();

  // get our command line args ;)
  KCmdLineArgs* args = KCmdLineArgs::parsedArgs();

  // now, first try to contact running kate instance if needed
  if (!args->isSet("new"))
  {
    // inialize the dbus stuff...
    // bus interface
    QDBusConnectionInterface *i = QDBusConnection::sessionBus().interface ();

    // service name....
    QString serviceName;

    // two possibilities: pid given or not...
    if ( (args->isSet("pid")) || (!qgetenv("KATE_PID").isEmpty()))
    {
      QString usePid;
      if (args->isSet("pid")) usePid = args->getOption("pid");
      else usePid = QString::fromLocal8Bit(qgetenv("KATE_PID"));

      serviceName = "org.kde.kate-" + usePid;
    }
    else // pid not given, try to guess it....
    {
      QDBusReply<QStringList> servicesReply = i->registeredServiceNames ();
      QStringList services;
      if (servicesReply.isValid())
        services = servicesReply.value ();

      foreach (const QString &s, services)
      {
        if (s.startsWith ("org.kde.kate-"))
        {
          serviceName = s;
          break;
        }
      }
    }

    // no already running instance found and no specific pid given, start new instance...
    bool foundRunningService = false;
    if (!serviceName.isEmpty ())
    {
      QDBusReply<bool> there = i->isServiceRegistered (serviceName);
      foundRunningService = there.isValid () && there.value();
    }

    if (foundRunningService)
    {
      // open given session
      if (args->isSet ("start"))
      {
        QDBusMessage m = QDBusMessage::createMethodCall (serviceName,
                QLatin1String("/MainApplication"), "org.kde.Kate.Application", "activateSession");

        QList<QVariant> dbusargs;
        dbusargs.append(args->getOption("start"));
        m.setArguments(dbusargs);

        QDBusConnection::sessionBus().call (m);
      }

      QString enc = args->isSet("encoding") ? args->getOption("encoding") : QByteArray("");

      bool tempfileSet = KCmdLineArgs::isTempFileSet();

      // open given files...
      for (int z = 0; z < args->count(); z++)
      {
        QDBusMessage m = QDBusMessage::createMethodCall (serviceName,
                QLatin1String("/MainApplication"), "org.kde.Kate.Application", "openUrl");

        QList<QVariant> dbusargs;
        dbusargs.append(args->url(z).url());
        dbusargs.append(enc);
        dbusargs.append(tempfileSet);
        m.setArguments(dbusargs);

        QDBusConnection::sessionBus().call (m);
      }

      if( args->isSet( "stdin" ) )
      {
        QTextStream input(stdin, QIODevice::ReadOnly);

        // set chosen codec
        QTextCodec *codec = args->isSet("encoding") ? QTextCodec::codecForName(args->getOption("encoding").toUtf8()) : 0;

        if (codec)
          input.setCodec (codec);

        QString line;
        QString text;

        do
        {
          line = input.readLine();
          text.append( line + '\n' );
        }
        while( !line.isNull() );

        QDBusMessage m = QDBusMessage::createMethodCall (serviceName,
                QLatin1String("/MainApplication"), "org.kde.Kate.Application", "openInput");

        QList<QVariant> dbusargs;
        dbusargs.append(text);
        m.setArguments(dbusargs);

        QDBusConnection::sessionBus().call (m);
      }

      int line = 0;
      int column = 0;
      bool nav = false;

      if (args->isSet ("line"))
      {
        line = args->getOption ("line").toInt() - 1;
        nav = true;
      }

      if (args->isSet ("column"))
      {
        column = args->getOption ("column").toInt() - 1;
        nav = true;
      }

      if (nav)
      {
        QDBusMessage m = QDBusMessage::createMethodCall (serviceName,
                QLatin1String("/MainApplication"), "org.kde.Kate.Application", "setCursor");

        QList<QVariant> args;
        args.append(line);
        args.append(column);
        m.setArguments(args);

        QDBusConnection::sessionBus().call (m);
      }

      // application object to have event loop
      QCoreApplication app (argc, argv);

      // connect dbus signal
      if (args->isSet( "block" )) {
        KateWaiter *waiter = new KateWaiter (&app);
        QDBusConnection::sessionBus().connect(serviceName, QString("/MainApplication"), "org.kde.Kate.Application", "exiting", waiter, SLOT(exiting()));
      }

#ifdef Q_WS_X11
      // make the world happy, we are started, kind of...
      KStartupInfo::appStarted ();
#endif

      // this will wait until exiting is emited by the used instance, if wanted...
      return args->isSet( "block" ) ? app.exec () : 0;
    }
  }

  // construct the real kate app object ;)
  KateApp app (args);
  if (app.shouldExit()) return 0;

  // execute ourself ;)
  return app.exec();
}

// kate: space-indent on; indent-width 2; replace-tabs on;

#include "katemain.moc"
<commit_msg>safety net for kate, exit if the main app did leave the dbus<commit_after>/* This file is part of the KDE project
   Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org>
   Copyright (C) 2002 Joseph Wenninger <jowenn@kde.org>

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

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

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

#include "kateapp.h"

#include <kate_export.h>
#include <KLocale>
#include <KCmdLineArgs>
#include <KAboutData>
#include <KStartupInfo>
#include <kdebug.h>

#include <QTextCodec>
#include <QByteArray>
#include <QCoreApplication>
#include <QDBusMessage>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QDBusReply>
#include <QVariant>

class KateWaiter : public QObject {
  Q_OBJECT

  private:
    QCoreApplication *m_app;
    QString m_service;

  public:
    KateWaiter (QCoreApplication *app, const QString &service)
      : QObject (app), m_app (app), m_service (service) {
      connect ( QDBusConnection::sessionBus().interface(), SIGNAL( serviceOwnerChanged( QString, QString, QString ) )
          , this, SLOT(serviceOwnerChanged( QString, QString, QString )) );
    }

  public Q_SLOTS:
    void exiting () {
      m_app->quit ();
    }

    void serviceOwnerChanged( const QString & name, const QString &, const QString &) {
      if (name != m_service)
          return;

      m_app->quit ();
    }
};

extern "C" KDE_EXPORT int kdemain( int argc, char **argv )
{
  // here we go, construct the Kate version
  QByteArray kateVersion = KateApp::kateVersion().toLatin1();

  KAboutData aboutData ("kate", 0, ki18n("Kate"), kateVersion,
                        ki18n( "Kate - Advanced Text Editor" ), KAboutData::License_LGPL_V2,
                        ki18n( "(c) 2000-2005 The Kate Authors" ), KLocalizedString(), "http://www.kate-editor.org");
  aboutData.setOrganizationDomain("kde.org");
  aboutData.addAuthor (ki18n("Christoph Cullmann"), ki18n("Maintainer"), "cullmann@kde.org", "http://www.babylon2k.de");
  aboutData.addAuthor (ki18n("Anders Lund"), ki18n("Core Developer"), "anders@alweb.dk", "http://www.alweb.dk");
  aboutData.addAuthor (ki18n("Joseph Wenninger"), ki18n("Core Developer"), "jowenn@kde.org", "http://stud3.tuwien.ac.at/~e9925371");
  aboutData.addAuthor (ki18n("Hamish Rodda"), ki18n("Core Developer"), "rodda@kde.org");
  aboutData.addAuthor (ki18n("Dominik Haumann"), ki18n("Developer & Highlight wizard"), "dhdev@gmx.de");
  aboutData.addAuthor (ki18n("Waldo Bastian"), ki18n( "The cool buffersystem" ), "bastian@kde.org" );
  aboutData.addAuthor (ki18n("Charles Samuels"), ki18n("The Editing Commands"), "charles@kde.org");
  aboutData.addAuthor (ki18n("Matt Newell"), ki18n("Testing, ..."), "newellm@proaxis.com");
  aboutData.addAuthor (ki18n("Michael Bartl"), ki18n("Former Core Developer"), "michael.bartl1@chello.at");
  aboutData.addAuthor (ki18n("Michael McCallum"), ki18n("Core Developer"), "gholam@xtra.co.nz");
  aboutData.addAuthor (ki18n("Jochen Wilhemly"), ki18n( "KWrite Author" ), "digisnap@cs.tu-berlin.de" );
  aboutData.addAuthor (ki18n("Michael Koch"), ki18n("KWrite port to KParts"), "koch@kde.org");
  aboutData.addAuthor (ki18n("Christian Gebauer"), KLocalizedString(), "gebauer@kde.org" );
  aboutData.addAuthor (ki18n("Simon Hausmann"), KLocalizedString(), "hausmann@kde.org" );
  aboutData.addAuthor (ki18n("Glen Parker"), ki18n("KWrite Undo History, Kspell integration"), "glenebob@nwlink.com");
  aboutData.addAuthor (ki18n("Scott Manson"), ki18n("KWrite XML Syntax highlighting support"), "sdmanson@alltel.net");
  aboutData.addAuthor (ki18n("John Firebaugh"), ki18n("Patches and more"), "jfirebaugh@kde.org");

  aboutData.addCredit (ki18n("Matteo Merli"), ki18n("Highlighting for RPM Spec-Files, Perl, Diff and more"), "merlim@libero.it");
  aboutData.addCredit (ki18n("Rocky Scaletta"), ki18n("Highlighting for VHDL"), "rocky@purdue.edu");
  aboutData.addCredit (ki18n("Yury Lebedev"), ki18n("Highlighting for SQL"));
  aboutData.addCredit (ki18n("Chris Ross"), ki18n("Highlighting for Ferite"));
  aboutData.addCredit (ki18n("Nick Roux"), ki18n("Highlighting for ILERPG"));
  aboutData.addCredit (ki18n("Carsten Niehaus"), ki18n("Highlighting for LaTeX"));
  aboutData.addCredit (ki18n("Per Wigren"), ki18n("Highlighting for Makefiles, Python"));
  aboutData.addCredit (ki18n("Jan Fritz"), ki18n("Highlighting for Python"));
  aboutData.addCredit (ki18n("Daniel Naber"));
  aboutData.addCredit (ki18n("Roland Pabel"), ki18n("Highlighting for Scheme"));
  aboutData.addCredit (ki18n("Cristi Dumitrescu"), ki18n("PHP Keyword/Datatype list"));
  aboutData.addCredit (ki18n("Carsten Pfeiffer"), ki18n("Very nice help"));
  aboutData.addCredit (ki18n("All people who have contributed and I have forgotten to mention"));

  // command line args init and co
  KCmdLineArgs::init (argc, argv, &aboutData);

  KCmdLineOptions options;
  options.add("s");
  options.add("start <name>", ki18n("Start Kate with a given session"));
  options.add("n");
  options.add("new", ki18n("Force start of a new kate instance"));
  options.add("b");
  options.add("block", ki18n("If using an already running kate instance, block until it exits"));
  options.add("p");
  options.add("pid <pid>", ki18n("Only try to reuse kate instance with this pid"));
  options.add("e");
  options.add("encoding <name>", ki18n("Set encoding for the file to open"));
  options.add("l");
  options.add("line <line>", ki18n("Navigate to this line"));
  options.add("c");
  options.add("column <column>", ki18n("Navigate to this column"));
  options.add("i");
  options.add("stdin", ki18n("Read the contents of stdin"));
  options.add("u");
  options.add("use", ki18n("Reuse existing Kate instance, default, only for compatiblity"));
  options.add("+[URL]", ki18n("Document to open"));
  KCmdLineArgs::addCmdLineOptions (options);
  KCmdLineArgs::addTempFileOption();

  // get our command line args ;)
  KCmdLineArgs* args = KCmdLineArgs::parsedArgs();

  // now, first try to contact running kate instance if needed
  if (!args->isSet("new"))
  {
    // inialize the dbus stuff...
    // bus interface
    QDBusConnectionInterface *i = QDBusConnection::sessionBus().interface ();

    // service name....
    QString serviceName;

    // two possibilities: pid given or not...
    if ( (args->isSet("pid")) || (!qgetenv("KATE_PID").isEmpty()))
    {
      QString usePid;
      if (args->isSet("pid")) usePid = args->getOption("pid");
      else usePid = QString::fromLocal8Bit(qgetenv("KATE_PID"));

      serviceName = "org.kde.kate-" + usePid;
    }
    else // pid not given, try to guess it....
    {
      QDBusReply<QStringList> servicesReply = i->registeredServiceNames ();
      QStringList services;
      if (servicesReply.isValid())
        services = servicesReply.value ();

      foreach (const QString &s, services)
      {
        if (s.startsWith ("org.kde.kate-"))
        {
          serviceName = s;
          break;
        }
      }
    }

    // no already running instance found and no specific pid given, start new instance...
    bool foundRunningService = false;
    if (!serviceName.isEmpty ())
    {
      QDBusReply<bool> there = i->isServiceRegistered (serviceName);
      foundRunningService = there.isValid () && there.value();
    }

    if (foundRunningService)
    {
      // open given session
      if (args->isSet ("start"))
      {
        QDBusMessage m = QDBusMessage::createMethodCall (serviceName,
                QLatin1String("/MainApplication"), "org.kde.Kate.Application", "activateSession");

        QList<QVariant> dbusargs;
        dbusargs.append(args->getOption("start"));
        m.setArguments(dbusargs);

        QDBusConnection::sessionBus().call (m);
      }

      QString enc = args->isSet("encoding") ? args->getOption("encoding") : QByteArray("");

      bool tempfileSet = KCmdLineArgs::isTempFileSet();

      // open given files...
      for (int z = 0; z < args->count(); z++)
      {
        QDBusMessage m = QDBusMessage::createMethodCall (serviceName,
                QLatin1String("/MainApplication"), "org.kde.Kate.Application", "openUrl");

        QList<QVariant> dbusargs;
        dbusargs.append(args->url(z).url());
        dbusargs.append(enc);
        dbusargs.append(tempfileSet);
        m.setArguments(dbusargs);

        QDBusConnection::sessionBus().call (m);
      }

      if( args->isSet( "stdin" ) )
      {
        QTextStream input(stdin, QIODevice::ReadOnly);

        // set chosen codec
        QTextCodec *codec = args->isSet("encoding") ? QTextCodec::codecForName(args->getOption("encoding").toUtf8()) : 0;

        if (codec)
          input.setCodec (codec);

        QString line;
        QString text;

        do
        {
          line = input.readLine();
          text.append( line + '\n' );
        }
        while( !line.isNull() );

        QDBusMessage m = QDBusMessage::createMethodCall (serviceName,
                QLatin1String("/MainApplication"), "org.kde.Kate.Application", "openInput");

        QList<QVariant> dbusargs;
        dbusargs.append(text);
        m.setArguments(dbusargs);

        QDBusConnection::sessionBus().call (m);
      }

      int line = 0;
      int column = 0;
      bool nav = false;

      if (args->isSet ("line"))
      {
        line = args->getOption ("line").toInt() - 1;
        nav = true;
      }

      if (args->isSet ("column"))
      {
        column = args->getOption ("column").toInt() - 1;
        nav = true;
      }

      if (nav)
      {
        QDBusMessage m = QDBusMessage::createMethodCall (serviceName,
                QLatin1String("/MainApplication"), "org.kde.Kate.Application", "setCursor");

        QList<QVariant> args;
        args.append(line);
        args.append(column);
        m.setArguments(args);

        QDBusConnection::sessionBus().call (m);
      }

      // application object to have event loop
      QCoreApplication app (argc, argv);

      // connect dbus signal
      if (args->isSet( "block" )) {
        KateWaiter *waiter = new KateWaiter (&app, serviceName);
        QDBusConnection::sessionBus().connect(serviceName, QString("/MainApplication"), "org.kde.Kate.Application", "exiting", waiter, SLOT(exiting()));
      }

#ifdef Q_WS_X11
      // make the world happy, we are started, kind of...
      KStartupInfo::appStarted ();
#endif

      // this will wait until exiting is emited by the used instance, if wanted...
      return args->isSet( "block" ) ? app.exec () : 0;
    }
  }

  // construct the real kate app object ;)
  KateApp app (args);
  if (app.shouldExit()) return 0;

  // execute ourself ;)
  return app.exec();
}

// kate: space-indent on; indent-width 2; replace-tabs on;

#include "katemain.moc"
<|endoftext|>