<commit_before>// Filename: glxGraphicsPipe.cxx
// Created by:  mike (09Jan97)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University.  All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license.  You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////

#include "glxGraphicsPipe.h"
#include "glxGraphicsWindow.h"
#include "glxGraphicsBuffer.h"
#include "glxGraphicsPixmap.h"
#include "glxGraphicsStateGuardian.h"
#include "posixGraphicsStateGuardian.h"
#include "config_glxdisplay.h"
#include "frameBufferProperties.h"

TypeHandle glxGraphicsPipe::_type_handle;

////////////////////////////////////////////////////////////////////
//     Function: glxGraphicsPipe::Constructor
//       Access: Public
//  Description:
////////////////////////////////////////////////////////////////////
glxGraphicsPipe::
glxGraphicsPipe(const string &display) : x11GraphicsPipe(display) {
  if (_display == None) {
    // Some error must have occurred.
    return;
  }

  string display_spec (XDisplayString(_display));

  int errorBase, eventBase;
  if (!glXQueryExtension(_display, &errorBase, &eventBase)) {
    glxdisplay_cat.error()
      << "OpenGL GLX extension not supported on display \"" << display_spec
      << "\".\n";
    return;
  }
}

////////////////////////////////////////////////////////////////////
//     Function: glxGraphicsPipe::get_interface_name
//       Access: Published, Virtual
//  Description: Returns the name of the rendering interface
//               associated with this GraphicsPipe.  This is used to
//               present to the user to allow him/her to choose
//               between several possible GraphicsPipes available on a
//               particular platform, so the name should be meaningful
//               and unique for a given platform.
////////////////////////////////////////////////////////////////////
string glxGraphicsPipe::
get_interface_name() const {
  return "OpenGL";
}

////////////////////////////////////////////////////////////////////
//     Function: glxGraphicsPipe::pipe_constructor
//       Access: Public, Static
//  Description: This function is passed to the GraphicsPipeSelection
//               object to allow the user to make a default
//               glxGraphicsPipe.
////////////////////////////////////////////////////////////////////
PT(GraphicsPipe) glxGraphicsPipe::
pipe_constructor() {
  return new glxGraphicsPipe;
}

////////////////////////////////////////////////////////////////////
//     Function: glxGraphicsPipe::make_output
//       Access: Protected, Virtual
//  Description: Creates a new window on the pipe, if possible.
////////////////////////////////////////////////////////////////////
PT(GraphicsOutput) glxGraphicsPipe::
make_output(const string &name,
            const FrameBufferProperties &fb_prop,
            const WindowProperties &win_prop,
            int flags,
            GraphicsEngine *engine,
            GraphicsStateGuardian *gsg,
            GraphicsOutput *host,
            int retry,
            bool &precertify) {

  if (!_is_valid) {
    return NULL;
  }

  glxGraphicsStateGuardian *glxgsg = 0;
  if (gsg != 0) {
    DCAST_INTO_R(glxgsg, gsg, NULL);
  }

  bool support_rtt;
  support_rtt = false;
  /*
    Currently, no support for glxGraphicsBuffer render-to-texture.
  if (glxgsg) {
     support_rtt =
      glxgsg -> get_supports_render_texture() &&
      support_render_texture;
  }
  */

  // First thing to try: a glxGraphicsWindow

  if (retry == 0) {
    if (((flags&BF_require_parasite)!=0)||
        ((flags&BF_refuse_window)!=0)||
        ((flags&BF_resizeable)!=0)||
        ((flags&BF_size_track_host)!=0)||
        ((flags&BF_rtt_cumulative)!=0)||
        ((flags&BF_can_bind_color)!=0)||
        ((flags&BF_can_bind_every)!=0)||
        ((flags&BF_can_bind_layered)!=0)) {
      return NULL;
    }
    return new glxGraphicsWindow(engine, this, name, fb_prop, win_prop,
                                 flags, gsg, host);
  }

  // Second thing to try: a GLGraphicsBuffer

  if (retry == 1) {
    if ((host==0)||
        (!gl_support_fbo)||
        ((flags&BF_require_parasite)!=0)||
        ((flags&BF_require_window)!=0)) {
      return NULL;
    }
    // Early failure - if we are sure that this buffer WONT
    // meet specs, we can bail out early.
    int _fbo_multisample = 0;
    if (!ConfigVariableBool("framebuffer-object-multisample", false, PRC_DESC("Enabled Multisample."))) {
        _fbo_multisample = 16;
    }
    if ((flags & BF_fb_props_optional)==0) {
      if ((fb_prop.get_indexed_color() > 0)||
          (fb_prop.get_back_buffers() > 0)||
          (fb_prop.get_accum_bits() > 0)||
          (fb_prop.get_multisamples() > _fbo_multisample)) {
        return NULL;
      }
    }
    // Early success - if we are sure that this buffer WILL
    // meet specs, we can precertify it.
    if ((glxgsg != 0) &&
        (glxgsg->is_valid()) &&
        (!glxgsg->needs_reset()) &&
        (glxgsg->_supports_framebuffer_object) &&
        (glxgsg->_glDrawBuffers != 0)&&
        (fb_prop.is_basic())) {
      precertify = true;
    }
    return new GLGraphicsBuffer(engine, this, name, fb_prop, win_prop,
                                flags, gsg, host);
  }

  // Third thing to try: a glxGraphicsBuffer
  if (glxgsg == NULL || glxgsg->_supports_fbconfig) {
    if (retry == 2) {
      if (!glx_support_pbuffer) {
        return NULL;
      }

      if (((flags&BF_require_parasite)!=0)||
          ((flags&BF_require_window)!=0)||
          ((flags&BF_resizeable)!=0)||
          ((flags&BF_size_track_host)!=0)||
          ((flags&BF_can_bind_layered)!=0)) {
        return NULL;
      }

      if (!support_rtt) {
        if (((flags&BF_rtt_cumulative)!=0)||
            ((flags&BF_can_bind_every)!=0)) {
          // If we require Render-to-Texture, but can't be sure we
          // support it, bail.
          return NULL;
        }
      }

      return new glxGraphicsBuffer(engine, this, name, fb_prop, win_prop,
                                   flags, gsg, host);
    }
  }

  // Third thing to try: a glxGraphicsPixmap.
  if (retry == 3) {
    if (!glx_support_pixmap) {
      return NULL;
    }

    if (((flags&BF_require_parasite)!=0)||
        ((flags&BF_require_window)!=0)||
        ((flags&BF_resizeable)!=0)||
        ((flags&BF_size_track_host)!=0)||
        ((flags&BF_can_bind_layered)!=0)) {
      return NULL;
    }

    if (((flags&BF_rtt_cumulative)!=0)||
        ((flags&BF_can_bind_every)!=0)) {
      return NULL;
    }

    return new glxGraphicsPixmap(engine, this, name, fb_prop, win_prop,
                                 flags, gsg, host);
  }

  // Nothing else left to try.
  return NULL;
}

////////////////////////////////////////////////////////////////////
//     Function: glxGraphicsPipe::make_callback_gsg
//       Access: Protected, Virtual
//  Description: This is called when make_output() is used to create a
//               CallbackGraphicsWindow.  If the GraphicsPipe can
//               construct a GSG that's not associated with any
//               particular window object, do so now, assuming the
//               correct graphics context has been set up externally.
////////////////////////////////////////////////////////////////////
PT(GraphicsStateGuardian) glxGraphicsPipe::
make_callback_gsg(GraphicsEngine *engine) {
  // We create a PosixGraphicsStateGuardian instead of a
  // glxGraphicsStateGuardian, because the externally-created context
  // might not have anything to do with the glx interface.
  return new PosixGraphicsStateGuardian(engine, this);
}
<commit_msg>Allow creating a buffer under a callback GSG<commit_after>// Filename: glxGraphicsPipe.cxx
// Created by:  mike (09Jan97)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University.  All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license.  You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////

#include "glxGraphicsPipe.h"
#include "glxGraphicsWindow.h"
#include "glxGraphicsBuffer.h"
#include "glxGraphicsPixmap.h"
#include "glxGraphicsStateGuardian.h"
#include "posixGraphicsStateGuardian.h"
#include "config_glxdisplay.h"
#include "frameBufferProperties.h"

TypeHandle glxGraphicsPipe::_type_handle;

////////////////////////////////////////////////////////////////////
//     Function: glxGraphicsPipe::Constructor
//       Access: Public
//  Description:
////////////////////////////////////////////////////////////////////
glxGraphicsPipe::
glxGraphicsPipe(const string &display) : x11GraphicsPipe(display) {
  if (_display == None) {
    // Some error must have occurred.
    return;
  }

  string display_spec (XDisplayString(_display));

  int errorBase, eventBase;
  if (!glXQueryExtension(_display, &errorBase, &eventBase)) {
    glxdisplay_cat.error()
      << "OpenGL GLX extension not supported on display \"" << display_spec
      << "\".\n";
    return;
  }
}

////////////////////////////////////////////////////////////////////
//     Function: glxGraphicsPipe::get_interface_name
//       Access: Published, Virtual
//  Description: Returns the name of the rendering interface
//               associated with this GraphicsPipe.  This is used to
//               present to the user to allow him/her to choose
//               between several possible GraphicsPipes available on a
//               particular platform, so the name should be meaningful
//               and unique for a given platform.
////////////////////////////////////////////////////////////////////
string glxGraphicsPipe::
get_interface_name() const {
  return "OpenGL";
}

////////////////////////////////////////////////////////////////////
//     Function: glxGraphicsPipe::pipe_constructor
//       Access: Public, Static
//  Description: This function is passed to the GraphicsPipeSelection
//               object to allow the user to make a default
//               glxGraphicsPipe.
////////////////////////////////////////////////////////////////////
PT(GraphicsPipe) glxGraphicsPipe::
pipe_constructor() {
  return new glxGraphicsPipe;
}

////////////////////////////////////////////////////////////////////
//     Function: glxGraphicsPipe::make_output
//       Access: Protected, Virtual
//  Description: Creates a new window on the pipe, if possible.
////////////////////////////////////////////////////////////////////
PT(GraphicsOutput) glxGraphicsPipe::
make_output(const string &name,
            const FrameBufferProperties &fb_prop,
            const WindowProperties &win_prop,
            int flags,
            GraphicsEngine *engine,
            GraphicsStateGuardian *gsg,
            GraphicsOutput *host,
            int retry,
            bool &precertify) {

  if (!_is_valid) {
    return NULL;
  }

  // This may not be a GLX GSG; it might be a callback GSG.
  PosixGraphicsStateGuardian *posixgsg = NULL;
  glxGraphicsStateGuardian *glxgsg = NULL;
  if (gsg != NULL) {
    DCAST_INTO_R(posixgsg, gsg, NULL);
    glxgsg = DCAST(glxGraphicsStateGuardian, posixgsg);
  }

  bool support_rtt;
  support_rtt = false;
  /*
    Currently, no support for glxGraphicsBuffer render-to-texture.
  if (glxgsg) {
     support_rtt =
      glxgsg -> get_supports_render_texture() &&
      support_render_texture;
  }
  */

  // First thing to try: a glxGraphicsWindow

  if (retry == 0) {
    if (gsg != NULL && glxgsg == NULL) {
      // We can't use a non-GLX GSG.
      return NULL;
    }
    if (((flags&BF_require_parasite)!=0)||
        ((flags&BF_refuse_window)!=0)||
        ((flags&BF_resizeable)!=0)||
        ((flags&BF_size_track_host)!=0)||
        ((flags&BF_rtt_cumulative)!=0)||
        ((flags&BF_can_bind_color)!=0)||
        ((flags&BF_can_bind_every)!=0)||
        ((flags&BF_can_bind_layered)!=0)) {
      return NULL;
    }
    return new glxGraphicsWindow(engine, this, name, fb_prop, win_prop,
                                 flags, gsg, host);
  }

  // Second thing to try: a GLGraphicsBuffer

  if (retry == 1) {
    if ((host==0)||
        (!gl_support_fbo)||
        ((flags&BF_require_parasite)!=0)||
        ((flags&BF_require_window)!=0)) {
      return NULL;
    }
    // Early failure - if we are sure that this buffer WONT
    // meet specs, we can bail out early.
    int _fbo_multisample = 0;
    if (!ConfigVariableBool("framebuffer-object-multisample", false, PRC_DESC("Enabled Multisample."))) {
      _fbo_multisample = 16;
    }
    if ((flags & BF_fb_props_optional)==0) {
      if ((fb_prop.get_indexed_color() > 0)||
          (fb_prop.get_back_buffers() > 0)||
          (fb_prop.get_accum_bits() > 0)||
          (fb_prop.get_multisamples() > _fbo_multisample)) {
        return NULL;
      }
    }
    // Early success - if we are sure that this buffer WILL
    // meet specs, we can precertify it.
    if ((posixgsg != 0) &&
        (posixgsg->is_valid()) &&
        (!posixgsg->needs_reset()) &&
        (posixgsg->_supports_framebuffer_object) &&
        (posixgsg->_glDrawBuffers != 0)&&
        (fb_prop.is_basic())) {
      precertify = true;
    }
    return new GLGraphicsBuffer(engine, this, name, fb_prop, win_prop,
                                flags, gsg, host);
  }

  // Third thing to try: a glxGraphicsBuffer
  if (glxgsg == NULL || glxgsg->_supports_fbconfig) {
    if (retry == 2) {
      if (!glx_support_pbuffer) {
        return NULL;
      }

      if (((flags&BF_require_parasite)!=0)||
          ((flags&BF_require_window)!=0)||
          ((flags&BF_resizeable)!=0)||
          ((flags&BF_size_track_host)!=0)||
          ((flags&BF_can_bind_layered)!=0)) {
        return NULL;
      }

      if (!support_rtt) {
        if (((flags&BF_rtt_cumulative)!=0)||
            ((flags&BF_can_bind_every)!=0)) {
          // If we require Render-to-Texture, but can't be sure we
          // support it, bail.
          return NULL;
        }
      }

      return new glxGraphicsBuffer(engine, this, name, fb_prop, win_prop,
                                   flags, gsg, host);
    }
  }

  // Third thing to try: a glxGraphicsPixmap.
  if (retry == 3) {
    if (!glx_support_pixmap) {
      return NULL;
    }

    if (((flags&BF_require_parasite)!=0)||
        ((flags&BF_require_window)!=0)||
        ((flags&BF_resizeable)!=0)||
        ((flags&BF_size_track_host)!=0)||
        ((flags&BF_can_bind_layered)!=0)) {
      return NULL;
    }

    if (((flags&BF_rtt_cumulative)!=0)||
        ((flags&BF_can_bind_every)!=0)) {
      return NULL;
    }

    return new glxGraphicsPixmap(engine, this, name, fb_prop, win_prop,
                                 flags, gsg, host);
  }

  // Nothing else left to try.
  return NULL;
}

////////////////////////////////////////////////////////////////////
//     Function: glxGraphicsPipe::make_callback_gsg
//       Access: Protected, Virtual
//  Description: This is called when make_output() is used to create a
//               CallbackGraphicsWindow.  If the GraphicsPipe can
//               construct a GSG that's not associated with any
//               particular window object, do so now, assuming the
//               correct graphics context has been set up externally.
////////////////////////////////////////////////////////////////////
PT(GraphicsStateGuardian) glxGraphicsPipe::
make_callback_gsg(GraphicsEngine *engine) {
  // We create a PosixGraphicsStateGuardian instead of a
  // glxGraphicsStateGuardian, because the externally-created context
  // might not have anything to do with the glx interface.
  return new PosixGraphicsStateGuardian(engine, this);
}
<|endoftext|>


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

#include "SkGLWidget.h"

SkGLWidget::SkGLWidget(SkDebugger* debugger) : QGLWidget() {
    this->setStyleSheet("QWidget {background-color: white; border: 1px solid #cccccc;}");
    fDebugger = debugger;
    fCurIntf = NULL;
    fCurContext = NULL;
    fGpuDevice = NULL;
    fCanvas = NULL;
}

SkGLWidget::~SkGLWidget() {
    SkSafeUnref(fCurIntf);
    SkSafeUnref(fCurContext);
    SkSafeUnref(fGpuDevice);
    SkSafeUnref(fCanvas);
}

void SkGLWidget::initializeGL() {
    fCurIntf = GrGLCreateNativeInterface();
    fCurContext = GrContext::Create(kOpenGL_GrBackend, (GrBackendContext) fCurIntf);
    GrBackendRenderTargetDesc desc = this->getDesc(this->width(), this->height());
    GrRenderTarget* curRenderTarget = fCurContext->wrapBackendRenderTarget(desc);
    fGpuDevice = new SkGpuDevice(fCurContext, curRenderTarget);
    fCanvas = new SkCanvas(fGpuDevice);
    curRenderTarget->unref();

    glClearColor(1, 1, 1, 0);
    glClearStencil(0);
    glClear(GL_STENCIL_BUFFER_BIT);
}

void SkGLWidget::resizeGL(int w, int h) {
    GrBackendRenderTargetDesc desc = this->getDesc(w, h);
    GrRenderTarget* curRenderTarget = fCurContext->wrapBackendRenderTarget(desc);
    SkSafeUnref(fGpuDevice);
    SkSafeUnref(fCanvas);
    fGpuDevice = new SkGpuDevice(fCurContext, curRenderTarget);
    fCanvas = new SkCanvas(fGpuDevice);
    fDebugger->resize(w, h);
    draw();
}

void SkGLWidget::paintGL() {
    if (!this->isHidden()) {
        fDebugger->draw(fCanvas);
        // TODO(chudy): Implement an optional flush button in Gui.
        fCanvas->flush();
        emit drawComplete();
    }
}

GrBackendRenderTargetDesc SkGLWidget::getDesc(int w, int h) {
    GrBackendRenderTargetDesc desc;
    desc.fWidth = SkScalarRound(this->width());
    desc.fHeight = SkScalarRound(this->height());
    desc.fConfig = kSkia8888_GrPixelConfig;
    GR_GL_GetIntegerv(fCurIntf, GR_GL_SAMPLES, &desc.fSampleCnt);
    GR_GL_GetIntegerv(fCurIntf, GR_GL_STENCIL_BITS, &desc.fStencilBits);
    GrGLint buffer;
    GR_GL_GetIntegerv(fCurIntf, GR_GL_FRAMEBUFFER_BINDING, &buffer);
    desc.fRenderTargetHandle = buffer;

    return desc;
}
<commit_msg>Fix uninitialized Render Target origin issue in debugger<commit_after>
/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkGLWidget.h"

SkGLWidget::SkGLWidget(SkDebugger* debugger) : QGLWidget() {
    this->setStyleSheet("QWidget {background-color: white; border: 1px solid #cccccc;}");
    fDebugger = debugger;
    fCurIntf = NULL;
    fCurContext = NULL;
    fGpuDevice = NULL;
    fCanvas = NULL;
}

SkGLWidget::~SkGLWidget() {
    SkSafeUnref(fCurIntf);
    SkSafeUnref(fCurContext);
    SkSafeUnref(fGpuDevice);
    SkSafeUnref(fCanvas);
}

void SkGLWidget::initializeGL() {
    fCurIntf = GrGLCreateNativeInterface();
    fCurContext = GrContext::Create(kOpenGL_GrBackend, (GrBackendContext) fCurIntf);
    GrBackendRenderTargetDesc desc = this->getDesc(this->width(), this->height());
    desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
    GrRenderTarget* curRenderTarget = fCurContext->wrapBackendRenderTarget(desc);
    fGpuDevice = new SkGpuDevice(fCurContext, curRenderTarget);
    fCanvas = new SkCanvas(fGpuDevice);
    curRenderTarget->unref();

    glClearColor(1, 1, 1, 0);
    glClearStencil(0);
    glClear(GL_STENCIL_BUFFER_BIT);
}

void SkGLWidget::resizeGL(int w, int h) {
    GrBackendRenderTargetDesc desc = this->getDesc(w, h);
    desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
    GrRenderTarget* curRenderTarget = fCurContext->wrapBackendRenderTarget(desc);
    SkSafeUnref(fGpuDevice);
    SkSafeUnref(fCanvas);
    fGpuDevice = new SkGpuDevice(fCurContext, curRenderTarget);
    fCanvas = new SkCanvas(fGpuDevice);
    fDebugger->resize(w, h);
    draw();
}

void SkGLWidget::paintGL() {
    if (!this->isHidden()) {
        fDebugger->draw(fCanvas);
        // TODO(chudy): Implement an optional flush button in Gui.
        fCanvas->flush();
        emit drawComplete();
    }
}

GrBackendRenderTargetDesc SkGLWidget::getDesc(int w, int h) {
    GrBackendRenderTargetDesc desc;
    desc.fWidth = SkScalarRound(this->width());
    desc.fHeight = SkScalarRound(this->height());
    desc.fConfig = kSkia8888_GrPixelConfig;
    GR_GL_GetIntegerv(fCurIntf, GR_GL_SAMPLES, &desc.fSampleCnt);
    GR_GL_GetIntegerv(fCurIntf, GR_GL_STENCIL_BITS, &desc.fStencilBits);
    GrGLint buffer;
    GR_GL_GetIntegerv(fCurIntf, GR_GL_FRAMEBUFFER_BINDING, &buffer);
    desc.fRenderTargetHandle = buffer;

    return desc;
}
<|endoftext|>


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

#include "SkGLWidget.h"

#if SK_SUPPORT_GPU

SkGLWidget::SkGLWidget(SkDebugger* debugger) : QGLWidget() {
    fDebugger = debugger;
}

SkGLWidget::~SkGLWidget() {
}

void SkGLWidget::setSampleCount(int sampleCount) {
    QGLFormat currentFormat = format();
    currentFormat.setSampleBuffers(sampleCount > 0);
    currentFormat.setSamples(sampleCount);
    setFormat(currentFormat);
}

void SkGLWidget::initializeGL() {
    if (!fCurIntf) {
        fCurIntf.reset(GrGLCreateNativeInterface());
    }
    if (!fCurIntf) {
        return;
    }
    // The call may come multiple times, for example after setSampleCount().  The QGLContext will be
    // different, but we do not have a mechanism to catch the destroying of QGLContext, so that
    // proper resource cleanup could be made.
    if (fCurContext) {
        fCurContext->abandonContext();
    }
    fGpuDevice.reset(nullptr);
    fCanvas.reset(nullptr);

    fCurContext.reset(GrContext::Create(kOpenGL_GrBackend, (GrBackendContext) fCurIntf.get()));
}

void SkGLWidget::createRenderTarget() {
    if (!fCurContext) {
        return;
    }

    glDisable(GL_SCISSOR_TEST);
    glStencilMask(0xffffffff);
    glClearStencil(0);
    glClear(GL_STENCIL_BUFFER_BIT);
    fCurContext->resetContext();

    fGpuDevice.reset(nullptr);
    fCanvas.reset(nullptr);

    GrBackendRenderTargetDesc desc = this->getDesc(this->width(), this->height());
    desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
    sk_sp<GrRenderTarget> curRenderTarget(
            fCurContext->textureProvider()->wrapBackendRenderTarget(desc));
    SkSurfaceProps props(0, kUnknown_SkPixelGeometry);
    fGpuDevice.reset(SkGpuDevice::Make(std::move(curRenderTarget), &props,
                                       SkGpuDevice::kUninit_InitContents).release());
    fCanvas.reset(new SkCanvas(fGpuDevice));
}

void SkGLWidget::resizeGL(int w, int h) {
    SkASSERT(w == this->width() && h == this->height());
    this->createRenderTarget();
}

void SkGLWidget::paintGL() {
    if (!this->isHidden() && fCanvas) {
        fCurContext->resetContext();
        fDebugger->draw(fCanvas.get());
        // TODO(chudy): Implement an optional flush button in Gui.
        fCanvas->flush();
        Q_EMIT drawComplete();
    }
}

GrBackendRenderTargetDesc SkGLWidget::getDesc(int w, int h) {
    GrBackendRenderTargetDesc desc;
    desc.fWidth = SkScalarRoundToInt(this->width());
    desc.fHeight = SkScalarRoundToInt(this->height());
    desc.fConfig = kSkia8888_GrPixelConfig;
    GR_GL_GetIntegerv(fCurIntf, GR_GL_SAMPLES, &desc.fSampleCnt);
    GR_GL_GetIntegerv(fCurIntf, GR_GL_STENCIL_BITS, &desc.fStencilBits);
    GrGLint buffer;
    GR_GL_GetIntegerv(fCurIntf, GR_GL_FRAMEBUFFER_BINDING, &buffer);
    desc.fRenderTargetHandle = buffer;

    return desc;
}

#endif
<commit_msg>Fix debugger build by specifying nullptr for color space.<commit_after>
/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkGLWidget.h"

#if SK_SUPPORT_GPU

SkGLWidget::SkGLWidget(SkDebugger* debugger) : QGLWidget() {
    fDebugger = debugger;
}

SkGLWidget::~SkGLWidget() {
}

void SkGLWidget::setSampleCount(int sampleCount) {
    QGLFormat currentFormat = format();
    currentFormat.setSampleBuffers(sampleCount > 0);
    currentFormat.setSamples(sampleCount);
    setFormat(currentFormat);
}

void SkGLWidget::initializeGL() {
    if (!fCurIntf) {
        fCurIntf.reset(GrGLCreateNativeInterface());
    }
    if (!fCurIntf) {
        return;
    }
    // The call may come multiple times, for example after setSampleCount().  The QGLContext will be
    // different, but we do not have a mechanism to catch the destroying of QGLContext, so that
    // proper resource cleanup could be made.
    if (fCurContext) {
        fCurContext->abandonContext();
    }
    fGpuDevice.reset(nullptr);
    fCanvas.reset(nullptr);

    fCurContext.reset(GrContext::Create(kOpenGL_GrBackend, (GrBackendContext) fCurIntf.get()));
}

void SkGLWidget::createRenderTarget() {
    if (!fCurContext) {
        return;
    }

    glDisable(GL_SCISSOR_TEST);
    glStencilMask(0xffffffff);
    glClearStencil(0);
    glClear(GL_STENCIL_BUFFER_BIT);
    fCurContext->resetContext();

    fGpuDevice.reset(nullptr);
    fCanvas.reset(nullptr);

    GrBackendRenderTargetDesc desc = this->getDesc(this->width(), this->height());
    desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
    sk_sp<GrRenderTarget> curRenderTarget(
            fCurContext->textureProvider()->wrapBackendRenderTarget(desc));
    SkSurfaceProps props(0, kUnknown_SkPixelGeometry);
    fGpuDevice.reset(SkGpuDevice::Make(std::move(curRenderTarget), nullptr, &props,
                                       SkGpuDevice::kUninit_InitContents).release());
    fCanvas.reset(new SkCanvas(fGpuDevice));
}

void SkGLWidget::resizeGL(int w, int h) {
    SkASSERT(w == this->width() && h == this->height());
    this->createRenderTarget();
}

void SkGLWidget::paintGL() {
    if (!this->isHidden() && fCanvas) {
        fCurContext->resetContext();
        fDebugger->draw(fCanvas.get());
        // TODO(chudy): Implement an optional flush button in Gui.
        fCanvas->flush();
        Q_EMIT drawComplete();
    }
}

GrBackendRenderTargetDesc SkGLWidget::getDesc(int w, int h) {
    GrBackendRenderTargetDesc desc;
    desc.fWidth = SkScalarRoundToInt(this->width());
    desc.fHeight = SkScalarRoundToInt(this->height());
    desc.fConfig = kSkia8888_GrPixelConfig;
    GR_GL_GetIntegerv(fCurIntf, GR_GL_SAMPLES, &desc.fSampleCnt);
    GR_GL_GetIntegerv(fCurIntf, GR_GL_STENCIL_BITS, &desc.fStencilBits);
    GrGLint buffer;
    GR_GL_GetIntegerv(fCurIntf, GR_GL_FRAMEBUFFER_BINDING, &buffer);
    desc.fRenderTargetHandle = buffer;

    return desc;
}

#endif
<|endoftext|>


<commit_before>#include "DSL_utility.hpp"

using namespace std;

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// elliptic curve pairing
//

bool validPairingName(const string& name) {
    return pairingBN128(name) || pairingEdwards(name);
}

bool pairingBN128(const string& name) {
    return "BN128" == name;
}

bool pairingEdwards(const string& name) {
    return "Edwards" == name;
}

////////////////////////////////////////////////////////////////////////////////
// SHA-2
//

bool validSHA2Name(const string& shaBits) {
    return
        ("1" == shaBits) ||
        ("224" == shaBits) ||
        ("256" == shaBits) ||
        ("384" == shaBits) ||
        ("512" == shaBits) ||
        ("512_224" == shaBits) ||
        ("512_256" == shaBits);
}

bool validSHA2Name(const size_t shaBits) {
    return
        (1 == shaBits) ||
        (224 == shaBits) ||
        (256 == shaBits) ||
        (384 == shaBits) ||
        (512 == shaBits);
}

bool nameSHA256(const string& shaBits) {
    return "256" == shaBits;
}

bool nameSHA512(const string& shaBits) {
    return "512" == shaBits;
}

} // namespace snarkfront
<commit_msg>validAESName<commit_after>#include "DSL_utility.hpp"

using namespace std;

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// elliptic curve pairing
//

bool validPairingName(const string& name) {
    return pairingBN128(name) || pairingEdwards(name);
}

bool pairingBN128(const string& name) {
    return "BN128" == name;
}

bool pairingEdwards(const string& name) {
    return "Edwards" == name;
}

////////////////////////////////////////////////////////////////////////////////
// SHA-2
//

bool validSHA2Name(const string& shaBits) {
    return
        ("1" == shaBits) ||
        ("224" == shaBits) ||
        ("256" == shaBits) ||
        ("384" == shaBits) ||
        ("512" == shaBits) ||
        ("512_224" == shaBits) ||
        ("512_256" == shaBits);
}

bool validSHA2Name(const size_t shaBits) {
    return
        (1 == shaBits) ||
        (224 == shaBits) ||
        (256 == shaBits) ||
        (384 == shaBits) ||
        (512 == shaBits);
}

bool nameSHA256(const string& shaBits) {
    return "256" == shaBits;
}

bool nameSHA512(const string& shaBits) {
    return "512" == shaBits;
}

////////////////////////////////////////////////////////////////////////////////
// AES
//

bool validAESName(const size_t aesBits) {
    return 128 == aesBits || 192 == aesBits || 256 == aesBits;
}

} // namespace snarkfront
<|endoftext|>


<commit_before>/***************************************************************************
 *  mng/mng.h
 *
 *  Part of the STXXL. See http://stxxl.sourceforge.net
 *
 *  Copyright (C) 2002-2004 Roman Dementiev <dementiev@mpi-sb.mpg.de>
 *  Copyright (C) 2008 Andreas Beckmann <beckmann@cs.uni-frankfurt.de>
 *
 *  Distributed under the Boost Software License, Version 1.0.
 *  (See accompanying file LICENSE_1_0.txt or copy at
 *  http://www.boost.org/LICENSE_1_0.txt)
 **************************************************************************/

#include <sstream>
#include <stxxl/mng>
#include <stxxl/bits/io/io.h>
#include <stxxl/bits/version.h>

__STXXL_BEGIN_NAMESPACE

void DiskAllocator::dump()
{
    int64 total = 0;
    sortseq::const_iterator cur = free_space.begin();
    STXXL_ERRMSG("Free regions dump:");
    for ( ; cur != free_space.end(); ++cur)
    {
        STXXL_ERRMSG("Free chunk: begin: " << (cur->first) << " size: " << (cur->second));
        total += cur->second;
    }
    STXXL_ERRMSG("Total bytes: " << total);
}

void config::init(const char * config_path)
{
    logger::get_instance();
    STXXL_MSG(get_version_string());
    std::vector<DiskEntry> flash_props;
    std::ifstream cfg_file(config_path);
    if (!cfg_file)
    {
        STXXL_ERRMSG("Warning: no config file found.");
        STXXL_ERRMSG("Using default disk configuration.");
#ifndef BOOST_MSVC
        DiskEntry entry1 = { "/var/tmp/stxxl", "syscall", 1000 * 1024 * 1024, true };
#else
        DiskEntry entry1 = { "", "wincall", 1000 * 1024 * 1024, true };
        char * tmpstr = new char[255];
        stxxl_check_ne_0(GetTempPath(255, tmpstr), resource_error);
        entry1.path = tmpstr;
        entry1.path += "stxxl";
        delete[] tmpstr;
#endif
#if 0
        DiskEntry entry2 =
        { "/tmp/stxxl1", "mmap", 100 * 1024 * 1024, true };
        DiskEntry entry3 =
        { "/tmp/stxxl2", "simdisk", 1000 * 1024 * 1024, false };
#endif
        disks_props.push_back(entry1);
        //disks_props.push_back(entry2);
        //disks_props.push_back(entry3);
    }
    else
    {
        std::string line;

        while (cfg_file >> line)
        {
            std::vector<std::string> tmp = split(line, "=");
            bool is_disk;

            if (tmp[0][0] == '#')
            { }
            else if ((is_disk = (tmp[0] == "disk")) || tmp[0] == "flash")
            {
                tmp = split(tmp[1], ",");
                DiskEntry entry = {
                    tmp[0], tmp[2],
                    int64(atoi(tmp[1].c_str())) * int64(1024 * 1024),
                    false
                };
                if (is_disk)
                    disks_props.push_back(entry);
                else
                    flash_props.push_back(entry);
            }
            else
            {
                std::cerr << "Unknown token " <<
                tmp[0] << std::endl;
            }
        }
        cfg_file.close();
    }

    // put flash devices after regular disks
    first_flash = disks_props.size();
    disks_props.insert(disks_props.end(), flash_props.begin(), flash_props.end());

    if (disks_props.empty())
    {
        STXXL_THROW(std::runtime_error, "config::config", "No disks found in '" << config_path << "' .");
    }
    else
    {
#ifdef STXXL_VERBOSE_DISKS
        for (std::vector<DiskEntry>::const_iterator it =
                 disks_props.begin(); it != disks_props.end();
             it++)
        {
            STXXL_MSG("Disk '" << (*it).path << "' is allocated, space: " <<
                      ((*it).size) / (1024 * 1024) <<
                      " MiB, I/O implementation: " << (*it).io_impl);
        }
#else
        int64 total_size = 0;
        for (std::vector<DiskEntry>::const_iterator it =
                 disks_props.begin(); it != disks_props.end();
             it++)
            total_size += (*it).size;

        STXXL_MSG("" << disks_props.size() << " disks are allocated, total space: " <<
                  (total_size / (1024 * 1024)) <<
                  " MiB");
#endif
    }
}

file * FileCreator::create(const std::string & io_impl,
                                  const std::string & filename,
                                  int options, int disk)
{
    if (io_impl == "syscall")
    {
        ufs_file_base * result = new syscall_file(filename, options, disk);
        result->lock();
        return result;
    }
    else if (io_impl == "fileperblock_syscall")
    {
        fileperblock_file<syscall_file> * result = new fileperblock_file<syscall_file>(filename, options, disk);
        result->lock();
        return result;
    }
#ifndef BOOST_MSVC
    else if (io_impl == "mmap")
    {
        ufs_file_base * result = new mmap_file(filename, options, disk);
        result->lock();
        return result;
    }
    else if (io_impl == "fileperblock_mmap")
    {
        fileperblock_file<mmap_file> * result = new fileperblock_file<mmap_file>(filename, options, disk);
        result->lock();
        return result;
    }
    else if (io_impl == "simdisk")
    {
        ufs_file_base * result = new sim_disk_file(filename, options, disk);
        result->lock();
        return result;
    }
#else
    else if (io_impl == "wincall")
    {
        wfs_file_base * result = new wincall_file(filename, options, disk);
        result->lock();
        return result;
    }
    else if (io_impl == "fileperblock_wincall")
    {
        fileperblock_file<wincall_file> * result = new fileperblock_file<wincall_file>(filename, options, disk);
        result->lock();
        return result;
    }
#endif
#ifdef STXXL_BOOST_CONFIG
    else if (io_impl == "boostfd")
    {
        boostfd_file* result = new boostfd_file(filename, options, disk);
        result->lock();
        return result;
    }
    else if (io_impl == "fileperblock_boostfd")
    {
        fileperblock_file<boostfd_file> * result = new fileperblock_file<boostfd_file>(filename, options, disk);
        result->lock();
        return result;
    }
#endif
    else if (io_impl == "memory")
    {
        mem_file * result = new mem_file(disk);
        result->lock();
        return result;
    }
    else if (io_impl == "wbtl")
    {
        ufs_file_base * backend = new syscall_file(filename, options); // FIXME: ID
        wbtl_file * result = new stxxl::wbtl_file(backend, 16 * 1024 * 1024, 2, disk);
        result->lock();
        return result;
    }

    STXXL_THROW(std::runtime_error, "FileCreator::create", "Unsupported disk I/O implementation " <<
                io_impl << " .");

    return NULL;
}

block_manager::block_manager()
{
    FileCreator fc;
    debugmon::get_instance();
    config * cfg = config::get_instance();

    ndisks = cfg->disks_number();
    disk_allocators = new DiskAllocator *[ndisks];
    disk_files = new file *[ndisks];

    for (unsigned i = 0; i < ndisks; i++)
    {
        disk_files[i] = fc.create(cfg->disk_io_impl(i),
                                  cfg->disk_path(i),
                                  file::CREAT | file::RDWR | file::DIRECT, i);
        disk_files[i]->set_size(cfg->disk_size(i));
        disk_allocators[i] = new DiskAllocator(cfg->disk_size(i));
    }
}

block_manager::~block_manager()
{
    STXXL_VERBOSE1("Block manager destructor");
    for (unsigned i = 0; i < ndisks; i++)
    {
        delete disk_allocators[i];
        delete disk_files[i];
    }
    delete[] disk_allocators;
    delete[] disk_files;
}

__STXXL_END_NAMESPACE
// vim: et:ts=4:sw=4
<commit_msg>add wbtl hack to not use disk id -1 for backend disks<commit_after>/***************************************************************************
 *  mng/mng.h
 *
 *  Part of the STXXL. See http://stxxl.sourceforge.net
 *
 *  Copyright (C) 2002-2004 Roman Dementiev <dementiev@mpi-sb.mpg.de>
 *  Copyright (C) 2008 Andreas Beckmann <beckmann@cs.uni-frankfurt.de>
 *
 *  Distributed under the Boost Software License, Version 1.0.
 *  (See accompanying file LICENSE_1_0.txt or copy at
 *  http://www.boost.org/LICENSE_1_0.txt)
 **************************************************************************/

#include <sstream>
#include <stxxl/mng>
#include <stxxl/bits/io/io.h>
#include <stxxl/bits/version.h>

__STXXL_BEGIN_NAMESPACE

void DiskAllocator::dump()
{
    int64 total = 0;
    sortseq::const_iterator cur = free_space.begin();
    STXXL_ERRMSG("Free regions dump:");
    for ( ; cur != free_space.end(); ++cur)
    {
        STXXL_ERRMSG("Free chunk: begin: " << (cur->first) << " size: " << (cur->second));
        total += cur->second;
    }
    STXXL_ERRMSG("Total bytes: " << total);
}

void config::init(const char * config_path)
{
    logger::get_instance();
    STXXL_MSG(get_version_string());
    std::vector<DiskEntry> flash_props;
    std::ifstream cfg_file(config_path);
    if (!cfg_file)
    {
        STXXL_ERRMSG("Warning: no config file found.");
        STXXL_ERRMSG("Using default disk configuration.");
#ifndef BOOST_MSVC
        DiskEntry entry1 = { "/var/tmp/stxxl", "syscall", 1000 * 1024 * 1024, true };
#else
        DiskEntry entry1 = { "", "wincall", 1000 * 1024 * 1024, true };
        char * tmpstr = new char[255];
        stxxl_check_ne_0(GetTempPath(255, tmpstr), resource_error);
        entry1.path = tmpstr;
        entry1.path += "stxxl";
        delete[] tmpstr;
#endif
#if 0
        DiskEntry entry2 =
        { "/tmp/stxxl1", "mmap", 100 * 1024 * 1024, true };
        DiskEntry entry3 =
        { "/tmp/stxxl2", "simdisk", 1000 * 1024 * 1024, false };
#endif
        disks_props.push_back(entry1);
        //disks_props.push_back(entry2);
        //disks_props.push_back(entry3);
    }
    else
    {
        std::string line;

        while (cfg_file >> line)
        {
            std::vector<std::string> tmp = split(line, "=");
            bool is_disk;

            if (tmp[0][0] == '#')
            { }
            else if ((is_disk = (tmp[0] == "disk")) || tmp[0] == "flash")
            {
                tmp = split(tmp[1], ",");
                DiskEntry entry = {
                    tmp[0], tmp[2],
                    int64(atoi(tmp[1].c_str())) * int64(1024 * 1024),
                    false
                };
                if (is_disk)
                    disks_props.push_back(entry);
                else
                    flash_props.push_back(entry);
            }
            else
            {
                std::cerr << "Unknown token " <<
                tmp[0] << std::endl;
            }
        }
        cfg_file.close();
    }

    // put flash devices after regular disks
    first_flash = disks_props.size();
    disks_props.insert(disks_props.end(), flash_props.begin(), flash_props.end());

    if (disks_props.empty())
    {
        STXXL_THROW(std::runtime_error, "config::config", "No disks found in '" << config_path << "' .");
    }
    else
    {
#ifdef STXXL_VERBOSE_DISKS
        for (std::vector<DiskEntry>::const_iterator it =
                 disks_props.begin(); it != disks_props.end();
             it++)
        {
            STXXL_MSG("Disk '" << (*it).path << "' is allocated, space: " <<
                      ((*it).size) / (1024 * 1024) <<
                      " MiB, I/O implementation: " << (*it).io_impl);
        }
#else
        int64 total_size = 0;
        for (std::vector<DiskEntry>::const_iterator it =
                 disks_props.begin(); it != disks_props.end();
             it++)
            total_size += (*it).size;

        STXXL_MSG("" << disks_props.size() << " disks are allocated, total space: " <<
                  (total_size / (1024 * 1024)) <<
                  " MiB");
#endif
    }
}

file * FileCreator::create(const std::string & io_impl,
                                  const std::string & filename,
                                  int options, int disk)
{
    if (io_impl == "syscall")
    {
        ufs_file_base * result = new syscall_file(filename, options, disk);
        result->lock();
        return result;
    }
    else if (io_impl == "fileperblock_syscall")
    {
        fileperblock_file<syscall_file> * result = new fileperblock_file<syscall_file>(filename, options, disk);
        result->lock();
        return result;
    }
#ifndef BOOST_MSVC
    else if (io_impl == "mmap")
    {
        ufs_file_base * result = new mmap_file(filename, options, disk);
        result->lock();
        return result;
    }
    else if (io_impl == "fileperblock_mmap")
    {
        fileperblock_file<mmap_file> * result = new fileperblock_file<mmap_file>(filename, options, disk);
        result->lock();
        return result;
    }
    else if (io_impl == "simdisk")
    {
        ufs_file_base * result = new sim_disk_file(filename, options, disk);
        result->lock();
        return result;
    }
#else
    else if (io_impl == "wincall")
    {
        wfs_file_base * result = new wincall_file(filename, options, disk);
        result->lock();
        return result;
    }
    else if (io_impl == "fileperblock_wincall")
    {
        fileperblock_file<wincall_file> * result = new fileperblock_file<wincall_file>(filename, options, disk);
        result->lock();
        return result;
    }
#endif
#ifdef STXXL_BOOST_CONFIG
    else if (io_impl == "boostfd")
    {
        boostfd_file* result = new boostfd_file(filename, options, disk);
        result->lock();
        return result;
    }
    else if (io_impl == "fileperblock_boostfd")
    {
        fileperblock_file<boostfd_file> * result = new fileperblock_file<boostfd_file>(filename, options, disk);
        result->lock();
        return result;
    }
#endif
    else if (io_impl == "memory")
    {
        mem_file * result = new mem_file(disk);
        result->lock();
        return result;
    }
    else if (io_impl == "wbtl")
    {
        ufs_file_base * backend = new syscall_file(filename, options, disk + 1000); // FIXME: ID
        wbtl_file * result = new stxxl::wbtl_file(backend, 16 * 1024 * 1024, 2, disk);
        result->lock();
        return result;
    }

    STXXL_THROW(std::runtime_error, "FileCreator::create", "Unsupported disk I/O implementation " <<
                io_impl << " .");

    return NULL;
}

block_manager::block_manager()
{
    FileCreator fc;
    debugmon::get_instance();
    config * cfg = config::get_instance();

    ndisks = cfg->disks_number();
    disk_allocators = new DiskAllocator *[ndisks];
    disk_files = new file *[ndisks];

    for (unsigned i = 0; i < ndisks; i++)
    {
        disk_files[i] = fc.create(cfg->disk_io_impl(i),
                                  cfg->disk_path(i),
                                  file::CREAT | file::RDWR | file::DIRECT, i);
        disk_files[i]->set_size(cfg->disk_size(i));
        disk_allocators[i] = new DiskAllocator(cfg->disk_size(i));
    }
}

block_manager::~block_manager()
{
    STXXL_VERBOSE1("Block manager destructor");
    for (unsigned i = 0; i < ndisks; i++)
    {
        delete disk_allocators[i];
        delete disk_files[i];
    }
    delete[] disk_allocators;
    delete[] disk_files;
}

__STXXL_END_NAMESPACE
// vim: et:ts=4:sw=4
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2008-2010, Image Engine Design Inc. 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 Image Engine Design nor the names of any
//       other contributors to this software 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 "IECoreGL/NameStateComponent.h"

#include "IECore/Exception.h"

#include "boost/format.hpp"

using namespace IECoreGL;

IE_CORE_DEFINERUNTIMETYPED( NameStateComponent );

NameStateComponent::NameMap NameStateComponent::g_nameMap;
tbb::spin_rw_mutex NameStateComponent::g_nameMapMutex;
StateComponent::Description<NameStateComponent> NameStateComponent::g_description;

NameStateComponent::NameStateComponent( const std::string &name )
{
	Mutex::scoped_lock lock( g_nameMapMutex, true ); // write lock
	m_it = g_nameMap.insert( NamePair( name, g_nameMap.size() ) ).first;
}

NameStateComponent::~NameStateComponent()
{
}

const std::string &NameStateComponent::name() const
{
	Mutex::scoped_lock lock( g_nameMapMutex, false ); // read-only lock
	return (*m_it).first.value();
}

GLuint NameStateComponent::glName() const
{
	Mutex::scoped_lock lock( g_nameMapMutex, false ); // read-only lock
	return m_it->second;
}

void NameStateComponent::bind() const
{
	Mutex::scoped_lock lock( g_nameMapMutex, false ); // read-only lock
	glLoadName( m_it->second );
}

const std::string &NameStateComponent::nameFromGLName( GLuint glName )
{
	Mutex::scoped_lock lock( g_nameMapMutex, false ); // read-only lock
	const NameMap::nth_index<1>::type &index = g_nameMap.get<1>();
	NameMap::nth_index<1>::type::const_iterator it = index.find( glName );
	if( it==index.end() )
	{
		throw IECore::InvalidArgumentException( boost::str(
				boost::format( "NameStateComponent::nameFromGLName : Invalid glName (%1%)" ) % glName
			)
		);
	}
	return it->first.value();
}
<commit_msg>Optimizing access to global name map and not locking when just using the iterator stored on the NameStateComponent instance.<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2008-2010, Image Engine Design Inc. 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 Image Engine Design nor the names of any
//       other contributors to this software 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 "IECoreGL/NameStateComponent.h"

#include "IECore/Exception.h"

#include "boost/format.hpp"

using namespace IECoreGL;

IE_CORE_DEFINERUNTIMETYPED( NameStateComponent );

NameStateComponent::NameMap NameStateComponent::g_nameMap;
tbb::spin_rw_mutex NameStateComponent::g_nameMapMutex;
StateComponent::Description<NameStateComponent> NameStateComponent::g_description;

NameStateComponent::NameStateComponent( const std::string &name )
{
	Mutex::scoped_lock lock( g_nameMapMutex, false ); // read-only lock
	const NameMap::nth_index<0>::type &index = g_nameMap.get<0>();
	NameMap::nth_index<0>::type::const_iterator it = index.find( name );
	if( it!=g_nameMap.end() )
	{
		m_it = it;
	}
	else
	{
		lock.upgrade_to_writer();
		m_it = g_nameMap.insert( NamePair( name, g_nameMap.size() ) ).first;
	}

}

NameStateComponent::~NameStateComponent()
{
}

const std::string &NameStateComponent::name() const
{
	return (*m_it).first.value();
}

GLuint NameStateComponent::glName() const
{
	return m_it->second;
}

void NameStateComponent::bind() const
{
	glLoadName( m_it->second );
}

const std::string &NameStateComponent::nameFromGLName( GLuint glName )
{
	Mutex::scoped_lock lock( g_nameMapMutex, false ); // read-only lock
	const NameMap::nth_index<1>::type &index = g_nameMap.get<1>();
	NameMap::nth_index<1>::type::const_iterator it = index.find( glName );
	if( it==index.end() )
	{
		throw IECore::InvalidArgumentException( boost::str(
				boost::format( "NameStateComponent::nameFromGLName : Invalid glName (%1%)" ) % glName
			)
		);
	}
	return it->first.value();
}
<|endoftext|>


<commit_before>#include "overviewpage.h"
#include "ui_overviewpage.h"

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

#include <QAbstractItemDelegate>
#include <QPainter>
#include <QTimer>

#define DECORATION_SIZE 64
#define NUM_ITEMS 3

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

    }

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

        QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
        QRect mainRect = option.rect;
        QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));
        int xspace = DECORATION_SIZE + 8;
        int ypad = 6;
        int halfheight = (mainRect.height() - 2*ypad)/2;
        QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight);
        QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight);
        icon.paint(painter, decorationRect);

        QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();
        QString address = index.data(Qt::DisplayRole).toString();
        qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();
        bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();
        QVariant value = index.data(Qt::ForegroundRole);
        QColor foreground = option.palette.color(QPalette::Text);
        if(value.canConvert<QBrush>())
        {
            QBrush brush = qvariant_cast<QBrush>(value);
            foreground = brush.color();
        }

        painter->setPen(foreground);
        painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address);

        if(amount < 0)
        {
            foreground = COLOR_NEGATIVE;
        }
        else if(!confirmed)
        {
            foreground = COLOR_UNCONFIRMED;
        }
        else
        {
            foreground = option.palette.color(QPalette::Text);
        }
        painter->setPen(foreground);
        QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true);
        if(!confirmed)
        {
            amountText = QString("[") + amountText + QString("]");
        }
        painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText);

        painter->setPen(option.palette.color(QPalette::Text));
        painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date));

        painter->restore();
    }

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

    int unit;

};
#include "overviewpage.moc"

OverviewPage::OverviewPage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::OverviewPage),
    clientModel(0),
    walletModel(0),
    currentBalance(-1),
    currentUnconfirmedBalance(-1),
    currentImmatureBalance(-1),
    txdelegate(new TxViewDelegate()),
    filter(0)
{
    ui->setupUi(this);

    // Recent transactions
    ui->listTransactions->setItemDelegate(txdelegate);
    ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));
    ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));
    ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);

    connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(darkSendStatus()));
    timer->start(333);

    // init "out of sync" warning labels
    ui->labelWalletStatus->setText("(" + tr("out of sync") + ")");
    ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")");

    showingDarkSendMessage = 0;
    darksendActionCheck = 0;

    if(fMasterNode){
        ui->toggleDarksend->setText("(Disabled)");
        ui->toggleDarksend->setEnabled(false);
    }else if(!fEnableDarksend){
        ui->toggleDarksend->setText("Start Darksend Mixing");
    } else {
        ui->toggleDarksend->setText("Stop Darksend Mixing");
    }

    // start with displaying the "out of sync" warnings
    showOutOfSyncWarning(true);
}

void OverviewPage::handleTransactionClicked(const QModelIndex &index)
{
    if(filter)
        emit transactionClicked(filter->mapToSource(index));
}

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

void OverviewPage::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance, qint64 anonymizedBalance)
{
    int unit = walletModel->getOptionsModel()->getDisplayUnit();
    currentBalance = balance;
    currentUnconfirmedBalance = unconfirmedBalance;
    currentImmatureBalance = immatureBalance;
    currentAnonymizedBalance = anonymizedBalance;
    ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));
    ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance));
    ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance));
    ui->labelAnonymized->setText(BitcoinUnits::formatWithUnit(unit, anonymizedBalance));

    // only show immature (newly mined) balance if it's non-zero, so as not to complicate things
    // for the non-mining users
    bool showImmature = immatureBalance != 0;
    ui->labelImmature->setVisible(showImmature);
    ui->labelImmatureText->setVisible(showImmature);
}

void OverviewPage::setClientModel(ClientModel *model)
{
    this->clientModel = model;
    if(model)
    {
        // Show warning if this is a prerelease version
        connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString)));
        updateAlerts(model->getStatusBarWarnings());
    }
}

void OverviewPage::setWalletModel(WalletModel *model)
{
    this->walletModel = model;
    if(model && model->getOptionsModel())
    {
        // Set up transaction list
        filter = new TransactionFilterProxy();
        filter->setSourceModel(model->getTransactionTableModel());
        filter->setLimit(NUM_ITEMS);
        filter->setDynamicSortFilter(true);
        filter->setSortRole(Qt::EditRole);
        filter->sort(TransactionTableModel::Status, Qt::DescendingOrder);

        ui->listTransactions->setModel(filter);
        ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);

        // Keep up to date with wallet
        setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getAnonymizedBalance());
        connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64)));

        connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));

        connect(ui->runAutoDenom, SIGNAL(clicked()), this, SLOT(runDoAutomaticDenomination()));
        connect(ui->toggleDarksend, SIGNAL(clicked()), this, SLOT(toggleDarksend()));
    }

    // update the display unit, to not use the default ("BTC")
    updateDisplayUnit();
}

void OverviewPage::updateDisplayUnit()
{
    if(walletModel && walletModel->getOptionsModel())
    {
        if(currentBalance != -1)
            setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance, currentAnonymizedBalance);

        // Update txdelegate->unit with the current unit
        txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit();

        ui->listTransactions->update();
    }
}

void OverviewPage::updateAlerts(const QString &warnings)
{
    this->ui->labelAlerts->setVisible(!warnings.isEmpty());
    this->ui->labelAlerts->setText(warnings);
}

void OverviewPage::showOutOfSyncWarning(bool fShow)
{
    ui->labelWalletStatus->setVisible(fShow);
    ui->labelTransactionsStatus->setVisible(fShow);
}

void OverviewPage::updateDarksendProgress(){
    int64 balance = pwalletMain->GetBalance();
    if(balance == 0){
        ui->darksendProgress->setValue(0);
        QString s("No inputs detected");
        ui->darksendProgress->setToolTip(s);
        return;
    }

    std::ostringstream convert;
    //Get average rounds of inputs
    double a = ((double)pwalletMain->GetAverageAnonymizedRounds() / (double)nDarksendRounds)*100;
    //Get the anon threshold
    double max = nAnonymizeDarkcoinAmount;
    //If it's more than the wallet amount, limit to that.
    if(max > (double)(pwalletMain->GetBalance()/COIN)-1) max = (double)(pwalletMain->GetBalance()/COIN)-1;
    //denominated balance / anon threshold -- the percentage that we've completed
    double b = ((double)(pwalletMain->GetDenominatedBalance()/COIN) / max);

    double val = a*b;
    if(val < 0) val = 0;
    if(val > 100) val = 100;

    ui->darksendProgress->setValue(val);//rounds avg * denom progress
    convert << "Inputs have an average of " << pwalletMain->GetAverageAnonymizedRounds() << " of " << nDarksendRounds << " rounds (" << a << "/" << b << ")";
    QString s(convert.str().c_str());
    ui->darksendProgress->setToolTip(s);
}

void OverviewPage::darkSendStatus()
{
    if(nBestHeight != darkSendPool.cachedNumBlocks)
    {
        updateDarksendProgress();

        std::ostringstream convert2;
        convert2 << nAnonymizeDarkcoinAmount << " DRK / " << nDarksendRounds << " Rounds";
        QString s2(convert2.str().c_str());
        ui->labelAmountRounds->setText(s2);
    }

    if(!fEnableDarksend) {
        if(nBestHeight != darkSendPool.cachedNumBlocks)
        {
            darkSendPool.cachedNumBlocks = nBestHeight;

            ui->darksendEnabled->setText("Disabled");
            ui->darksendStatus->setText("");
        }

        return;
    }

    // check darksend status and unlock if needed
    if(nBestHeight != darkSendPool.cachedNumBlocks)
    {
        // Balance and number of transactions might have changed
        darkSendPool.cachedNumBlocks = nBestHeight;

        if (pwalletMain->GetBalance() - pwalletMain->GetAnonymizedBalance() > 2*COIN){
            if (walletModel->getEncryptionStatus() != WalletModel::Unencrypted){
                if((nAnonymizeDarkcoinAmount*COIN)-pwalletMain->GetAnonymizedBalance() > 1.1*COIN && walletModel->getEncryptionStatus() == WalletModel::Locked){
                    WalletModel::UnlockContext ctx(walletModel->requestUnlock(false));
                    if(!ctx.isValid()){
                        //unlock was cancelled
                        fEnableDarksend = false;
                        LogPrintf("Wallet is locked and user declined to unlock. Disabling Darksend.\n");
                    }
                }
                if((nAnonymizeDarkcoinAmount*COIN)-pwalletMain->GetAnonymizedBalance() <= 1.1*COIN &&
                    walletModel->getEncryptionStatus() == WalletModel::Unlocked &&
                    darkSendPool.GetMyTransactionCount() == 0){
                    LogPrintf("Darksend is complete, locking wallet.\n");
                    walletModel->Lock();
                }
            }
        }

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

        ui->darksendEnabled->setText("Enabled");
    }

    int state = darkSendPool.GetState();
    int entries = darkSendPool.GetEntriesCount();
    int accepted = darkSendPool.GetLastEntryAccepted();

    std::ostringstream convert;

    if(state == POOL_STATUS_ACCEPTING_ENTRIES) {
        if(entries == 0) {
            convert << "Darksend is idle";
            showingDarkSendMessage = 0;
        } else if (accepted == 1) {
            convert << "Darksend request complete: Your transaction was accepted into the pool!";
            if(showingDarkSendMessage % 10 > 8) {
                darkSendPool.lastEntryAccepted = 0;
                showingDarkSendMessage = 0;
            }
        } else {
            if(showingDarkSendMessage % 70 <= 40) convert << "Submitted to masternode, entries " << entries << "/" << darkSendPool.GetMaxPoolTransactions();
            else if(showingDarkSendMessage % 70 <= 50) convert << "Submitted to masternode, Waiting for more entries (" << entries << "/" << darkSendPool.GetMaxPoolTransactions() << " ) .";
            else if(showingDarkSendMessage % 70 <= 60) convert << "Submitted to masternode, Waiting for more entries (" << entries << "/" << darkSendPool.GetMaxPoolTransactions() << " ) ..";
            else if(showingDarkSendMessage % 70 <= 70) convert << "Submitted to masternode, Waiting for more entries (" << entries << "/" << darkSendPool.GetMaxPoolTransactions() << " ) ...";
        }
    } else if(state == POOL_STATUS_SIGNING) {
        if(showingDarkSendMessage % 70 <= 10) convert << "Found enough users, signing";
        else if(showingDarkSendMessage % 70 <= 20) convert << "Found enough users, signing ( waiting. )";
        else if(showingDarkSendMessage % 70 <= 30) convert << "Found enough users, signing ( waiting.. )";
        else if(showingDarkSendMessage % 70 <= 40) convert << "Found enough users, signing ( waiting... )";
    } else if(state == POOL_STATUS_TRANSMISSION) {
        convert << "Transmitting final transaction";
    } else if (state == POOL_STATUS_IDLE) {
        convert << "Darksend is idle";
    } else if (state == POOL_STATUS_FINALIZE_TRANSACTION) {
        convert << "Finalizing transaction";
    } else if(state == POOL_STATUS_ERROR) {
        convert << "Darksend request incomplete: " << darkSendPool.lastMessage << ". Will retry...";
    } else if(state == POOL_STATUS_SUCCESS) {
        convert << "Darksend request complete: " << darkSendPool.lastMessage;
    } else if(state == POOL_STATUS_QUEUE) {
        if(showingDarkSendMessage % 70 <= 50) convert << "Submitted to masternode, waiting in queue .";
        else if(showingDarkSendMessage % 70 <= 60) convert << "Submitted to masternode, waiting in queue ..";
        else if(showingDarkSendMessage % 70 <= 70) convert << "Submitted to masternode, waiting in queue ...";
    } else {
        convert << "unknown state : id=" << state;
    }

    if(state == POOL_STATUS_ERROR || state == POOL_STATUS_SUCCESS) darkSendPool.Check();

    QString s(convert.str().c_str());

    if(s != ui->darksendStatus->text())
        LogPrintf("%s\n", convert.str().c_str());

    ui->darksendStatus->setText(s);

    showingDarkSendMessage++;
    darksendActionCheck++;

    // Get DarkSend Denomination Status
}

void OverviewPage::runDoAutomaticDenomination(){
    darkSendPool.DoAutomaticDenominating();
}

void OverviewPage::toggleDarksend(){
    int64 balance = pwalletMain->GetBalance();
    if(balance < 2.5*COIN){
        QMessageBox::warning(this, tr("Darksend"),
            tr("Darksend requires at least 2.5 DRK to use."),
            QMessageBox::Ok, QMessageBox::Ok);
        return;
    }

    darkSendPool.cachedNumBlocks = 0;

    fEnableDarksend = !fEnableDarksend;

    if(!fEnableDarksend){
        ui->toggleDarksend->setText("Start Darksend Mixing");
    } else {
        ui->toggleDarksend->setText("Stop Darksend Mixing");

        /* show darksend configuration if client has defaults set */

        if(nAnonymizeDarkcoinAmount == 0){
            DarksendConfig dlg(this);
            dlg.setModel(walletModel);
            dlg.exec();
        }

        darkSendPool.DoAutomaticDenominating();
    }
}
<commit_msg>fix darksend status and button text on unlock cancel<commit_after>#include "overviewpage.h"
#include "ui_overviewpage.h"

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

#include <QAbstractItemDelegate>
#include <QPainter>
#include <QTimer>

#define DECORATION_SIZE 64
#define NUM_ITEMS 3

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

    }

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

        QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
        QRect mainRect = option.rect;
        QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));
        int xspace = DECORATION_SIZE + 8;
        int ypad = 6;
        int halfheight = (mainRect.height() - 2*ypad)/2;
        QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight);
        QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight);
        icon.paint(painter, decorationRect);

        QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();
        QString address = index.data(Qt::DisplayRole).toString();
        qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();
        bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();
        QVariant value = index.data(Qt::ForegroundRole);
        QColor foreground = option.palette.color(QPalette::Text);
        if(value.canConvert<QBrush>())
        {
            QBrush brush = qvariant_cast<QBrush>(value);
            foreground = brush.color();
        }

        painter->setPen(foreground);
        painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address);

        if(amount < 0)
        {
            foreground = COLOR_NEGATIVE;
        }
        else if(!confirmed)
        {
            foreground = COLOR_UNCONFIRMED;
        }
        else
        {
            foreground = option.palette.color(QPalette::Text);
        }
        painter->setPen(foreground);
        QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true);
        if(!confirmed)
        {
            amountText = QString("[") + amountText + QString("]");
        }
        painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText);

        painter->setPen(option.palette.color(QPalette::Text));
        painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date));

        painter->restore();
    }

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

    int unit;

};
#include "overviewpage.moc"

OverviewPage::OverviewPage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::OverviewPage),
    clientModel(0),
    walletModel(0),
    currentBalance(-1),
    currentUnconfirmedBalance(-1),
    currentImmatureBalance(-1),
    txdelegate(new TxViewDelegate()),
    filter(0)
{
    ui->setupUi(this);

    // Recent transactions
    ui->listTransactions->setItemDelegate(txdelegate);
    ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));
    ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));
    ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);

    connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(darkSendStatus()));
    timer->start(333);

    // init "out of sync" warning labels
    ui->labelWalletStatus->setText("(" + tr("out of sync") + ")");
    ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")");

    showingDarkSendMessage = 0;
    darksendActionCheck = 0;

    if(fMasterNode){
        ui->toggleDarksend->setText("(Disabled)");
        ui->toggleDarksend->setEnabled(false);
    }else if(!fEnableDarksend){
        ui->toggleDarksend->setText("Start Darksend Mixing");
    } else {
        ui->toggleDarksend->setText("Stop Darksend Mixing");
    }

    // start with displaying the "out of sync" warnings
    showOutOfSyncWarning(true);
}

void OverviewPage::handleTransactionClicked(const QModelIndex &index)
{
    if(filter)
        emit transactionClicked(filter->mapToSource(index));
}

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

void OverviewPage::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance, qint64 anonymizedBalance)
{
    int unit = walletModel->getOptionsModel()->getDisplayUnit();
    currentBalance = balance;
    currentUnconfirmedBalance = unconfirmedBalance;
    currentImmatureBalance = immatureBalance;
    currentAnonymizedBalance = anonymizedBalance;
    ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));
    ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance));
    ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance));
    ui->labelAnonymized->setText(BitcoinUnits::formatWithUnit(unit, anonymizedBalance));

    // only show immature (newly mined) balance if it's non-zero, so as not to complicate things
    // for the non-mining users
    bool showImmature = immatureBalance != 0;
    ui->labelImmature->setVisible(showImmature);
    ui->labelImmatureText->setVisible(showImmature);
}

void OverviewPage::setClientModel(ClientModel *model)
{
    this->clientModel = model;
    if(model)
    {
        // Show warning if this is a prerelease version
        connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString)));
        updateAlerts(model->getStatusBarWarnings());
    }
}

void OverviewPage::setWalletModel(WalletModel *model)
{
    this->walletModel = model;
    if(model && model->getOptionsModel())
    {
        // Set up transaction list
        filter = new TransactionFilterProxy();
        filter->setSourceModel(model->getTransactionTableModel());
        filter->setLimit(NUM_ITEMS);
        filter->setDynamicSortFilter(true);
        filter->setSortRole(Qt::EditRole);
        filter->sort(TransactionTableModel::Status, Qt::DescendingOrder);

        ui->listTransactions->setModel(filter);
        ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);

        // Keep up to date with wallet
        setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getAnonymizedBalance());
        connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64)));

        connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));

        connect(ui->runAutoDenom, SIGNAL(clicked()), this, SLOT(runDoAutomaticDenomination()));
        connect(ui->toggleDarksend, SIGNAL(clicked()), this, SLOT(toggleDarksend()));
    }

    // update the display unit, to not use the default ("BTC")
    updateDisplayUnit();
}

void OverviewPage::updateDisplayUnit()
{
    if(walletModel && walletModel->getOptionsModel())
    {
        if(currentBalance != -1)
            setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance, currentAnonymizedBalance);

        // Update txdelegate->unit with the current unit
        txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit();

        ui->listTransactions->update();
    }
}

void OverviewPage::updateAlerts(const QString &warnings)
{
    this->ui->labelAlerts->setVisible(!warnings.isEmpty());
    this->ui->labelAlerts->setText(warnings);
}

void OverviewPage::showOutOfSyncWarning(bool fShow)
{
    ui->labelWalletStatus->setVisible(fShow);
    ui->labelTransactionsStatus->setVisible(fShow);
}

void OverviewPage::updateDarksendProgress(){
    int64 balance = pwalletMain->GetBalance();
    if(balance == 0){
        ui->darksendProgress->setValue(0);
        QString s("No inputs detected");
        ui->darksendProgress->setToolTip(s);
        return;
    }

    std::ostringstream convert;
    //Get average rounds of inputs
    double a = ((double)pwalletMain->GetAverageAnonymizedRounds() / (double)nDarksendRounds)*100;
    //Get the anon threshold
    double max = nAnonymizeDarkcoinAmount;
    //If it's more than the wallet amount, limit to that.
    if(max > (double)(pwalletMain->GetBalance()/COIN)-1) max = (double)(pwalletMain->GetBalance()/COIN)-1;
    //denominated balance / anon threshold -- the percentage that we've completed
    double b = ((double)(pwalletMain->GetDenominatedBalance()/COIN) / max);

    double val = a*b;
    if(val < 0) val = 0;
    if(val > 100) val = 100;

    ui->darksendProgress->setValue(val);//rounds avg * denom progress
    convert << "Inputs have an average of " << pwalletMain->GetAverageAnonymizedRounds() << " of " << nDarksendRounds << " rounds (" << a << "/" << b << ")";
    QString s(convert.str().c_str());
    ui->darksendProgress->setToolTip(s);
}

void OverviewPage::darkSendStatus()
{
    if(nBestHeight != darkSendPool.cachedNumBlocks)
    {
        updateDarksendProgress();

        std::ostringstream convert2;
        convert2 << nAnonymizeDarkcoinAmount << " DRK / " << nDarksendRounds << " Rounds";
        QString s2(convert2.str().c_str());
        ui->labelAmountRounds->setText(s2);
    }

    if(!fEnableDarksend) {
        if(nBestHeight != darkSendPool.cachedNumBlocks)
        {
            darkSendPool.cachedNumBlocks = nBestHeight;

            ui->darksendEnabled->setText("Disabled");
            ui->darksendStatus->setText("");
            ui->toggleDarksend->setText("Start Darksend Mixing");
        }

        return;
    }

    // check darksend status and unlock if needed
    if(nBestHeight != darkSendPool.cachedNumBlocks)
    {
        // Balance and number of transactions might have changed
        darkSendPool.cachedNumBlocks = nBestHeight;

        if (pwalletMain->GetBalance() - pwalletMain->GetAnonymizedBalance() > 2*COIN){
            if (walletModel->getEncryptionStatus() != WalletModel::Unencrypted){
                if((nAnonymizeDarkcoinAmount*COIN)-pwalletMain->GetAnonymizedBalance() > 1.1*COIN &&
                    walletModel->getEncryptionStatus() == WalletModel::Locked){

                    WalletModel::UnlockContext ctx(walletModel->requestUnlock(false));
                    if(!ctx.isValid()){
                        //unlock was cancelled
                        fEnableDarksend = false;
                        darkSendPool.cachedNumBlocks = 0;
                        LogPrintf("Wallet is locked and user declined to unlock. Disabling Darksend.\n");
                    }
                }
                if((nAnonymizeDarkcoinAmount*COIN)-pwalletMain->GetAnonymizedBalance() <= 1.1*COIN &&
                    walletModel->getEncryptionStatus() == WalletModel::Unlocked &&
                    darkSendPool.GetMyTransactionCount() == 0){

                    LogPrintf("Darksend is complete, locking wallet.\n");
                    walletModel->Lock();
                }
            }
        }

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

        ui->darksendEnabled->setText("Enabled");
    }

    int state = darkSendPool.GetState();
    int entries = darkSendPool.GetEntriesCount();
    int accepted = darkSendPool.GetLastEntryAccepted();

    std::ostringstream convert;

    if(state == POOL_STATUS_ACCEPTING_ENTRIES) {
        if(entries == 0) {
            convert << "Darksend is idle";
            showingDarkSendMessage = 0;
        } else if (accepted == 1) {
            convert << "Darksend request complete: Your transaction was accepted into the pool!";
            if(showingDarkSendMessage % 10 > 8) {
                darkSendPool.lastEntryAccepted = 0;
                showingDarkSendMessage = 0;
            }
        } else {
            if(showingDarkSendMessage % 70 <= 40) convert << "Submitted to masternode, entries " << entries << "/" << darkSendPool.GetMaxPoolTransactions();
            else if(showingDarkSendMessage % 70 <= 50) convert << "Submitted to masternode, Waiting for more entries (" << entries << "/" << darkSendPool.GetMaxPoolTransactions() << " ) .";
            else if(showingDarkSendMessage % 70 <= 60) convert << "Submitted to masternode, Waiting for more entries (" << entries << "/" << darkSendPool.GetMaxPoolTransactions() << " ) ..";
            else if(showingDarkSendMessage % 70 <= 70) convert << "Submitted to masternode, Waiting for more entries (" << entries << "/" << darkSendPool.GetMaxPoolTransactions() << " ) ...";
        }
    } else if(state == POOL_STATUS_SIGNING) {
        if(showingDarkSendMessage % 70 <= 10) convert << "Found enough users, signing";
        else if(showingDarkSendMessage % 70 <= 20) convert << "Found enough users, signing ( waiting. )";
        else if(showingDarkSendMessage % 70 <= 30) convert << "Found enough users, signing ( waiting.. )";
        else if(showingDarkSendMessage % 70 <= 40) convert << "Found enough users, signing ( waiting... )";
    } else if(state == POOL_STATUS_TRANSMISSION) {
        convert << "Transmitting final transaction";
    } else if (state == POOL_STATUS_IDLE) {
        convert << "Darksend is idle";
    } else if (state == POOL_STATUS_FINALIZE_TRANSACTION) {
        convert << "Finalizing transaction";
    } else if(state == POOL_STATUS_ERROR) {
        convert << "Darksend request incomplete: " << darkSendPool.lastMessage << ". Will retry...";
    } else if(state == POOL_STATUS_SUCCESS) {
        convert << "Darksend request complete: " << darkSendPool.lastMessage;
    } else if(state == POOL_STATUS_QUEUE) {
        if(showingDarkSendMessage % 70 <= 50) convert << "Submitted to masternode, waiting in queue .";
        else if(showingDarkSendMessage % 70 <= 60) convert << "Submitted to masternode, waiting in queue ..";
        else if(showingDarkSendMessage % 70 <= 70) convert << "Submitted to masternode, waiting in queue ...";
    } else {
        convert << "unknown state : id=" << state;
    }

    if(state == POOL_STATUS_ERROR || state == POOL_STATUS_SUCCESS) darkSendPool.Check();

    QString s(convert.str().c_str());

    if(s != ui->darksendStatus->text())
        LogPrintf("%s\n", convert.str().c_str());

    ui->darksendStatus->setText(s);

    showingDarkSendMessage++;
    darksendActionCheck++;

    // Get DarkSend Denomination Status
}

void OverviewPage::runDoAutomaticDenomination(){
    darkSendPool.DoAutomaticDenominating();
}

void OverviewPage::toggleDarksend(){
    int64 balance = pwalletMain->GetBalance();
    if(balance < 2.5*COIN){
        QMessageBox::warning(this, tr("Darksend"),
            tr("Darksend requires at least 2.5 DRK to use."),
            QMessageBox::Ok, QMessageBox::Ok);
        return;
    }

    darkSendPool.cachedNumBlocks = 0;

    fEnableDarksend = !fEnableDarksend;

    if(!fEnableDarksend){
        ui->toggleDarksend->setText("Start Darksend Mixing");
    } else {
        ui->toggleDarksend->setText("Stop Darksend Mixing");

        /* show darksend configuration if client has defaults set */

        if(nAnonymizeDarkcoinAmount == 0){
            DarksendConfig dlg(this);
            dlg.setModel(walletModel);
            dlg.exec();
        }

        darkSendPool.DoAutomaticDenominating();
    }
}
<|endoftext|>


<commit_before>/*$Id$
 *
 * This source file is a part of the Berlin Project.
 * Copyright (C) 1999, 2000 Stefan Seefeld <stefan@berlin-consortium.org>
 * http://www.berlin-consortium.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
 * MA 02139, USA.
 */
#include "Prague/IPC/ptybuf.hh"
#include "Prague/IPC/TTYAgent.hh"
#include "Prague/Sys/Tracer.hh"
#include <unistd.h>
#include <cstdio>

using namespace Prague;

TTYAgent::TTYAgent(const std::string &cmd, IONotifier *io, EOFNotifier *eof)
  : Coprocess(cmd, io, eof)
{}

TTYAgent::~TTYAgent()
{
  stop();
  shutdown(in|out|err);
}

void TTYAgent::start()
{
  Trace trace("TTYAgent::start");
  if (pid() >= 0)
    {
      terminate();
      ptybuf *pty  = new ptybuf;
      int fd = pty->openpty();
      switch(_id = fork())
	{
	case -1:
	  _id = 0;
// 	  SystemError("cannot fork", true);
	  return;
	case  0:
	  {
	    // Set this (child) process to be its own process group leader
	    // This allows the shell to implement job control properly
	    // FIXME: portability of this function is uncertain
	    setpgrp();
            int fds = pty->opentty();
	    if (fds < 0) _exit(EXIT_FAILURE);
            close(fd);
            dup2(fds, fileno(stdin));
            dup2(fds, fileno(stdout));
            dup2(fds, fileno(stderr));
            if (fds > fileno(stderr)) close(fds);
            const char *argv[4];
            argv[0] = "/bin/sh";
            argv[1] = "-c";
            argv[2] = _path.c_str();
            argv[3] = 0;
            execvp ("/bin/sh", (char**) argv);
            perror("/bin/sh");
            _exit(EXIT_FAILURE);
            break;
	  }
	default:
 	  _inbuf = _outbuf = pty;
	  _errbuf = 0;
	  _inbuf->async(true);
 	  break;
	}
    }
  _running = true;
  mask(out);
  Coprocess::start();
};

void TTYAgent::set_window_size(unsigned short columns, unsigned short rows)
{
#if defined(HAVE_IOCTL)
  struct winsize ws;
  ws.ws_col = columns;
  ws.ws_row = rows;
  ws.ws_xpixel = ws.ws_ypixel = 0;
  if (ioctl (master, TIOCSWINSZ, &ws) != 0);
#endif
};
<commit_msg>more portability issues<commit_after>/*$Id$
 *
 * This source file is a part of the Berlin Project.
 * Copyright (C) 1999, 2000 Stefan Seefeld <stefan@berlin-consortium.org>
 * http://www.berlin-consortium.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
 * MA 02139, USA.
 */
#include "Prague/IPC/ptybuf.hh"
#include "Prague/IPC/TTYAgent.hh"
#include "Prague/Sys/Tracer.hh"
#include <unistd.h>
#include <cstdio>

using namespace Prague;

TTYAgent::TTYAgent(const std::string &cmd, IONotifier *io, EOFNotifier *eof)
  : Coprocess(cmd, io, eof)
{}

TTYAgent::~TTYAgent()
{
  stop();
  shutdown(in|out|err);
}

void TTYAgent::start()
{
  Trace trace("TTYAgent::start");
  if (pid() >= 0)
    {
      terminate();
      ptybuf *pty  = new ptybuf;
      int fd = pty->openpty();
      switch(_id = fork())
	{
	case -1:
	  _id = 0;
// 	  SystemError("cannot fork", true);
	  return;
	case  0:
	  {
	    // Set this (child) process to be its own process group leader
	    // This allows the shell to implement job control properly
	    // FIXME: portability of this function is uncertain
	    setpgid(0, 0);
            int fds = pty->opentty();
	    if (fds < 0) _exit(EXIT_FAILURE);
            close(fd);
            dup2(fds, fileno(stdin));
            dup2(fds, fileno(stdout));
            dup2(fds, fileno(stderr));
            if (fds > fileno(stderr)) close(fds);
            const char *argv[4];
            argv[0] = "/bin/sh";
            argv[1] = "-c";
            argv[2] = _path.c_str();
            argv[3] = 0;
            execvp ("/bin/sh", (char**) argv);
            perror("/bin/sh");
            _exit(EXIT_FAILURE);
            break;
	  }
	default:
 	  _inbuf = _outbuf = pty;
	  _errbuf = 0;
	  _inbuf->async(true);
 	  break;
	}
    }
  _running = true;
  mask(out);
  Coprocess::start();
};

void TTYAgent::set_window_size(unsigned short columns, unsigned short rows)
{
#if defined(HAVE_IOCTL)
  struct winsize ws;
  ws.ws_col = columns;
  ws.ws_row = rows;
  ws.ws_xpixel = ws.ws_ypixel = 0;
  if (ioctl (master, TIOCSWINSZ, &ws) != 0);
#endif
};
<|endoftext|>


<commit_before>// This file is part of the "x0" project, http://github.com/christianparpart/x0>
//   (c) 2009-2017 Christian Parpart <christian@parpart.family>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT

#include <xzero-flow/ir/Value.h>
#include <xzero-flow/ir/Instr.h>
#include <xzero-flow/ir/BasicBlock.h>
#include <xzero-flow/ir/IRHandler.h>
#include <xzero/logging.h>
#include <algorithm>
#include <assert.h>

namespace xzero::flow {

static unsigned long long valueCounter = 1;

Value::Value(const Value& v) : type_(v.type_), name_(), uses_() {
  char buf[256];
  snprintf(buf, sizeof(buf), "%s_%llu", v.name().c_str(), valueCounter);
  valueCounter++;
  name_ = buf;
}

Value::Value(FlowType ty, const std::string& name)
    : type_(ty), name_(name), uses_() {
  if (name_.empty()) {
    char buf[256];
    snprintf(buf, sizeof(buf), "unnamed%llu", valueCounter);
    valueCounter++;
    name_ = buf;
    // printf("default-create name: %s\n", name_.c_str());
  }
}

Value::~Value() {
  logTrace("Value($0).dtor", name());
  if (isUsed()) {
    logTrace("BUG! Value $0 is still in use by: $1",
             name(), StringUtil::join(uses_, ", ", &Value::name));
    for (auto* instr : uses_) {
      logTrace("In use by: $0 of block $1:", instr->name(),
          instr->getBasicBlock()->name());
      instr->dump();
      instr->getBasicBlock()->getHandler()->dump();
    }
  }
  assert(!isUsed() && "Value being destroyed is still in use.");
}

void Value::addUse(Instr* user) {
  uses_.push_back(user);
}

void Value::removeUse(Instr* user) {
  auto i = std::find(uses_.begin(), uses_.end(), user);

  assert(i != uses_.end());

  if (i != uses_.end()) {
    uses_.erase(i);
  }
}

void Value::replaceAllUsesWith(Value* newUse) {
  auto myUsers = uses_;

  for (Instr* user : myUsers) {
    user->replaceOperand(this, newUse);
  }
}

void Value::dump() {
  printf("Value '%s': %s\n", name_.c_str(), tos(type_).c_str());
}

}  // namespace xzero::flow
<commit_msg>[flow] ir/Value: prefer `XZERO_ASSERT()` and reduce trace output again<commit_after>// This file is part of the "x0" project, http://github.com/christianparpart/x0>
//   (c) 2009-2017 Christian Parpart <christian@parpart.family>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT

#include <xzero-flow/ir/Value.h>
#include <xzero-flow/ir/Instr.h>
#include <xzero-flow/ir/BasicBlock.h>
#include <xzero-flow/ir/IRHandler.h>
#include <xzero/logging.h>
#include <algorithm>
#include <assert.h>

namespace xzero::flow {

static unsigned long long valueCounter = 1;

Value::Value(const Value& v) : type_(v.type_), name_(), uses_() {
  char buf[256];
  snprintf(buf, sizeof(buf), "%s_%llu", v.name().c_str(), valueCounter);
  valueCounter++;
  name_ = buf;
}

Value::Value(FlowType ty, const std::string& name)
    : type_(ty), name_(name), uses_() {
  if (name_.empty()) {
    char buf[256];
    snprintf(buf, sizeof(buf), "unnamed%llu", valueCounter);
    valueCounter++;
    name_ = buf;
    // printf("default-create name: %s\n", name_.c_str());
  }
}

Value::~Value() {
  XZERO_ASSERT(!isUsed(), StringUtil::format(
      "Value being destroyed is still in use by: $0.",
      StringUtil::join(uses_, ", ", &Instr::name)));
}

void Value::addUse(Instr* user) {
  uses_.push_back(user);
}

void Value::removeUse(Instr* user) {
  auto i = std::find(uses_.begin(), uses_.end(), user);

  assert(i != uses_.end());

  if (i != uses_.end()) {
    uses_.erase(i);
  }
}

void Value::replaceAllUsesWith(Value* newUse) {
  auto myUsers = uses_;

  for (Instr* user : myUsers) {
    user->replaceOperand(this, newUse);
  }
}

void Value::dump() {
  printf("Value '%s': %s\n", name_.c_str(), tos(type_).c_str());
}

}  // namespace xzero::flow
<|endoftext|>