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

#include "net/base/cert_database.h"

#include <openssl/x509.h>

#include "base/logging.h"
#include "net/base/net_errors.h"
#include "net/base/openssl_private_key_store.h"
#include "net/base/x509_certificate.h"

namespace net {

CertDatabase::CertDatabase() {
}

int CertDatabase::CheckUserCert(X509Certificate* cert) {
  if (!cert)
    return ERR_CERT_INVALID;
  if (cert->HasExpired())
    return ERR_CERT_DATE_INVALID;

  if (!OpenSSLPrivateKeyStore::GetInstance()->FetchPrivateKey(
      X509_PUBKEY_get(X509_get_X509_PUBKEY(cert->os_cert_handle()))))
    return ERR_NO_PRIVATE_KEY_FOR_CERT;

  return OK;
}

int CertDatabase::AddUserCert(X509Certificate* cert) {
  // TODO(bulach): implement me.
  NOTIMPLEMENTED();
  return ERR_NOT_IMPLEMENTED;
}

void CertDatabase::ListCerts(CertificateList* certs) {
  // TODO(bulach): implement me.
  NOTIMPLEMENTED();
}

int CertDatabase::ImportFromPKCS12(const std::string& data,
                                   const string16& password) {
  // TODO(bulach): implement me.
  NOTIMPLEMENTED();
  return ERR_NOT_IMPLEMENTED;
}

int CertDatabase::ExportToPKCS12(const CertificateList& certs,
                                 const string16& password,
                                 std::string* output) const {
  // TODO(bulach): implement me.
  NOTIMPLEMENTED();
  return 0;
}

bool CertDatabase::DeleteCertAndKey(const X509Certificate* cert) {
  // TODO(bulach): implement me.
  NOTIMPLEMENTED();
  return false;
}

unsigned int CertDatabase::GetCertTrust(const X509Certificate* cert,
                                        CertType type) const {
  // TODO(bulach): implement me.
  NOTIMPLEMENTED();
  return 0;
}

bool CertDatabase::SetCertTrust(const X509Certificate* cert,
                                CertType type,
                                unsigned int trust_bits) {
  // TODO(bulach): implement me.
  NOTIMPLEMENTED();
  return false;
}

}  // namespace net
<commit_msg>Fixes OpenSSL build following http://codereview.chromium.org/5686002/<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/base/cert_database.h"

#include <openssl/x509.h>

#include "base/logging.h"
#include "net/base/net_errors.h"
#include "net/base/openssl_private_key_store.h"
#include "net/base/x509_certificate.h"

namespace net {

CertDatabase::CertDatabase() {
}

int CertDatabase::CheckUserCert(X509Certificate* cert) {
  if (!cert)
    return ERR_CERT_INVALID;
  if (cert->HasExpired())
    return ERR_CERT_DATE_INVALID;

  if (!OpenSSLPrivateKeyStore::GetInstance()->FetchPrivateKey(
      X509_PUBKEY_get(X509_get_X509_PUBKEY(cert->os_cert_handle()))))
    return ERR_NO_PRIVATE_KEY_FOR_CERT;

  return OK;
}

int CertDatabase::AddUserCert(X509Certificate* cert) {
  // TODO(bulach): implement me.
  NOTIMPLEMENTED();
  return ERR_NOT_IMPLEMENTED;
}

void CertDatabase::ListCerts(CertificateList* certs) {
  // TODO(bulach): implement me.
  NOTIMPLEMENTED();
}

CryptoModule* CertDatabase::GetDefaultModule() const {
  // TODO(bulach): implement me.
  NOTIMPLEMENTED();
  return NULL;
}

int CertDatabase::ImportFromPKCS12(net::CryptoModule* module,
                                   const std::string& data,
                                   const string16& password) {
  // TODO(bulach): implement me.
  NOTIMPLEMENTED();
  return ERR_NOT_IMPLEMENTED;
}

int CertDatabase::ExportToPKCS12(const CertificateList& certs,
                                 const string16& password,
                                 std::string* output) const {
  // TODO(bulach): implement me.
  NOTIMPLEMENTED();
  return 0;
}

bool CertDatabase::DeleteCertAndKey(const X509Certificate* cert) {
  // TODO(bulach): implement me.
  NOTIMPLEMENTED();
  return false;
}

unsigned int CertDatabase::GetCertTrust(const X509Certificate* cert,
                                        CertType type) const {
  // TODO(bulach): implement me.
  NOTIMPLEMENTED();
  return 0;
}

bool CertDatabase::SetCertTrust(const X509Certificate* cert,
                                CertType type,
                                unsigned int trust_bits) {
  // TODO(bulach): implement me.
  NOTIMPLEMENTED();
  return false;
}

}  // namespace net
<|endoftext|>


<commit_before>class Solution {
    public:
        bool search(int A[], int n, int target) {
            if(n == 0) return -1;
            int start = findStart(A, n);
            if(start == 0){
                int index = binarySearch(A, 0, n - 1, target);
                if(index == -1) return false;
                else return true;
            }
            else{
                int index = binarySearch(A, 0, start - 1, target);
                if(index != -1) return true;
                index = binarySearch(A, start, n - 1, target);
                if(index != -1) return true;
                else return false;
            }
        }

        int findStart(int A[], int n){
            if(n < 2) return 0;
            int start = 0, end = n - 1;
            while(end - start > 1){
                int mid = (start + end)/2;
                if(A[mid] >= A[start] && A[mid] <= A[end]) return start;
                else if(A[mid] > A[start] && A[mid] > A[end]) start = mid;
                else if(A[mid] < A[start] && A[mid] < A[end]) end = mid;
                else if(A[mid] == A[start] && A[mid] == A[end]) {
                    if(start == mid - 1 && end == mid + 1)
                        return start;
                    else start = mid;
                }
                else if(A[mid] < A[start] && A[mid] == A[end]) end = mid;
                else if(A[mid] == A[start] && A[mid] > A[end]) start = mid;
            }
            if(A[start] < A[end]) return start;
            else return end;
        }

        int binarySearch(int A[], int start, int end, int target){
            while(start <= end){
                int mid = (start + end)/2;
                if(A[mid] == target) return mid;
                else if(A[mid] > target) end = mid - 1;
                else if(A[mid] < target) start = mid + 1;
            }
            return -1;
        }
};
<commit_msg>add a solution from discussion<commit_after>class Solution {
    public:
        bool search(int A[], int n, int target) {
            int l = 0, r = n - 1;
            while(l <= r){
                int m = l + (r-l)/2;
                if(A[m] == target) return true;
                else if(A[l] < A[m]){ // left part is sorted
                    if(A[l] <= target && target < A[m]) r = m - 1;
                    else l = m + 1;
                }
                else if(A[m] < A[r]){ // right part is sorted
                    if(A[m] < target && target <= A[r]) l = m + 1;
                    else r = m - 1;
                }
                else{
                    if(A[l] == target) return true;
                    else l++;
                };
            }
            return false;
        }
};
<|endoftext|>


<commit_before>// PVFilterTest.cpp -- test class for pvoc data filters

#include "PVFilterTest.h"
#include <stdio.h>

PVFilter *
PVFilterTest::create()
{
	return new PVFilterTest;
}

PVFilterTest::PVFilterTest()
{
}

PVFilterTest::~PVFilterTest()
{
}

int
PVFilterTest::run(float *pvdata, int nvals)
{
	for (int n = 0; n < nvals; ++n) {
		const int ampIdx = n * 2;
		const int frqIdx = ampIdx + 1;
		pvdata[frqIdx] *= val2;
		pvdata[frqIdx] += val1;
	}
	return 0;
}

int
PVFilterTest::init(double *pp, int nargs)
{
	val1 = pp[0];
	val2 = pp[1];
	return 1;
}

// This function is called by the PVOC setup() routine for each DSO

extern "C" {
int registerLib(int (*register_fun)(FilterCreateFunction)) {
	return register_fun(&PVFilterTest::create);
}
}
<commit_msg>One more for the PVOC plugins.<commit_after>// PVFilterTest.cpp -- test class for pvoc data filters

#include "PVFilterTest.h"
#include <stdio.h>
#include <ugens.h>

PVFilter *
PVFilterTest::create()
{
	return new PVFilterTest;
}

PVFilterTest::PVFilterTest()
{
}

PVFilterTest::~PVFilterTest()
{
}

int
PVFilterTest::run(float *pvdata, int nvals)
{
	for (int n = 0; n < nvals; ++n) {
		const int ampIdx = n * 2;
		const int frqIdx = ampIdx + 1;
		pvdata[frqIdx] *= val2;
		pvdata[frqIdx] += val1;
	}
	return 0;
}

int
PVFilterTest::init(double *pp, int nargs)
{
	val1 = pp[0];
	val2 = pp[1];
	return 1;
}

// This function is called by the PVOC setup() routine for each DSO

extern "C" {
int registerLib(int (*register_fun)(FilterCreateFunction)) {
	return register_fun(&PVFilterTest::create);
}
}
<|endoftext|>


<commit_before>#include "Context.h"

#include <cmath>
#include <iostream>

#ifdef OPENGL
#include <glm/glm.hpp>
#endif

using namespace std;
using namespace canvas;

void
Context::resize(unsigned int _width, unsigned int _height) {
  width = _width;
  height = _height;
  getDefaultSurface().resize(_width, _height);
}

void
Context::fillRect(double x, double y, double w, double h) {
  save();
  beginPath();
  moveTo(x, y);
  lineTo(x + w, y);
  lineTo(x + w, y + h);
  lineTo(x, y + h);
  closePath();
  fill();
  beginPath(); // tmp fix
  restore();
}

void
Context::strokeRect(double x, double y, double w, double h) {
  beginPath();
  moveTo(x, y);
  lineTo(x + w, y);
  lineTo(x + w, y + h);
  lineTo(x, y + h);
  closePath();
  stroke();
}

void
Context::fillText(const std::string & text, double x, double y) {
  if (hasShadow()) {
    // cerr << "DRAWING SHADOW for text " << text << ", w = " << getWidth() << ", h = " << getHeight() << endl;
    auto shadow = createSurface(getDefaultSurface().getWidth() + 2 * shadowBlur, getDefaultSurface().getHeight() + 2 * shadowBlur);
    Style tmp = fillStyle;
    fillStyle.color = shadowColor;
    shadow->fillText(*this, text, x + shadowOffsetX + shadowBlur, y + shadowOffsetY + shadowBlur);
    shadow->gaussianBlur(shadowBlur, shadowBlur);
    fillStyle = tmp;
    drawImage(*shadow, -shadowBlur, -shadowBlur, shadow->getWidth(), shadow->getHeight());
  }
  getDefaultSurface().fillText(*this, text, x, y);
}

// Implementation by node-canvas (Node canvas is a Cairo backed Canvas implementation for NodeJS)
// Original implementation influenced by WebKit.
void
Context::arcTo(double x1, double y1, double x2, double y2, double radius) {
#if 0
  Point _p0 = getCurrentPoint();
  glm::dvec2 current(_p0.x, _p0.y);
  glm::dvec2 p1(x1, y1), p2(x2, y2);

  glm::dvec2 v1 = glm::normalize(current - p1);
  glm::dvec2 v2 = glm::normalize(p2 - p1);

  double alpha = atan2(v1.y, v1.x) - atan2(v2.y, v2.x);
  if (alpha < 0) alpha += 2*M_PI;
  // TODO obtuse angles

  double dist = radius / sin(alpha / 2) * cos(alpha / 2);
  // calculate tangential points
  glm::dvec2 t1 = dist * v1 + p1;

  double a0 = atan2(v1.y, v1.x) - M_PI / 2;
  glm::dvec2 nv1(cos(a0), sin(a0));
  glm::dvec2 c = t1 + radius * nv1;

  double a1 = atan2(v1.y, v1.x) + M_PI / 2;
  double a2 = atan2(v2.y, v2.x) - M_PI / 2;

  lineTo(t1.x, t1.y);
  arc(c.x, c.y, radius, a1, a2, a1 > a2);
  lineTo(p2.x, p2.y);
#else
  Point p0 = getCurrentPoint();
  Point p1(x1, y1);
  Point p2(x2, y2);

  if ((p1.x == p0.x && p1.y == p0.y) || (p1.x == p2.x && p1.y == p2.y) || radius == 0.f) {
    lineTo(p1.x, p1.y);
    // p2?
    return;
  }

  Point p1p0((p0.x - p1.x), (p0.y - p1.y));
  Point p1p2((p2.x - p1.x), (p2.y - p1.y));
  float p1p0_length = sqrt(p1p0.x * p1p0.x + p1p0.y * p1p0.y);
  float p1p2_length = sqrt(p1p2.x * p1p2.x + p1p2.y * p1p2.y);

  double cos_phi = (p1p0.x * p1p2.x + p1p0.y * p1p2.y) / (p1p0_length * p1p2_length);
  // all points on a line logic
  if (-1 == cos_phi) {
    lineTo(p1.x, p1.y);
    // p2?
    return;
  }

  if (1 == cos_phi) {
    // add infinite far away point
    unsigned int max_length = 65535;
    double factor_max = max_length / p1p0_length;
    Point ep((p0.x + factor_max * p1p0.x), (p0.y + factor_max * p1p0.y));
    lineTo(ep.x, ep.y);
    return;
  }

  double tangent = radius / tan(acos(cos_phi) / 2);
  double factor_p1p0 = tangent / p1p0_length;
  Point t_p1p0((p1.x + factor_p1p0 * p1p0.x), (p1.y + factor_p1p0 * p1p0.y));

  Point orth_p1p0(p1p0.y, -p1p0.x);
  double orth_p1p0_length = sqrt(orth_p1p0.x * orth_p1p0.x + orth_p1p0.y * orth_p1p0.y);
  double factor_ra = radius / orth_p1p0_length;

  double cos_alpha = (orth_p1p0.x * p1p2.x + orth_p1p0.y * p1p2.y) / (orth_p1p0_length * p1p2_length);
  if (cos_alpha < 0.f) {
    orth_p1p0 = Point(-orth_p1p0.x, -orth_p1p0.y);
  }

  Point p((t_p1p0.x + factor_ra * orth_p1p0.x), (t_p1p0.y + factor_ra * orth_p1p0.y));

  orth_p1p0 = Point(-orth_p1p0.x, -orth_p1p0.y);
  double sa = acos(orth_p1p0.x / orth_p1p0_length);
  if (orth_p1p0.y < 0.f) {
    sa = 2 * M_PI - sa;
  }

  bool anticlockwise = false;

  double factor_p1p2 = tangent / p1p2_length;
  Point t_p1p2((p1.x + factor_p1p2 * p1p2.x), (p1.y + factor_p1p2 * p1p2.y));
  Point orth_p1p2((t_p1p2.x - p.x),(t_p1p2.y - p.y));
  double orth_p1p2_length = sqrt(orth_p1p2.x * orth_p1p2.x + orth_p1p2.y * orth_p1p2.y);
  double ea = acos(orth_p1p2.x / orth_p1p2_length);

  if (orth_p1p2.y < 0) ea = 2 * M_PI - ea;
  if ((sa > ea) && ((sa - ea) < M_PI)) anticlockwise = true;
  if ((sa < ea) && ((ea - sa) > M_PI)) anticlockwise = true;

  // cerr << "ARC " << int(t_p1p0.x) << " " << int(t_p1p0.y) << " " << int(p.x) << " " << int(p.y) << " " << radius << " " << int(sa * 180.0 / M_PI) << " " << int(ea * 180.0 / M_PI) << " " << (anticlockwise ? "acw" : "cw") << endl;

  lineTo(t_p1p0.x, t_p1p0.y);
  arc(p.x, p.y, radius, sa, ea, anticlockwise); // && M_PI * 2 != radius);
#endif
}
<commit_msg>add shadow support to fill method<commit_after>#include "Context.h"

#include <cmath>
#include <iostream>

#ifdef OPENGL
#include <glm/glm.hpp>
#endif

using namespace std;
using namespace canvas;

void
Context::resize(unsigned int _width, unsigned int _height) {
  width = _width;
  height = _height;
  getDefaultSurface().resize(_width, _height);
}

void
Context::fillRect(double x, double y, double w, double h) {
  save();
  beginPath();
  moveTo(x, y);
  lineTo(x + w, y);
  lineTo(x + w, y + h);
  lineTo(x, y + h);
  closePath();
  fill();
  beginPath(); // tmp fix
  restore();
}

void
Context::strokeRect(double x, double y, double w, double h) {
  beginPath();
  moveTo(x, y);
  lineTo(x + w, y);
  lineTo(x + w, y + h);
  lineTo(x, y + h);
  closePath();
  stroke();
}

void
Context::fillText(const std::string & text, double x, double y) {
  if (hasShadow()) {
    // cerr << "DRAWING SHADOW for text " << text << ", w = " << getWidth() << ", h = " << getHeight() << endl;
    auto shadow = createSurface(getDefaultSurface().getWidth() + 2 * shadowBlur, getDefaultSurface().getHeight() + 2 * shadowBlur);
    Style tmp = fillStyle;
    fillStyle.color = shadowColor;
    shadow->fillText(*this, text, x + shadowOffsetX + shadowBlur, y + shadowOffsetY + shadowBlur);
    shadow->gaussianBlur(shadowBlur, shadowBlur);
    fillStyle = tmp;
    drawImage(*shadow, -shadowBlur, -shadowBlur, shadow->getWidth(), shadow->getHeight());
  }
  getDefaultSurface().fillText(*this, text, x, y);
}

#if 0
// Implementation by node-canvas (Node canvas is a Cairo backed Canvas implementation for NodeJS)
// Original implementation influenced by WebKit.
void
Context::arcTo(double x1, double y1, double x2, double y2, double radius) {
#if 0
  Point _p0 = getCurrentPoint();
  glm::dvec2 current(_p0.x, _p0.y);
  glm::dvec2 p1(x1, y1), p2(x2, y2);

  glm::dvec2 v1 = glm::normalize(current - p1);
  glm::dvec2 v2 = glm::normalize(p2 - p1);

  double alpha = atan2(v1.y, v1.x) - atan2(v2.y, v2.x);
  if (alpha < 0) alpha += 2*M_PI;
  // TODO obtuse angles

  double dist = radius / sin(alpha / 2) * cos(alpha / 2);
  // calculate tangential points
  glm::dvec2 t1 = dist * v1 + p1;

  double a0 = atan2(v1.y, v1.x) - M_PI / 2;
  glm::dvec2 nv1(cos(a0), sin(a0));
  glm::dvec2 c = t1 + radius * nv1;

  double a1 = atan2(v1.y, v1.x) + M_PI / 2;
  double a2 = atan2(v2.y, v2.x) - M_PI / 2;

  lineTo(t1.x, t1.y);
  arc(c.x, c.y, radius, a1, a2, a1 > a2);
  lineTo(p2.x, p2.y);
#else
  Point p0 = getCurrentPoint();
  Point p1(x1, y1);
  Point p2(x2, y2);

  if ((p1.x == p0.x && p1.y == p0.y) || (p1.x == p2.x && p1.y == p2.y) || radius == 0.f) {
    lineTo(p1.x, p1.y);
    // p2?
    return;
  }

  Point p1p0((p0.x - p1.x), (p0.y - p1.y));
  Point p1p2((p2.x - p1.x), (p2.y - p1.y));
  float p1p0_length = sqrt(p1p0.x * p1p0.x + p1p0.y * p1p0.y);
  float p1p2_length = sqrt(p1p2.x * p1p2.x + p1p2.y * p1p2.y);

  double cos_phi = (p1p0.x * p1p2.x + p1p0.y * p1p2.y) / (p1p0_length * p1p2_length);
  // all points on a line logic
  if (-1 == cos_phi) {
    lineTo(p1.x, p1.y);
    // p2?
    return;
  }

  if (1 == cos_phi) {
    // add infinite far away point
    unsigned int max_length = 65535;
    double factor_max = max_length / p1p0_length;
    Point ep((p0.x + factor_max * p1p0.x), (p0.y + factor_max * p1p0.y));
    lineTo(ep.x, ep.y);
    return;
  }

  double tangent = radius / tan(acos(cos_phi) / 2);
  double factor_p1p0 = tangent / p1p0_length;
  Point t_p1p0((p1.x + factor_p1p0 * p1p0.x), (p1.y + factor_p1p0 * p1p0.y));

  Point orth_p1p0(p1p0.y, -p1p0.x);
  double orth_p1p0_length = sqrt(orth_p1p0.x * orth_p1p0.x + orth_p1p0.y * orth_p1p0.y);
  double factor_ra = radius / orth_p1p0_length;

  double cos_alpha = (orth_p1p0.x * p1p2.x + orth_p1p0.y * p1p2.y) / (orth_p1p0_length * p1p2_length);
  if (cos_alpha < 0.f) {
    orth_p1p0 = Point(-orth_p1p0.x, -orth_p1p0.y);
  }

  Point p((t_p1p0.x + factor_ra * orth_p1p0.x), (t_p1p0.y + factor_ra * orth_p1p0.y));

  orth_p1p0 = Point(-orth_p1p0.x, -orth_p1p0.y);
  double sa = acos(orth_p1p0.x / orth_p1p0_length);
  if (orth_p1p0.y < 0.f) {
    sa = 2 * M_PI - sa;
  }

  bool anticlockwise = false;

  double factor_p1p2 = tangent / p1p2_length;
  Point t_p1p2((p1.x + factor_p1p2 * p1p2.x), (p1.y + factor_p1p2 * p1p2.y));
  Point orth_p1p2((t_p1p2.x - p.x),(t_p1p2.y - p.y));
  double orth_p1p2_length = sqrt(orth_p1p2.x * orth_p1p2.x + orth_p1p2.y * orth_p1p2.y);
  double ea = acos(orth_p1p2.x / orth_p1p2_length);

  if (orth_p1p2.y < 0) ea = 2 * M_PI - ea;
  if ((sa > ea) && ((sa - ea) < M_PI)) anticlockwise = true;
  if ((sa < ea) && ((ea - sa) > M_PI)) anticlockwise = true;

  // cerr << "ARC " << int(t_p1p0.x) << " " << int(t_p1p0.y) << " " << int(p.x) << " " << int(p.y) << " " << radius << " " << int(sa * 180.0 / M_PI) << " " << int(ea * 180.0 / M_PI) << " " << (anticlockwise ? "acw" : "cw") << endl;

  lineTo(t_p1p0.x, t_p1p0.y);
  arc(p.x, p.y, radius, sa, ea, anticlockwise); // && M_PI * 2 != radius);
#endif
}
#endif

void
Context::fill() {
  if (hasShadow()) {
    auto shadow = createSurface(getDefaultSurface().getWidth() + 2 * shadowBlur, getDefaultSurface().getHeight() + 2 * shadowBlur);
    Style tmp_style = fillStyle;
    tmp_style.color = shadowColor;
    Path tmp_path = current_path;
    tmp_path.offset(shadowOffsetX + shadowBlur, shadowOffsetY + shadowBlur);

    shadow->fill(tmp_path, tmp_style);
    shadow->gaussianBlur(shadowBlur, shadowBlur);

    drawImage(*shadow, -shadowBlur, -shadowBlur, shadow->getWidth(), shadow->getHeight());
  }
  getDefaultSurface().fill(current_path, fillStyle);
}
<|endoftext|>


<commit_before><commit_msg>Add a comment to document that we don't know if a nonblocking connect will ever return 0, and therefore we don't know if the event object will be signaled in that case.<commit_after><|endoftext|>


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

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

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

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

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

#include "otbKmzExport.h"

#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbKmzProductWriter.h"

namespace otb
{

int KmzExport::Describe(ApplicationDescriptor* descriptor)
{
  descriptor->SetName("KmzExport");
  descriptor->SetDescription("Chain that Estimate a sensor model in order to export the input image to Google Earth understandable format Kmz");
  descriptor->AddInputImage();
  descriptor->AddOption("OutputProductName", "Output Kmz product ", "kmz", 1, true,ApplicationDescriptor::String);
  descriptor->AddOption("LogoImage", "Output Kmz product ", "lo", 1, false,ApplicationDescriptor::String);
  descriptor->AddOption("LegendImage", "Output Kmz product ", "le", 1, false,ApplicationDescriptor::String);

  return EXIT_SUCCESS;
}

int KmzExport::Execute(otb::ApplicationOptionsResult* parseResult)
{
  typedef otb::VectorImage<float, 2>                      ImageType;
  typedef otb::KmzProductWriter<ImageType>                KmzProductWriterType;
  typedef otb::ImageFileReader<ImageType>                 ReaderType;

  // Instanciate reader
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(parseResult->GetInputImage());
  reader->UpdateOutputInformation();

  // Second part : Image To Kmz
  KmzProductWriterType::Pointer    kmzWriter  = KmzProductWriterType::New();
  kmzWriter->SetInput(reader->GetOutput());
  kmzWriter->SetPath(parseResult->GetParameterString("OutputProductName"));

  // Read the logo if any
  if(parseResult->IsOptionPresent("LogoImage"))
    {
    ReaderType::Pointer logoReader  = ReaderType::New();
    logoReader->SetFileName(parseResult->GetParameterString("LogoImage"));
    logoReader->Update();
    kmzWriter->SetLogo(logoReader->GetOutput());
    }
  // Read the legend if any
  if(parseResult->IsOptionPresent("LegendImage"))
    {
    ReaderType::Pointer legendReader  = ReaderType::New();
    legendReader->SetFileName(parseResult->GetParameterString("LegendImage"));
    legendReader->Update();
    kmzWriter->AddLegend("Input Legend",legendReader->GetOutput());
    kmzWriter->AddLegend(legendReader->GetOutput());
    }

  // trigger the writing
  kmzWriter->Update();

  return EXIT_SUCCESS;
}
}
<commit_msg>ENH : change the type of the option && enable modules with no outputimage to work proprely on Qgis<commit_after>/*=========================================================================

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

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

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

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

#include "otbKmzExport.h"

#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbKmzProductWriter.h"

namespace otb
{

int KmzExport::Describe(ApplicationDescriptor* descriptor)
{
  descriptor->SetName("KmzExport");
  descriptor->SetDescription("Chain that Estimate a sensor model in order to export the input image to Google Earth understandable format Kmz");
  descriptor->AddInputImage();
  descriptor->AddOption("OutputProductName", "Output Kmz product ", "kmz", 1, true,ApplicationDescriptor::FileName);
  descriptor->AddOption("LogoImage", "Add a logo to the final Kmz ", "lo", 1, false,ApplicationDescriptor::FileName);
  descriptor->AddOption("LegendImage", "Add a legend to the image exported ", "le", 1, false,ApplicationDescriptor::FileName);

  return EXIT_SUCCESS;
}

int KmzExport::Execute(otb::ApplicationOptionsResult* parseResult)
{
  typedef otb::VectorImage<float, 2>                      ImageType;
  typedef otb::KmzProductWriter<ImageType>                KmzProductWriterType;
  typedef otb::ImageFileReader<ImageType>                 ReaderType;

  // Instanciate reader
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(parseResult->GetInputImage());
  reader->UpdateOutputInformation();

  // Second part : Image To Kmz
  KmzProductWriterType::Pointer    kmzWriter  = KmzProductWriterType::New();
  kmzWriter->SetInput(reader->GetOutput());
  kmzWriter->SetPath(parseResult->GetParameterString("OutputProductName"));

  // Read the logo if any
  if(parseResult->IsOptionPresent("LogoImage"))
    {
    ReaderType::Pointer logoReader  = ReaderType::New();
    logoReader->SetFileName(parseResult->GetParameterString("LogoImage"));
    logoReader->Update();
    kmzWriter->SetLogo(logoReader->GetOutput());
    }
  // Read the legend if any
  if(parseResult->IsOptionPresent("LegendImage"))
    {
    ReaderType::Pointer legendReader  = ReaderType::New();
    legendReader->SetFileName(parseResult->GetParameterString("LegendImage"));
    legendReader->Update();
    kmzWriter->AddLegend("Input Legend",legendReader->GetOutput());
    kmzWriter->AddLegend(legendReader->GetOutput());
    }

  // trigger the writing
  kmzWriter->Update();

  return EXIT_SUCCESS;
}
}
<|endoftext|>


<commit_before>#include <bitcoin/bitcoin.hpp>
using namespace bc;

using std::placeholders::_1;
using std::placeholders::_2;

void blockchain_started(const std::error_code& ec);
void copy_block(const std::error_code& ec, const message::block& blk,
    size_t depth, blockchain* chain_1, blockchain* chain_2);
void handle_import(const std::error_code& ec,
    size_t depth, const hash_digest& hash,
    blockchain* chain_1, blockchain* chain_2);

void blockchain_started(const std::error_code& ec)
{
    if (ec)
        log_error() << "Blockchain init error: " << ec.message();
    else
        log_info() << "Blockchain initialized!";
}

void copy_block(const std::error_code& ec, const message::block& blk,
    size_t depth, blockchain* chain_1, blockchain* chain_2)
{
    if (ec)
        log_error() << "Fetch error: " << ec.message();
    chain_2->import(blk, depth,
        std::bind(&handle_import, _1,
            depth, hash_block_header(blk), chain_1, chain_2));
}

void handle_import(const std::error_code& ec,
    size_t depth, const hash_digest& hash,
    blockchain* chain_1, blockchain* chain_2)
{
    if (ec)
    {
        log_error() << "Import error: " << ec.message();
        return;
    }
    log_info() << "Imported block #" << depth << " " << hash;
    if (depth == 200)
    {
        log_info() << "Finished.";
        return;
    }
    fetch_block(*chain_1, depth + 1,
        std::bind(copy_block, _1, _2, depth + 1, chain_1, chain_2));
}

int main()
{
    bdb_blockchain::setup("database-copy");
    async_service service(1);
    bdb_blockchain chain_1(service);
    leveldb_blockchain chain_2(service);
    chain_1.start("database", blockchain_started);
    chain_2.start("/home/genjix/tmp/lvldb/database", blockchain_started);
    const size_t start_depth = 1;
    fetch_block(chain_1, start_depth,
        std::bind(copy_block, _1, _2, start_depth, &chain_1, &chain_2));
    std::cin.get();
    log_info() << "Exiting...";
    service.stop();
    service.join();
    chain_1.stop();
    chain_2.stop();
    return 0;
}

<commit_msg>download blockchain from SOURCE to DEST. can resume from last place if stopped.<commit_after>#include <boost/lexical_cast.hpp>
#include <bitcoin/bitcoin.hpp>
using namespace bc;

using std::placeholders::_1;
using std::placeholders::_2;

void blockchain_started(const std::error_code& ec);
void copy_block(const std::error_code& ec, const message::block& blk,
    size_t depth, blockchain* chain_1, blockchain* chain_2);
void handle_import(const std::error_code& ec,
    size_t depth, const hash_digest& hash,
    blockchain* chain_1, blockchain* chain_2);

void blockchain_started(const std::error_code& ec)
{
    if (ec)
        log_error() << "Blockchain init error: " << ec.message();
    else
        log_info() << "Blockchain initialized!";
}

void resume_copy(const std::error_code& ec, size_t last_depth,
    blockchain* chain_1, blockchain* chain_2)
{
    size_t resume_depth = last_depth + 1;
    if (ec == error::not_found)
        resume_depth = 0;
    else if (ec)
    {
        log_error() << "Error fetch last depth from DEST: " << ec.message();
        return;
    }
    fetch_block(*chain_1, resume_depth,
        std::bind(copy_block, _1, _2, resume_depth, chain_1, chain_2));
}

void copy_block(const std::error_code& ec, const message::block& blk,
    size_t depth, blockchain* chain_1, blockchain* chain_2)
{
    if (ec)
        log_error() << "Fetch error: " << ec.message();
    chain_2->import(blk, depth,
        std::bind(&handle_import, _1,
            depth, hash_block_header(blk), chain_1, chain_2));
}

void handle_import(const std::error_code& ec,
    size_t depth, const hash_digest& hash,
    blockchain* chain_1, blockchain* chain_2)
{
    if (ec)
    {
        log_error() << "Import error: " << ec.message();
        return;
    }
    log_info() << "Imported block #" << depth << " " << hash;
    /*if (depth == end_depth)
    {
        log_info() << "Finished.";
        return;
    }*/
    fetch_block(*chain_1, depth + 1,
        std::bind(copy_block, _1, _2, depth + 1, chain_1, chain_2));
}

int main(int argc, char** argv)
{
    if (argc != 3)
    {
        log_info() << "Usage: import SOURCE DEST";
        return 1;
    }
    async_service service(1);
    bdb_blockchain chain_1(service);
    leveldb_blockchain chain_2(service);
    chain_1.start(argv[1], blockchain_started);
    chain_2.start(argv[2], blockchain_started);
    chain_2.fetch_last_depth(
        std::bind(resume_copy, _1, _2, &chain_1, &chain_2));
    std::cin.get();
    log_info() << "Exiting...";
    service.stop();
    service.join();
    chain_1.stop();
    chain_2.stop();
    return 0;
}

<|endoftext|>


<commit_before>/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: t; tab-width: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine.].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 2004-2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*   Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */

#include "MMgc.h"

#ifdef MMGC_MEMORY_PROFILER

#include <Msgqueue.h>

/**
* compiled with the /W4 warning level
* which is quite picky.  Disable warnings we don't care about.
*/
#ifdef _MSC_VER
#pragma warning(disable:4127) //conditional expression is constant
#endif

class SignalData : public MMgc::GCAllocObject
{
public:
	SignalData(uint32_t *addr, HANDLE handle)
		: profilerAddr(addr), eventHandle(handle) {}
	uint32_t *profilerAddr;
	HANDLE eventHandle;
};

void WriteOnNamedSignal(const char* name, uint32_t *addr);

static SignalData *sig_data=NULL;
static bool spyRunning;

DWORD WINAPI WaitForMemorySignal(LPVOID)
{
	SignalData *sd = sig_data;
	while(spyRunning) {
		WaitForSingleObject(sig_data->eventHandle, INFINITE);
		// For some reason ReadMsgQueue does not clear the signal on the handle (even though it should), and we
		// end up setting the profilerAddr constantly, which makes the VM hang, since all it is doing is writing out profile data.
		// so we have to call CloseMsgQueue, and then open a new queue, and wait on that.
		//char buff[256];
		//DWORD bytesread;
		//ReadMsgQueue(sig_data->eventHandle, buff, 256, &bytesread, INFINITE, 0);
		CloseMsgQueue(sd->eventHandle);
		if(spyRunning) {
			*(sig_data->profilerAddr) = true;
			WriteOnNamedSignal("MMgc::MemoryProfiler::DumpFatties", sd->profilerAddr);
			break;
		}
	}
	delete sd;
	return 0;
}

void WriteOnNamedSignal(const char *name, uint32_t *addr)
{
	HANDLE m_namedSharedObject;

	MSGQUEUEOPTIONS msgopts;

	msgopts.dwFlags = MSGQUEUE_NOPRECOMMIT;
	msgopts.dwMaxMessages = 1;
	msgopts.cbMaxMessage = 256;
	msgopts.bReadAccess = TRUE;
	msgopts.dwSize = sizeof(MSGQUEUEOPTIONS);

	WCHAR wName[256];

	MultiByteToWideChar(CP_ACP, 0, name, -1, wName, 256);

	m_namedSharedObject = CreateMsgQueue(wName, &msgopts);

	sig_data = new SignalData(addr, m_namedSharedObject);
	CreateThread(NULL, 0, WaitForMemorySignal, NULL, 0, NULL);
}

#include "windows.h"

#ifdef _MSC_VER
	#pragma warning(disable: 4995) //disabling warning for deprecated _snprintf
#endif

static uint32_t mmgc_spy_signal = 0;

FILE* spyStream = NULL;

void SpyLog(const char* message)
{
	fprintf(spyStream, "%s", message);
}

extern void RedirectLogOutput(void (*)(const char*));

void VMPI_spyCallback()
{
	if(mmgc_spy_signal)
	{
		mmgc_spy_signal = 0;

		spyStream = fopen("Temp\\gcstats.txt", "w");

		GCAssert(spyStream != NULL);
		RedirectLogOutput(SpyLog);

		MMgc::GCHeap::GetGCHeap()->DumpMemoryInfoLocked();

		fflush(spyStream);

		fclose(spyStream);
		RedirectLogOutput(NULL);
		spyStream = NULL;
 	}
}

bool VMPI_spySetup()
{
	WriteOnNamedSignal("MMgc::MemoryProfiler::DumpFatties", &mmgc_spy_signal);
	return true;
}

void VMPI_spyTeardown()
{
	spyRunning = false;
	if(sig_data)
		SetEvent(sig_data->eventHandle);
}

bool VMPI_hasSymbols()
{
	return false;
}

#endif //MMGC_MEMORY_PROFILER
<commit_msg>Submitted wrong patch, update to the right one<commit_after>/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: t; tab-width: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine.].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 2004-2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*   Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */

#include "MMgc.h"

#ifdef MMGC_MEMORY_PROFILER

#include <Msgqueue.h>

/**
* compiled with the /W4 warning level
* which is quite picky.  Disable warnings we don't care about.
*/
#ifdef _MSC_VER
#pragma warning(disable:4127) //conditional expression is constant
#endif

class SignalData : public MMgc::GCAllocObject
{
public:
	SignalData(uint32_t *addr, HANDLE handle)
		: profilerAddr(addr), eventHandle(handle) {}
	uint32_t *profilerAddr;
	HANDLE eventHandle;
};

void WriteOnNamedSignal(const char* name, uint32_t *addr);

static SignalData *sig_data=NULL;
static bool spyRunning=false;

DWORD WINAPI WaitForMemorySignal(LPVOID)
{
	SignalData *sd = sig_data;
	while(spyRunning) {
		WaitForSingleObject(sig_data->eventHandle, INFINITE);
		// For some reason ReadMsgQueue does not clear the signal on the handle (even though it should), and we
		// end up setting the profilerAddr constantly, which makes the VM hang, since all it is doing is writing out profile data.
		// so we have to call CloseMsgQueue, and then open a new queue, and wait on that.
		//char buff[256];
		//DWORD bytesread;
		//ReadMsgQueue(sig_data->eventHandle, buff, 256, &bytesread, INFINITE, 0);
		CloseMsgQueue(sd->eventHandle);
		if(spyRunning) {
			*(sig_data->profilerAddr) = true;
			WriteOnNamedSignal("MMgc::MemoryProfiler::DumpFatties", sd->profilerAddr);
			break;
		}
	}
	delete sd;
	return 0;
}

void WriteOnNamedSignal(const char *name, uint32_t *addr)
{
	HANDLE m_namedSharedObject;

	MSGQUEUEOPTIONS msgopts;

	msgopts.dwFlags = MSGQUEUE_NOPRECOMMIT;
	msgopts.dwMaxMessages = 1;
	msgopts.cbMaxMessage = 256;
	msgopts.bReadAccess = TRUE;
	msgopts.dwSize = sizeof(MSGQUEUEOPTIONS);

	WCHAR wName[256];

	MultiByteToWideChar(CP_ACP, 0, name, -1, wName, 256);

	m_namedSharedObject = CreateMsgQueue(wName, &msgopts);

	sig_data = new SignalData(addr, m_namedSharedObject);
	spyRunning = true;
	CreateThread(NULL, 0, WaitForMemorySignal, NULL, 0, NULL);
}

#include "windows.h"

#ifdef _MSC_VER
	#pragma warning(disable: 4995) //disabling warning for deprecated _snprintf
#endif

static uint32_t mmgc_spy_signal = 0;

FILE* spyStream = NULL;

void SpyLog(const char* message)
{
	fprintf(spyStream, "%s", message);
}

extern void RedirectLogOutput(void (*)(const char*));

void VMPI_spyCallback()
{
	if(mmgc_spy_signal)
	{
		mmgc_spy_signal = 0;

		spyStream = fopen("Temp\\gcstats.txt", "w");

		GCAssert(spyStream != NULL);
		RedirectLogOutput(SpyLog);

		MMgc::GCHeap::GetGCHeap()->DumpMemoryInfoLocked();

		fflush(spyStream);

		fclose(spyStream);
		RedirectLogOutput(NULL);
		spyStream = NULL;
 	}
}

bool VMPI_spySetup()
{
	WriteOnNamedSignal("MMgc::MemoryProfiler::DumpFatties", &mmgc_spy_signal);
	return true;
}

void VMPI_spyTeardown()
{
	spyRunning = false;
	if(sig_data)
		SetEvent(sig_data->eventHandle);
}

bool VMPI_hasSymbols()
{
	return false;
}

#endif //MMGC_MEMORY_PROFILER
<|endoftext|>


<commit_before>#include "CppUTest/TestHarness.h"

#include "IpcSockServer.h"
#include "IpcSocKClient.h"
#include <future>

static const std::string dummy_path = "/tmp/test-socket";
static const int dummy_dueue_size = 128;

TEST_GROUP(Ipc)
{
    void setup()
    {
    }

    void teardown()
    {
    }
};

TEST(Ipc, ServerSingle)
{
    UtilTime timeout = 0.5;
    IpcSockServer server(dummy_path, dummy_dueue_size, timeout);

    bool initted = server.init();
    bool started = server.start();
    bool stoped = server.stop();

    CHECK_EQUAL(true, initted);
    CHECK_EQUAL(true, started);
    CHECK_EQUAL(true, stoped);
}
<commit_msg>add single test for IpcSockClient class<commit_after>#include "CppUTest/TestHarness.h"

#include "IpcSockServer.h"
#include "IpcSocKClient.h"
#include <future>

static const std::string dummy_path = "/tmp/test-socket";
static const int dummy_dueue_size = 128;

TEST_GROUP(Ipc)
{
    void setup()
    {
    }

    void teardown()
    {
    }
};

TEST(Ipc, ServerSingle)
{
    UtilTime timeout = 0.5;
    IpcSockServer server(dummy_path, dummy_dueue_size, timeout);

    bool initted = server.init();
    bool started = server.start();
    bool stoped = server.stop();

    CHECK_EQUAL(true, initted);
    CHECK_EQUAL(true, started);
    CHECK_EQUAL(true, stoped);
}

TEST(Ipc, ClientSingle)
{
    IpcSockClient client(dummy_path);

    bool initted = client.init();
    bool started = client.start(); /* サーバ起動していないためfail */

    CHECK_EQUAL(true, initted);
    CHECK_EQUAL(false, started);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: acceptor.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 18:28:11 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _OSL_PIPE_HXX_
#include <osl/pipe.hxx>
#endif

#ifndef _OSL_SOCKET_HXX_
#include <osl/socket.hxx>
#endif

#ifndef _RTL_UNLOAD_H_
#include <rtl/unload.h>
#endif

#include <com/sun/star/connection/XConnection.hpp>

namespace io_acceptor {

    extern rtl_StandardModuleCount g_moduleCount;

    class PipeAcceptor
    {
    public:
        PipeAcceptor( const ::rtl::OUString &sPipeName , const ::rtl::OUString &sConnectionDescription );

        void init();
        ::com::sun::star::uno::Reference < ::com::sun::star::connection::XConnection >  accept(  );

        void stopAccepting();

        ::osl::Mutex m_mutex;
        ::osl::Pipe m_pipe;
        ::rtl::OUString m_sPipeName;
        ::rtl::OUString m_sConnectionDescription;
        sal_Bool m_bClosed;
    };

    class SocketAcceptor
    {
    public:
        SocketAcceptor( const ::rtl::OUString & sSocketName ,
                        sal_uInt16 nPort,
                        sal_Bool bTcpNoDelay,
                        const ::rtl::OUString &sConnectionDescription );

        void init();
        ::com::sun::star::uno::Reference < ::com::sun::star::connection::XConnection > accept();

        void stopAccepting();

        ::osl::SocketAddr m_addr;
        ::osl::AcceptorSocket m_socket;
        ::rtl::OUString m_sSocketName;
        ::rtl::OUString m_sConnectionDescription;
        sal_uInt16 m_nPort;
        sal_Bool m_bTcpNoDelay;
        sal_Bool m_bClosed;
    };

};

<commit_msg>INTEGRATION: CWS warnings01 (1.6.122); FILE MERGED 2005/09/22 20:27:12 sb 1.6.122.2: RESYNC: (1.6-1.7); FILE MERGED 2005/09/07 14:14:51 sb 1.6.122.1: #i53898# Made code warning-free.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: acceptor.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 00:16:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _OSL_PIPE_HXX_
#include <osl/pipe.hxx>
#endif

#ifndef _OSL_SOCKET_HXX_
#include <osl/socket.hxx>
#endif

#ifndef _RTL_UNLOAD_H_
#include <rtl/unload.h>
#endif

#include <com/sun/star/connection/XConnection.hpp>

namespace io_acceptor {

    extern rtl_StandardModuleCount g_moduleCount;

    class PipeAcceptor
    {
    public:
        PipeAcceptor( const ::rtl::OUString &sPipeName , const ::rtl::OUString &sConnectionDescription );

        void init();
        ::com::sun::star::uno::Reference < ::com::sun::star::connection::XConnection >  accept(  );

        void stopAccepting();

        ::osl::Mutex m_mutex;
        ::osl::Pipe m_pipe;
        ::rtl::OUString m_sPipeName;
        ::rtl::OUString m_sConnectionDescription;
        sal_Bool m_bClosed;
    };

    class SocketAcceptor
    {
    public:
        SocketAcceptor( const ::rtl::OUString & sSocketName ,
                        sal_uInt16 nPort,
                        sal_Bool bTcpNoDelay,
                        const ::rtl::OUString &sConnectionDescription );

        void init();
        ::com::sun::star::uno::Reference < ::com::sun::star::connection::XConnection > accept();

        void stopAccepting();

        ::osl::SocketAddr m_addr;
        ::osl::AcceptorSocket m_socket;
        ::rtl::OUString m_sSocketName;
        ::rtl::OUString m_sConnectionDescription;
        sal_uInt16 m_nPort;
        sal_Bool m_bTcpNoDelay;
        sal_Bool m_bClosed;
    };

}

<|endoftext|>


<commit_before>#include <QmitkDataTreeComboBox.h>
#include <QmitkPropertyViewFactory.h>

#include <itkCommand.h>
#include <mitkDataTreeFilterEvents.h>

#include <qobjectlist.h>

#include <stdexcept>

QmitkDataTreeComboBox::QmitkDataTreeComboBox(QWidget* parent, const char* name)
: QComboBox(parent, name),
  m_DataTreeFilter(NULL)
{
  initialize();
}

QmitkDataTreeComboBox::QmitkDataTreeComboBox(mitk::DataTreeFilter* filter,QWidget* parent, const char* name)
: QComboBox(parent, name),
  m_DataTreeFilter(filter)
{
  initialize();
  SetFilter(filter);
}

QmitkDataTreeComboBox::QmitkDataTreeComboBox(mitk::DataTreeBase* tree,QWidget* parent, const char* name)
: QComboBox(parent, name),
  m_DataTreeFilter(NULL)
{
  initialize();
  SetDataTree(tree);
}

QmitkDataTreeComboBox::QmitkDataTreeComboBox(mitk::DataTreeIteratorBase* iterator,QWidget* parent, const char* name)
: QComboBox(parent, name),
  m_DataTreeFilter(NULL)
{
  initialize();
  SetDataTree(iterator);
}

void QmitkDataTreeComboBox::initialize()
{
  // member initializations that are equal for all constructors
  m_SkipItem = NULL;
  m_SkipItemParent = NULL;
  m_SelfCall = false;
  m_DisplayedProperty.clear();
  m_UserSetDisplayedProperty.clear();

  connect(this, SIGNAL(activated(int)), this, SLOT(onActivated(int)));
}

QmitkDataTreeComboBox::~QmitkDataTreeComboBox()
{
  disconnectNotifications();
}

void QmitkDataTreeComboBox::connectNotifications()
{
  // connect to our filter's notifications
  {
  itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::Pointer command1 = itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::New();
  command1->SetCallbackFunction(this, &QmitkDataTreeComboBox::removeItemHandler);
  m_RemoveItemConnection = m_DataTreeFilter->AddObserver(mitk::TreeFilterRemoveItemEvent(), command1);
  }
  {
  itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::Pointer command2= itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::New();
  command2->SetCallbackFunction(this, &QmitkDataTreeComboBox::removeChildrenHandler);
  m_RemoveChildrenConnection = m_DataTreeFilter->AddObserver(mitk::TreeFilterRemoveChildrenEvent(), command2);
  }
  {
  itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::Pointer command3 = itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::New();
  command3->SetCallbackFunction(this, &QmitkDataTreeComboBox::removeAllHandler);
  m_RemoveAllConnection = m_DataTreeFilter->AddObserver(mitk::TreeFilterRemoveAllEvent(), command3);
  }
  {
  itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::Pointer command4 = itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::New();
  command4->SetCallbackFunction(this, &QmitkDataTreeComboBox::selectionChangedHandler);
  m_SelectionChangedConnection = m_DataTreeFilter->AddObserver(mitk::TreeFilterSelectionChangedEvent(), command4);
  }
  {
  itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::Pointer command5 = itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::New();
  command5->SetCallbackFunction(this, &QmitkDataTreeComboBox::itemAddedHandler);
  m_ItemAddedConnection = m_DataTreeFilter->AddObserver(mitk::TreeFilterItemAddedEvent(), command5);
  }
  {
  itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::Pointer command6 = itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::New();
  command6->SetCallbackFunction(this, &QmitkDataTreeComboBox::updateAllHandler);
  m_UpdateAllConnection = m_DataTreeFilter->AddObserver(mitk::TreeFilterUpdateAllEvent(), command6);
  }
}

void QmitkDataTreeComboBox::disconnectNotifications()
{
  if (!m_DataTreeFilter) return;

  m_DataTreeFilter->RemoveObserver( m_RemoveItemConnection );
  m_DataTreeFilter->RemoveObserver( m_RemoveChildrenConnection );
  m_DataTreeFilter->RemoveObserver( m_RemoveAllConnection );
  m_DataTreeFilter->RemoveObserver( m_SelectionChangedConnection );
  m_DataTreeFilter->RemoveObserver( m_ItemAddedConnection );
  m_DataTreeFilter->RemoveObserver( m_UpdateAllConnection );
}

void QmitkDataTreeComboBox::SetDataTree(mitk::DataTreeBase* tree)
{
  if (tree)
  {
    // create default filter with visibility (editable) and name (non-editable)
    m_PrivateFilter = mitk::DataTreeFilter::New(tree);
    m_PrivateFilter->SetFilter(&mitk::IsImage);
    m_PrivateFilter->SetSelectionMode(mitk::DataTreeFilter::SINGLE_SELECT);
    mitk::DataTreeFilter::PropertyList visible;
    visible.push_back("name");
    m_PrivateFilter->SetVisibleProperties(visible);

    disconnectNotifications(); // add observers
    m_DataTreeFilter = m_PrivateFilter;
    connectNotifications(); // add observers

    SetDisplayedProperty("name");
    generateItems();
  }
}

void QmitkDataTreeComboBox::SetDataTree(mitk::DataTreeIteratorBase* iterator)
{
  // create default filter if neccessary
  if (iterator && iterator->GetTree())
    SetDataTree(iterator->GetTree());
}

void QmitkDataTreeComboBox::SetFilter(mitk::DataTreeFilter* filter)
{
  disconnectNotifications();
  m_DataTreeFilter = filter;
  // in the case that somebody first sets a datatree and then a filter
  // destroy the default filter that was created in SetDataTree
  if (filter != m_PrivateFilter.GetPointer())
    m_PrivateFilter = NULL;
  connectNotifications(); // add observers

  if ( m_DataTreeFilter->GetSelectionMode() != mitk::DataTreeFilter::SINGLE_SELECT )
  {
    std::cerr << "---------------------------------------------------------------------------"
              << "QmitkDataTreeComboBoxes work only correctly with SINGLE_SELECT data tree filters!"
              << std::endl
              << "The filter you assigned in " << __FILE__ << ", l. " << __LINE__ << " has a differenct SelectionMode. Please change that."
              << std::endl
              << "If you don't know what this means, ask your programmer about it."
              << std::endl
              << "---------------------------------------------------------------------------"
              << std::endl;
  }

  determineDisplayedProperty();
  generateItems();
}

mitk::DataTreeFilter* QmitkDataTreeComboBox::GetFilter()
{
  return m_DataTreeFilter;
}

void QmitkDataTreeComboBox::onActivated(int index)
{
  // find item, generate signal
  try
  {
    // following cast is due to bad design... class Item needs needs rework
    m_SelfCall = true;
    const_cast<mitk::DataTreeFilter::Item*>(m_Items.at(index))->SetSelected(true);
    emit activated(m_Items.at(index));
    m_SelfCall = false;
  }
  catch (std::out_of_range)
  {
    std::cerr << "in onActivated(" << index << "), " << __FILE__ << "l. " << __LINE__ << ": not a good index..." << std::endl;
  }

  // TODO on selectionChanged notifications from treefilter => change selection!
}

void QmitkDataTreeComboBox::determineDisplayedProperty()
{
  if ( !m_UserSetDisplayedProperty.empty() )
    if (std::find( m_DataTreeFilter->GetVisibleProperties().begin(), m_DataTreeFilter->GetVisibleProperties().end(), m_UserSetDisplayedProperty )
        != m_DataTreeFilter->GetVisibleProperties().end() )
    {
      m_DisplayedProperty = m_UserSetDisplayedProperty;
      return;
    }

  // if this line is reached, either the user has not chosen a property to be displayed, or
  // that property is not available from the filter used.

  m_DisplayedProperty.clear();

  // This (often) determines the key of the left-most string property.
  // If such a property cannot be determined, "name" is used as a default.

  mitk::DataTreeFilter::ConstItemIterator itemiterend( m_DataTreeFilter->GetItems()->End() );
  --itemiterend; // last but one item (first items are often empty, just for structure)
  if (itemiterend != m_DataTreeFilter->GetItems()->End())
  {
    // visible properties left to right
    for( mitk::DataTreeFilter::PropertyList::const_iterator nameiter = m_DataTreeFilter->GetVisibleProperties().begin();
        nameiter != m_DataTreeFilter->GetVisibleProperties().end();
        ++nameiter )
    {
      // check if this is a string item
      const mitk::BaseProperty* property( itemiterend->GetProperty(*nameiter) );

      if ( const mitk::StringProperty* prop = dynamic_cast<const mitk::StringProperty*>(property) )
      {
        // success, use this for display
        m_DisplayedProperty = prop->GetValue();
        break;
      }
    }
  }

  m_DisplayedProperty = "name";
}

void QmitkDataTreeComboBox::SetDisplayedProperty(std::string prop)
{
  m_UserSetDisplayedProperty = prop;
  determineDisplayedProperty();
}

void QmitkDataTreeComboBox::AddItemsToList(const mitk::DataTreeFilter::ItemList* items,
                                           const mitk::DataTreeFilter::PropertyList& visibleProps,
                                           int level)
{
  mitk::DataTreeFilter::ConstItemIterator itemiter( items->Begin() );
  mitk::DataTreeFilter::ConstItemIterator itemiterend( items->End() );

  while ( itemiter != itemiterend ) // for all items
  {

    if (*itemiter == m_SkipItem)
    {
      // skip the item
      ++itemiter;
      continue;
    }

    // use first string property of visible properties list
    QString displayedText( ((const std::string)itemiter->GetProperty(m_DisplayedProperty)).c_str() );

    if ( m_DataTreeFilter->GetHierarchyHandling() != mitk::DataTreeFilter::FLATTEN_HIERARCHY )
    {
      displayedText = QString(" ") + displayedText;
      for (int i = 0; i < level; ++i)
        displayedText = QString("-") + displayedText;
    }

    m_Items.push_back(*itemiter);
    QComboBox::insertItem(displayedText);

    if ( itemiter->HasChildren() )
    {
      // add children, unless this item is the parent whose children were just deleted
      if (*itemiter != m_SkipItemParent)
        AddItemsToList(itemiter->GetChildren(), visibleProps, level+1);
    }

    ++itemiter;
  }
}

void QmitkDataTreeComboBox::clearItems()
{
  QComboBox::clear();
  m_Items.clear();
}

void QmitkDataTreeComboBox::generateItems()
{
  if (!m_DataTreeFilter) return;

  clearItems();

  // query DataTreeFilter about items and properties,
  // then ask factory to create PropertyObservers,
  // add them to the visible Qt items
  const mitk::DataTreeFilter::PropertyList&  visibleProps( m_DataTreeFilter->GetVisibleProperties() );

  // fill rows with property views for the visible items
  AddItemsToList(m_DataTreeFilter->GetItems(), visibleProps, 0);
}

void QmitkDataTreeComboBox::removeItemHandler( const itk::EventObject& e )
{
  const mitk::TreeFilterRemoveItemEvent& event( static_cast<const mitk::TreeFilterRemoveItemEvent&>(e) );
  m_SkipItem = event.GetChangedItem();
  // TODO: do something more clever
  generateItems();
  m_SkipItem = NULL;
}

void QmitkDataTreeComboBox::removeChildrenHandler( const itk::EventObject& e )
{
  const mitk::TreeFilterRemoveChildrenEvent& event( static_cast<const mitk::TreeFilterRemoveChildrenEvent&>(e) );
  // TODO: do something more clever
  m_SkipItemParent = event.GetChangedItem();
  generateItems();
  m_SkipItemParent = NULL;
}

void QmitkDataTreeComboBox::removeAllHandler( const itk::EventObject& )
{
  clearItems();
}

void QmitkDataTreeComboBox::selectionChangedHandler( const itk::EventObject& e)
{
  if (m_SelfCall) return; // invoked by this object

  const mitk::TreeFilterSelectionChangedEvent& event( static_cast<const mitk::TreeFilterSelectionChangedEvent&>(e) );
  const mitk::DataTreeFilter::Item* item = event.GetChangedItem();
  if (!event.IsSelected()) return; // only positive selections

  // find item, change selection, done
  int row(0);
  try
  {
    for (; row < QComboBox::count(); ++row)
      if ( m_Items.at(row) == item )
      {
        QComboBox::setCurrentItem(row);
        emit activated(m_Items.at(row));
        break;
      }
  }
  catch (std::out_of_range)
  {
    std::cerr << "in selectionChangedHandler(" << row << "), " << __FILE__ << " l. " << __LINE__ << ": not a good index..." << std::endl;
  }

}

void QmitkDataTreeComboBox::itemAddedHandler( const itk::EventObject& /*e*/ )
{
  //const mitk::TreeFilterItemAddedEvent& event( static_cast<const TreeFilterItemAddedEvent&>(e) );
  //mitk::DataTreeFilter::Item* item = event.GetChangedItem();
  // TODO: do something more clever
  generateItems();
}

void QmitkDataTreeComboBox::updateAllHandler( const itk::EventObject& )
{
  determineDisplayedProperty();
  generateItems();
}

<commit_msg>Added documentation.<commit_after>#include <QmitkDataTreeComboBox.h>
#include <QmitkPropertyViewFactory.h>

#include <itkCommand.h>
#include <mitkDataTreeFilterEvents.h>

#include <qobjectlist.h>

#include <stdexcept>

/**
  Initializes QmitkDataTreeComboBox from nothing. Results in an empty widget. Call SetDataTree or GetFilter later to fill widget with items.

  \param parent Qt widget that is parent
  \param name Qt name
*/
QmitkDataTreeComboBox::QmitkDataTreeComboBox(QWidget* parent, const char* name)
: QComboBox(parent, name),
  m_DataTreeFilter(NULL)
{
  initialize();
}

/**
  Initializes DataTreeComboBox from a mitk::DataTreeFilter.

  \param filter pointer to the mitk::DataTreeFilter to be displayed
  \param parent Qt widget that is parent
  \param name Qt name
*/
QmitkDataTreeComboBox::QmitkDataTreeComboBox(mitk::DataTreeFilter* filter,QWidget* parent, const char* name)
: QComboBox(parent, name),
  m_DataTreeFilter(filter)
{
  initialize();
  SetFilter(filter);
}

/**
  Initializes DataTreeComboBox from a mitk::DataTreeBase. Will create a private mitk::DataTreeFilter, containing only the "name" and "visible" properties of anything

  \param tree pointer to the mitk::DataTreeBase to be displayed (after creating a private filter)
  \param parent Qt widget that is parent
  \param name Qt name
*/
QmitkDataTreeComboBox::QmitkDataTreeComboBox(mitk::DataTreeBase* tree,QWidget* parent, const char* name)
: QComboBox(parent, name),
  m_DataTreeFilter(NULL)
{
  initialize();
  SetDataTree(tree);
}

/**
  Initializes DataTreeListView from a mitk::DataTreeIteratorBase. Will create a private mitk::DataTreeFilter, containing only the "name" and "visible" properties of anything

  \param iterator  pointer to the mitk::DataTreeIteratorBase, which points anywhere into the data tree to be displayed (after creating a private filter)
  \param parent Qt widget that is parent
  \param name Qt name
*/
QmitkDataTreeComboBox::QmitkDataTreeComboBox(mitk::DataTreeIteratorBase* iterator,QWidget* parent, const char* name)
: QComboBox(parent, name),
  m_DataTreeFilter(NULL)
{
  initialize();
  SetDataTree(iterator);
}

/**
  This is called by all constructors. Initializes some members.
*/
void QmitkDataTreeComboBox::initialize()
{
  // member initializations that are equal for all constructors
  m_SkipItem = NULL;
  m_SkipItemParent = NULL;
  m_SelfCall = false;
  m_DisplayedProperty.clear();
  m_UserSetDisplayedProperty.clear();

  connect(this, SIGNAL(activated(int)), this, SLOT(onActivated(int)));
}

/**
  Minor cleanup. Disconnect all itk-observers.
*/
QmitkDataTreeComboBox::~QmitkDataTreeComboBox()
{
  disconnectNotifications();
}

/**
  Creates new itk-observers for the notifications of mitk::DataTreeFilter. Connects them to ...Handler(itk::EventObject) functions.
*/
void QmitkDataTreeComboBox::connectNotifications()
{
  if (!m_DataTreeFilter) return;

  // connect to our filter's notifications
  {
  itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::Pointer command1 = itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::New();
  command1->SetCallbackFunction(this, &QmitkDataTreeComboBox::removeItemHandler);
  m_RemoveItemConnection = m_DataTreeFilter->AddObserver(mitk::TreeFilterRemoveItemEvent(), command1);
  }
  {
  itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::Pointer command2= itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::New();
  command2->SetCallbackFunction(this, &QmitkDataTreeComboBox::removeChildrenHandler);
  m_RemoveChildrenConnection = m_DataTreeFilter->AddObserver(mitk::TreeFilterRemoveChildrenEvent(), command2);
  }
  {
  itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::Pointer command3 = itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::New();
  command3->SetCallbackFunction(this, &QmitkDataTreeComboBox::removeAllHandler);
  m_RemoveAllConnection = m_DataTreeFilter->AddObserver(mitk::TreeFilterRemoveAllEvent(), command3);
  }
  {
  itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::Pointer command4 = itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::New();
  command4->SetCallbackFunction(this, &QmitkDataTreeComboBox::selectionChangedHandler);
  m_SelectionChangedConnection = m_DataTreeFilter->AddObserver(mitk::TreeFilterSelectionChangedEvent(), command4);
  }
  {
  itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::Pointer command5 = itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::New();
  command5->SetCallbackFunction(this, &QmitkDataTreeComboBox::itemAddedHandler);
  m_ItemAddedConnection = m_DataTreeFilter->AddObserver(mitk::TreeFilterItemAddedEvent(), command5);
  }
  {
  itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::Pointer command6 = itk::ReceptorMemberCommand<QmitkDataTreeComboBox>::New();
  command6->SetCallbackFunction(this, &QmitkDataTreeComboBox::updateAllHandler);
  m_UpdateAllConnection = m_DataTreeFilter->AddObserver(mitk::TreeFilterUpdateAllEvent(), command6);
  }
}

/**
  removes all itk-Observers
*/
void QmitkDataTreeComboBox::disconnectNotifications()
{
  if (!m_DataTreeFilter) return;

  m_DataTreeFilter->RemoveObserver( m_RemoveItemConnection );
  m_DataTreeFilter->RemoveObserver( m_RemoveChildrenConnection );
  m_DataTreeFilter->RemoveObserver( m_RemoveAllConnection );
  m_DataTreeFilter->RemoveObserver( m_SelectionChangedConnection );
  m_DataTreeFilter->RemoveObserver( m_ItemAddedConnection );
  m_DataTreeFilter->RemoveObserver( m_UpdateAllConnection );
}

/**
  User provides only a data tree and does not tell, what should be displayed. So this method creates a private
  mitk::DataTreeFilter, determines only "name" to be visible.
  Then the pointer m_DataTreeFilter is set to this private filter.

  \param tree Tree to display
*/
void QmitkDataTreeComboBox::SetDataTree(mitk::DataTreeBase* tree)
{
  if (tree)
  {
    // create default filter with visibility (editable) and name (non-editable)
    m_PrivateFilter = mitk::DataTreeFilter::New(tree);
    m_PrivateFilter->SetFilter(&mitk::IsImage);
    m_PrivateFilter->SetSelectionMode(mitk::DataTreeFilter::SINGLE_SELECT);
    mitk::DataTreeFilter::PropertyList visible;
    visible.push_back("name");
    m_PrivateFilter->SetVisibleProperties(visible);

    disconnectNotifications();
    m_DataTreeFilter = m_PrivateFilter;
    connectNotifications(); // add observers

    SetDisplayedProperty("name");
    generateItems();
  }
  else
  {
    disconnectNotifications();
    m_DataTreeFilter = NULL;
    m_PrivateFilter = NULL;
    generateItems();
  }
}

/**
  Get the tree behind the iterator and call the other SetDataTree()

  \param iterator  pointer to the mitk::DataTreeIteratorBase, which points anywhere into the data tree to be displayed (after creating a private filter)
*/
void QmitkDataTreeComboBox::SetDataTree(mitk::DataTreeIteratorBase* iterator)
{
  // create default filter if neccessary
  if (iterator && iterator->GetTree())
    SetDataTree(iterator->GetTree());
}

/**
  Display items from the mitk::DataTreeFilter provided in \a filter. Warn if filter's selection mode is not SINGLE_SELECT,
  because a combobox can only mark one object as selected.

  \param filter pointer to the mitk::DataTreeFilter to be displayed
*/
void QmitkDataTreeComboBox::SetFilter(mitk::DataTreeFilter* filter)
{
  disconnectNotifications();
  m_DataTreeFilter = filter;
  // in the case that somebody first sets a datatree and then a filter
  // destroy the default filter that was created in SetDataTree
  if (filter != m_PrivateFilter.GetPointer())
    m_PrivateFilter = NULL;
  connectNotifications(); // add observers

  if ( m_DataTreeFilter->GetSelectionMode() != mitk::DataTreeFilter::SINGLE_SELECT )
  {
    std::cerr << "---------------------------------------------------------------------------"
              << "QmitkDataTreeComboBoxes work only correctly with SINGLE_SELECT data tree filters!"
              << std::endl
              << "The filter you assigned in " << __FILE__ << ", l. " << __LINE__ << " has a differenct SelectionMode. Please change that."
              << std::endl
              << "If you don't know what this means, ask your programmer about it."
              << std::endl
              << "---------------------------------------------------------------------------"
              << std::endl;
  }

  determineDisplayedProperty();
  generateItems();
}

/**
  Get the currently active mitk::DataTreeFilter. May either be user provided or created privatly for some data tree.

  \return active mitk::DataTreeFilter
*/
mitk::DataTreeFilter* QmitkDataTreeComboBox::GetFilter()
{
  return m_DataTreeFilter;
}

/**
  Called whenever the user selects a different item. The task here is to find the belonging item and change its selection status.
  The formerly selected item is correctly deselected by mitk::DataTreeFilter::Item::SetSelected(bool), when the DataTreeFilter's
  selection mode is SINGLE_SELECT.
*/
void QmitkDataTreeComboBox::onActivated(int index)
{
  // find item, generate signal
  try
  {
    // following cast is due to bad design... class Item needs needs rework
    m_SelfCall = true;
    const_cast<mitk::DataTreeFilter::Item*>(m_Items.at(index))->SetSelected(true);
    emit activated(m_Items.at(index));
    m_SelfCall = false;
  }
  catch (std::out_of_range)
  {
    std::cerr << "in onActivated(" << index << "), " << __FILE__ << "l. " << __LINE__ << ": not a good index..." << std::endl;
  }

  // TODO on selectionChanged notifications from treefilter => change selection!
}

/**
  If the user has not determined (via SetDisplayedProperty), which property should be displayed, this method
  tries to find a mitk::StringProperty in the DataTreeFilter's list of available properties.

  Defaults to the "name" property.
*/
void QmitkDataTreeComboBox::determineDisplayedProperty()
{
  if ( !m_UserSetDisplayedProperty.empty() )
    if (std::find( m_DataTreeFilter->GetVisibleProperties().begin(), m_DataTreeFilter->GetVisibleProperties().end(), m_UserSetDisplayedProperty )
        != m_DataTreeFilter->GetVisibleProperties().end() )
    {
      m_DisplayedProperty = m_UserSetDisplayedProperty;
      return;
    }

  // if this line is reached, either the user has not chosen a property to be displayed, or
  // that property is not available from the filter used.

  m_DisplayedProperty.clear();

  // This (often) determines the key of the left-most string property.
  // If such a property cannot be determined, "name" is used as a default.

  mitk::DataTreeFilter::ConstItemIterator itemiterend( m_DataTreeFilter->GetItems()->End() );
  --itemiterend; // last but one item (first items are often empty, just for structure)
  if (itemiterend != m_DataTreeFilter->GetItems()->End())
  {
    // visible properties left to right
    for( mitk::DataTreeFilter::PropertyList::const_iterator nameiter = m_DataTreeFilter->GetVisibleProperties().begin();
        nameiter != m_DataTreeFilter->GetVisibleProperties().end();
        ++nameiter )
    {
      // check if this is a string item
      const mitk::BaseProperty* property( itemiterend->GetProperty(*nameiter) );

      if ( const mitk::StringProperty* prop = dynamic_cast<const mitk::StringProperty*>(property) )
      {
        // success, use this for display
        m_DisplayedProperty = prop->GetValue();
        break;
      }
    }
  }

  m_DisplayedProperty = "name";
}

/**
  Let the user set the property to be displayed. Then regenerate items.

  \param prop String key to the property to be displayed
*/
void QmitkDataTreeComboBox::SetDisplayedProperty(std::string prop)
{
  m_UserSetDisplayedProperty = prop;
  determineDisplayedProperty();
  generateItems();
}

/**
  This method creates combo box items for the item list that is provided by a mitk::DataTreeFilter.

  \param items The top level item list (items may have children, then this method calls itself recursively)
  \param visibleProps Properties for which display widgets should be created
  \param level Level of recursion. Needed to display the right amout of indentation for child items.
*/
*/
void QmitkDataTreeComboBox::AddItemsToList(const mitk::DataTreeFilter::ItemList* items,
                                           const mitk::DataTreeFilter::PropertyList& visibleProps,
                                           int level)
{
  mitk::DataTreeFilter::ConstItemIterator itemiter( items->Begin() );
  mitk::DataTreeFilter::ConstItemIterator itemiterend( items->End() );

  while ( itemiter != itemiterend ) // for all items
  {

    if (*itemiter == m_SkipItem)
    {
      // skip the item
      ++itemiter;
      continue;
    }

    // use first string property of visible properties list
    QString displayedText( ((const std::string)itemiter->GetProperty(m_DisplayedProperty)).c_str() );

    if ( m_DataTreeFilter->GetHierarchyHandling() != mitk::DataTreeFilter::FLATTEN_HIERARCHY )
    {
      displayedText = QString(" ") + displayedText;
      for (int i = 0; i < level; ++i)
        displayedText = QString("-") + displayedText;
    }

    m_Items.push_back(*itemiter);
    QComboBox::insertItem(displayedText);

    if ( itemiter->HasChildren() )
    {
      // add children, unless this item is the parent whose children were just deleted
      if (*itemiter != m_SkipItemParent)
        AddItemsToList(itemiter->GetChildren(), visibleProps, level+1);
    }

    ++itemiter;
  }
}

/**
  Deletes all child widgets.
*/
void QmitkDataTreeComboBox::clearItems()
{
  QComboBox::clear();
  m_Items.clear();
}

/**
  Regenerates all displayed items.
*/
void QmitkDataTreeComboBox::generateItems()
{
  if (!m_DataTreeFilter) return;

  clearItems();

  // query DataTreeFilter about items and properties,
  // then ask factory to create PropertyObservers,
  // add them to the visible Qt items
  const mitk::DataTreeFilter::PropertyList&  visibleProps( m_DataTreeFilter->GetVisibleProperties() );

  // fill rows with property views for the visible items
  AddItemsToList(m_DataTreeFilter->GetItems(), visibleProps, 0);
}

/**
  Handles TreeFilterRemoveItemEvents from the DataTreeFilter. For this purpose a variable m_SkipItem is set to contain the
  item, which will shortly be deleted. This is necessary because the notification is sent while the item still exists.
  m_SkipItem is considered in generateItem().
  Perhaps something more sophisticated could be implemented.
*/
void QmitkDataTreeComboBox::removeItemHandler( const itk::EventObject& e )
{
  const mitk::TreeFilterRemoveItemEvent& event( static_cast<const mitk::TreeFilterRemoveItemEvent&>(e) );
  m_SkipItem = event.GetChangedItem();
  // TODO: do something more clever
  generateItems();
  m_SkipItem = NULL;
}

/**
  Handles TreeFilterRemoveChildrenEvents from the DataTreeFilter. For this purpose a variable m_SkipItemParent is set to contain the
  item, which will shortly be deleted. This is necessary because the notification is sent while the item still exists.
  m_SkipItemParent is considered in generateItem().
  Perhaps something more sophisticated could be implemented.
*/
void QmitkDataTreeComboBox::removeChildrenHandler( const itk::EventObject& e )
{
  const mitk::TreeFilterRemoveChildrenEvent& event( static_cast<const mitk::TreeFilterRemoveChildrenEvent&>(e) );
  // TODO: do something more clever
  m_SkipItemParent = event.GetChangedItem();
  generateItems();
  m_SkipItemParent = NULL;
}

/**
  Handles TreeFilterRemoveAllEvents from the DataTreeFilter. The implementation is extremely easy, as clearing all items is
  needed in other contexts as well.
*/
void QmitkDataTreeComboBox::removeAllHandler( const itk::EventObject& )
{
  clearItems();
}

/**
  Handles TreeFilterSelectionChangedEvents from the DataTreeFilter.
*/
void QmitkDataTreeComboBox::selectionChangedHandler( const itk::EventObject& e)
{
  if (m_SelfCall) return; // invoked by this object

  const mitk::TreeFilterSelectionChangedEvent& event( static_cast<const mitk::TreeFilterSelectionChangedEvent&>(e) );
  const mitk::DataTreeFilter::Item* item = event.GetChangedItem();
  if (!event.IsSelected()) return; // only positive selections

  // find item, change selection, done
  int row(0);
  try
  {
    for (; row < QComboBox::count(); ++row)
      if ( m_Items.at(row) == item )
      {
        QComboBox::setCurrentItem(row);
        emit activated(m_Items.at(row));
        break;
      }
  }
  catch (std::out_of_range)
  {
    std::cerr << "in selectionChangedHandler(" << row << "), " << __FILE__ << " l. " << __LINE__ << ": not a good index..." << std::endl;
  }

}

/**
  Handles TreeFilterItemAddedEvents from the DataTreeFilter. Implemented by simply regenerating everything.
  Perhaps something more sophisticated could be implemented.
*/
void QmitkDataTreeComboBox::itemAddedHandler( const itk::EventObject& /*e*/ )
{
  //const mitk::TreeFilterItemAddedEvent& event( static_cast<const TreeFilterItemAddedEvent&>(e) );
  //mitk::DataTreeFilter::Item* item = event.GetChangedItem();
  // TODO: do something more clever
  generateItems();
}

/**
  Handles TreeFilterUpdateAllEvents from the DataTreeFilter.
*/
void QmitkDataTreeComboBox::updateAllHandler( const itk::EventObject& )
{
  determineDisplayedProperty();
  generateItems();
}

<|endoftext|>


<commit_before>/*
    WDL - wndsize.cpp
    Copyright (C) 2004 and later, Cockos Incorporated

    This software is provided 'as-is', without any express or implied
    warranty.  In no event will the authors be held liable for any damages
    arising from the use of this software.

    Permission is granted to anyone to use this software for any purpose,
    including commercial applications, and to alter it and redistribute it
    freely, subject to the following restrictions:

    1. The origin of this software must not be misrepresented; you must not
       claim that you wrote the original software. If you use this software
       in a product, an acknowledgment in the product documentation would be
       appreciated but is not required.
    2. Altered source versions must be plainly marked as such, and must not be
       misrepresented as being the original software.
    3. This notice may not be removed or altered from any source distribution.

*/

/*
For information on how to use this class, see wndsize.h :)
*/

#ifndef _WIN32
#include "../swell/swell.h"
#else
#include <windows.h>
#endif

#include "wndsize.h"
#include "virtwnd.h"

void WDL_WndSizer::init(HWND hwndDlg, RECT *initr)
{
  m_hwnd=hwndDlg;
  RECT r;
  if (initr)
    r=*initr;
  else
    GetClientRect(m_hwnd,&r);
  set_orig_rect(&r);

  m_list.Resize(0);

  memset(&m_margins,0,sizeof(m_margins));
}

void WDL_WndSizer::init_item(int dlg_id, float *scales, RECT *initr)
{
  init_item(dlg_id,scales[0],scales[1],scales[2],scales[3],initr);
}
void WDL_WndSizer::init_itemvirt(WDL_VWnd *vwnd, float *scales)
{
  init_itemvirt(vwnd,scales[0],scales[1],scales[2],scales[3]);
}

void WDL_WndSizer::init_itemvirt(WDL_VirtualWnd *vwnd,
                                 float left_scale, float top_scale, float right_scale, float bottom_scale)
{
  RECT this_r={0,};
  if (vwnd) vwnd->GetPosition(&this_r);
  int osize=m_list.GetSize();
  m_list.Resize(osize+sizeof(WDL_WndSizer__rec));

  WDL_WndSizer__rec *rec=(WDL_WndSizer__rec *) ((char *)m_list.Get()+osize);

  rec->hwnd=0;
  rec->vwnd=vwnd;
  rec->scales[0]=left_scale;
  rec->scales[1]=top_scale;
  rec->scales[2]=right_scale;
  rec->scales[3]=bottom_scale;
  rec->real_orig = rec->last = rec->orig = this_r;
}

void WDL_WndSizer::init_itemhwnd(HWND h, float left_scale, float top_scale, float right_scale, float bottom_scale, RECT *srcr)
{
  RECT this_r={0,};
  if (srcr) this_r=*srcr;
  else if (h)
  {
    GetWindowRect(h,&this_r);
    ScreenToClient(m_hwnd,(LPPOINT) &this_r);
    ScreenToClient(m_hwnd,((LPPOINT) &this_r)+1);

  #ifndef _WIN32
    if (this_r.bottom < this_r.top)
    {
      int oh=this_r.top-this_r.bottom;
      this_r.bottom=this_r.top;
      this_r.top -= oh;
    }
  #endif
  }
  int osize=m_list.GetSize();
  m_list.Resize(osize+sizeof(WDL_WndSizer__rec));

  WDL_WndSizer__rec *rec=(WDL_WndSizer__rec *) ((char *)m_list.Get()+osize);

  rec->hwnd=h;
  rec->vwnd=0;
  rec->scales[0]=left_scale;
  rec->scales[1]=top_scale;
  rec->scales[2]=right_scale;
  rec->scales[3]=bottom_scale;

  rec->real_orig = rec->last = rec->orig = this_r;
}

void WDL_WndSizer::init_item(int dlg_id, float left_scale, float top_scale, float right_scale, float bottom_scale, RECT *initr)
{
  init_itemhwnd(GetDlgItem(m_hwnd,dlg_id),left_scale,top_scale,right_scale,bottom_scale,initr);
}

#ifdef _WIN32
BOOL CALLBACK WDL_WndSizer::enum_RegionRemove(HWND hwnd,LPARAM lParam)
{
  WDL_WndSizer *_this=(WDL_WndSizer *)lParam;
//  if(GetParent(hwnd)!=_this->m_hwnd) return TRUE;

  if (IsWindowVisible(hwnd))
  {
    RECT r;
    GetWindowRect(hwnd,&r);
    ScreenToClient(_this->m_hwnd,(LPPOINT)&r);
    ScreenToClient(_this->m_hwnd,((LPPOINT)&r)+1);

    HRGN rgn2=CreateRectRgn(r.left,r.top,r.right,r.bottom);
    CombineRgn(_this->m_enum_rgn,_this->m_enum_rgn,rgn2,RGN_DIFF);
    DeleteObject(rgn2);
  }

  return TRUE;
}
#endif

void WDL_WndSizer::remove_item(int dlg_id)
{
  remove_itemhwnd(GetDlgItem(m_hwnd,dlg_id));
}

void WDL_WndSizer::remove_itemhwnd(HWND h)
{
  WDL_WndSizer__rec *rec;
  while ((rec=get_itembywnd(h)))
  {
    WDL_WndSizer__rec *list=(WDL_WndSizer__rec *) ((char *)m_list.Get());
    int list_size=m_list.GetSize()/sizeof(WDL_WndSizer__rec);
    int idx=rec-list;

    if (idx >= 0 && idx < list_size-1)
      memcpy(rec,rec+1,(list_size-(idx+1))*sizeof(WDL_WndSizer__rec));
    m_list.Resize((list_size-1)*sizeof(WDL_WndSizer__rec));
  }
}

void WDL_WndSizer::remove_itemvirt(WDL_VirtualWnd *vwnd)
{
  WDL_WndSizer__rec *rec;
  while ((rec=get_itembyvirt(vwnd)))
  {
    WDL_WndSizer__rec *list=(WDL_WndSizer__rec *) ((char *)m_list.Get());
    int list_size=m_list.GetSize()/sizeof(WDL_WndSizer__rec);
    int idx=rec-list;

    if (idx >= 0 && idx < list_size-1)
      memcpy(rec,rec+1,(list_size-(idx+1))*sizeof(WDL_WndSizer__rec));
    m_list.Resize((list_size-1)*sizeof(WDL_WndSizer__rec));
  }
}

void WDL_WndSizer::transformRect(RECT *r, const float *scales, const RECT *wndSize)
{
  POINT sz = { wndSize->right, wndSize->bottom };
  if (sz.x < m_min_size.x) sz.x=m_min_size.x;
  if (sz.y < m_min_size.y) sz.y=m_min_size.y;

  sz.x -= m_orig_size.x;
  sz.y -= m_orig_size.y;

  if (scales[0] >= 1.0) r->left += sz.x;
  else if (scales[0]>0.0) r->left += (int) (sz.x*scales[0]);

  if (scales[1] >= 1.0) r->top += sz.y;
  else if (scales[1]>0.0) r->top += (int) (sz.y*scales[1]);

  if (scales[2] >= 1.0) r->right += sz.x;
  else if (scales[2]>0.0) r->right += (int) (sz.x*scales[2]);

  if (scales[3] >= 1.0) r->bottom += sz.y;
  else if (scales[3]>0.0) r->bottom += (int) (sz.y*scales[3]);

  r->left += m_margins.left;
  r->right += m_margins.left;
  r->top += m_margins.top;
  r->bottom += m_margins.top;

  if (r->bottom < r->top) r->bottom=r->top;
  if (r->right < r->left) r->right=r->left;
}

void WDL_WndSizer::onResize(HWND only, int notouch, int xtranslate, int ytranslate)
{
  if (!m_hwnd) return;

  RECT new_rect;

  GetClientRect(m_hwnd,&new_rect);
#ifdef _WIN32

  m_enum_rgn=CreateRectRgn(new_rect.left,new_rect.top,new_rect.right,new_rect.bottom);
 // EnumChildWindows(m_hwnd,enum_RegionRemove,(LPARAM)this);

  HDWP hdwndpos=NULL;
  int has_dfwp=0;
#endif
  WDL_WndSizer__rec *rec=(WDL_WndSizer__rec *) ((char *)m_list.Get());
  int cnt=m_list.GetSize() / sizeof(WDL_WndSizer__rec);

  new_rect.right -= m_margins.left+m_margins.right;
  new_rect.bottom -= m_margins.top+m_margins.bottom;

  int x;
  for (x = 0; x < cnt; x ++)
  {

    if ((rec->vwnd && !only) || (rec->hwnd && (!only || only == rec->hwnd)))
    {
      RECT r=rec->orig;
      transformRect(&r,rec->scales,&new_rect);

      rec->last = r;

      if (!notouch)
      {
        if (rec->hwnd)
        {
#ifdef _WIN32
          if (!has_dfwp)
          {
            has_dfwp=1;
            if (!only && GetVersion() < 0x80000000) hdwndpos=BeginDeferWindowPos(cnt);
          }

          if (IsWindow(rec->hwnd))
          {
            if (!hdwndpos)
#endif
              SetWindowPos(rec->hwnd, NULL, r.left+xtranslate,r.top+ytranslate,r.right-r.left,r.bottom-r.top, SWP_NOZORDER|SWP_NOACTIVATE);

#ifdef _WIN32
            else
            {
              hdwndpos=DeferWindowPos(hdwndpos, rec->hwnd, NULL, r.left+xtranslate,r.top+ytranslate,r.right-r.left,r.bottom-r.top, SWP_NOZORDER|SWP_NOACTIVATE);
            }
          }
#endif
        }
        if (rec->vwnd)
        {
          rec->vwnd->SetPosition(&r);
        }
      }
    }
    rec++;
  }
#ifdef _WIN32
  if (hdwndpos) EndDeferWindowPos(hdwndpos);

  EnumChildWindows(m_hwnd,enum_RegionRemove,(LPARAM)this);
  InvalidateRgn(m_hwnd,m_enum_rgn,FALSE);
  DeleteObject(m_enum_rgn);
#endif
}

WDL_WndSizer__rec *WDL_WndSizer::get_itembyindex(int id)
{
  if (id >= 0 && id < (m_list.GetSize() / (int)sizeof(WDL_WndSizer__rec)))
  {
    return ((WDL_WndSizer__rec *) m_list.Get())+id;
  }
  return NULL;
}

WDL_WndSizer__rec *WDL_WndSizer::get_itembywnd(HWND h)
{
  if (h)
  {
    WDL_WndSizer__rec *rec=(WDL_WndSizer__rec *) ((char *)m_list.Get());
    int cnt=m_list.GetSize() / sizeof(WDL_WndSizer__rec);
    while (cnt--)
    {
      if (rec->hwnd == h) return rec;
      rec++;
    }
  }
  return 0;
}

WDL_WndSizer__rec *WDL_WndSizer::get_itembyvirt(WDL_VirtualWnd *vwnd)
{
  if (!vwnd) return 0;
  WDL_WndSizer__rec *rec=(WDL_WndSizer__rec *) ((char *)m_list.Get());
  int cnt=m_list.GetSize() / sizeof(WDL_WndSizer__rec);
  while (cnt--)
  {
    if (rec->vwnd == vwnd) return rec;
    rec++;
  }
  return 0;
}

WDL_WndSizer__rec *WDL_WndSizer::get_item(int dlg_id)
{
  WDL_WndSizer__rec *rec=(WDL_WndSizer__rec *) ((char *)m_list.Get());
  int cnt=m_list.GetSize() / sizeof(WDL_WndSizer__rec);
  while (cnt--)
  {
    if (rec->vwnd && rec->vwnd->GetID() == dlg_id) return rec;
    rec++;
  }

  return get_itembywnd(GetDlgItem(m_hwnd,dlg_id));
}
<commit_msg>wndsizer: transformRect() applies margins directly -- from e78f203<commit_after>/*
    WDL - wndsize.cpp
    Copyright (C) 2004 and later, Cockos Incorporated

    This software is provided 'as-is', without any express or implied
    warranty.  In no event will the authors be held liable for any damages
    arising from the use of this software.

    Permission is granted to anyone to use this software for any purpose,
    including commercial applications, and to alter it and redistribute it
    freely, subject to the following restrictions:

    1. The origin of this software must not be misrepresented; you must not
       claim that you wrote the original software. If you use this software
       in a product, an acknowledgment in the product documentation would be
       appreciated but is not required.
    2. Altered source versions must be plainly marked as such, and must not be
       misrepresented as being the original software.
    3. This notice may not be removed or altered from any source distribution.

*/

/*
For information on how to use this class, see wndsize.h :)
*/

#ifndef _WIN32
#include "../swell/swell.h"
#else
#include <windows.h>
#endif

#include "wndsize.h"
#include "virtwnd.h"

void WDL_WndSizer::init(HWND hwndDlg, RECT *initr)
{
  m_hwnd=hwndDlg;
  RECT r;
  if (initr)
    r=*initr;
  else
    GetClientRect(m_hwnd,&r);
  set_orig_rect(&r);

  m_list.Resize(0);

  memset(&m_margins,0,sizeof(m_margins));
}

void WDL_WndSizer::init_item(int dlg_id, float *scales, RECT *initr)
{
  init_item(dlg_id,scales[0],scales[1],scales[2],scales[3],initr);
}
void WDL_WndSizer::init_itemvirt(WDL_VWnd *vwnd, float *scales)
{
  init_itemvirt(vwnd,scales[0],scales[1],scales[2],scales[3]);
}

void WDL_WndSizer::init_itemvirt(WDL_VirtualWnd *vwnd,
                                 float left_scale, float top_scale, float right_scale, float bottom_scale)
{
  RECT this_r={0,};
  if (vwnd) vwnd->GetPosition(&this_r);
  int osize=m_list.GetSize();
  m_list.Resize(osize+sizeof(WDL_WndSizer__rec));

  WDL_WndSizer__rec *rec=(WDL_WndSizer__rec *) ((char *)m_list.Get()+osize);

  rec->hwnd=0;
  rec->vwnd=vwnd;
  rec->scales[0]=left_scale;
  rec->scales[1]=top_scale;
  rec->scales[2]=right_scale;
  rec->scales[3]=bottom_scale;
  rec->real_orig = rec->last = rec->orig = this_r;
}

void WDL_WndSizer::init_itemhwnd(HWND h, float left_scale, float top_scale, float right_scale, float bottom_scale, RECT *srcr)
{
  RECT this_r={0,};
  if (srcr) this_r=*srcr;
  else if (h)
  {
    GetWindowRect(h,&this_r);
    ScreenToClient(m_hwnd,(LPPOINT) &this_r);
    ScreenToClient(m_hwnd,((LPPOINT) &this_r)+1);

  #ifndef _WIN32
    if (this_r.bottom < this_r.top)
    {
      int oh=this_r.top-this_r.bottom;
      this_r.bottom=this_r.top;
      this_r.top -= oh;
    }
  #endif
  }
  int osize=m_list.GetSize();
  m_list.Resize(osize+sizeof(WDL_WndSizer__rec));

  WDL_WndSizer__rec *rec=(WDL_WndSizer__rec *) ((char *)m_list.Get()+osize);

  rec->hwnd=h;
  rec->vwnd=0;
  rec->scales[0]=left_scale;
  rec->scales[1]=top_scale;
  rec->scales[2]=right_scale;
  rec->scales[3]=bottom_scale;

  rec->real_orig = rec->last = rec->orig = this_r;
}

void WDL_WndSizer::init_item(int dlg_id, float left_scale, float top_scale, float right_scale, float bottom_scale, RECT *initr)
{
  init_itemhwnd(GetDlgItem(m_hwnd,dlg_id),left_scale,top_scale,right_scale,bottom_scale,initr);
}

#ifdef _WIN32
BOOL CALLBACK WDL_WndSizer::enum_RegionRemove(HWND hwnd,LPARAM lParam)
{
  WDL_WndSizer *_this=(WDL_WndSizer *)lParam;
//  if(GetParent(hwnd)!=_this->m_hwnd) return TRUE;

  if (IsWindowVisible(hwnd))
  {
    RECT r;
    GetWindowRect(hwnd,&r);
    ScreenToClient(_this->m_hwnd,(LPPOINT)&r);
    ScreenToClient(_this->m_hwnd,((LPPOINT)&r)+1);

    HRGN rgn2=CreateRectRgn(r.left,r.top,r.right,r.bottom);
    CombineRgn(_this->m_enum_rgn,_this->m_enum_rgn,rgn2,RGN_DIFF);
    DeleteObject(rgn2);
  }

  return TRUE;
}
#endif

void WDL_WndSizer::remove_item(int dlg_id)
{
  remove_itemhwnd(GetDlgItem(m_hwnd,dlg_id));
}

void WDL_WndSizer::remove_itemhwnd(HWND h)
{
  WDL_WndSizer__rec *rec;
  while ((rec=get_itembywnd(h)))
  {
    WDL_WndSizer__rec *list=(WDL_WndSizer__rec *) ((char *)m_list.Get());
    int list_size=m_list.GetSize()/sizeof(WDL_WndSizer__rec);
    int idx=rec-list;

    if (idx >= 0 && idx < list_size-1)
      memcpy(rec,rec+1,(list_size-(idx+1))*sizeof(WDL_WndSizer__rec));
    m_list.Resize((list_size-1)*sizeof(WDL_WndSizer__rec));
  }
}

void WDL_WndSizer::remove_itemvirt(WDL_VirtualWnd *vwnd)
{
  WDL_WndSizer__rec *rec;
  while ((rec=get_itembyvirt(vwnd)))
  {
    WDL_WndSizer__rec *list=(WDL_WndSizer__rec *) ((char *)m_list.Get());
    int list_size=m_list.GetSize()/sizeof(WDL_WndSizer__rec);
    int idx=rec-list;

    if (idx >= 0 && idx < list_size-1)
      memcpy(rec,rec+1,(list_size-(idx+1))*sizeof(WDL_WndSizer__rec));
    m_list.Resize((list_size-1)*sizeof(WDL_WndSizer__rec));
  }
}

void WDL_WndSizer::transformRect(RECT *r, const float *scales, const RECT *wndSize)
{
  POINT sz = { wndSize->right, wndSize->bottom };

  sz.x -= m_margins.left+m_margins.right;
  sz.y -= m_margins.top+m_margins.bottom;

  if (sz.x < m_min_size.x) sz.x=m_min_size.x;
  if (sz.y < m_min_size.y) sz.y=m_min_size.y;

  sz.x -= m_orig_size.x;
  sz.y -= m_orig_size.y;

  if (scales[0] >= 1.0) r->left += sz.x;
  else if (scales[0]>0.0) r->left += (int) (sz.x*scales[0]);

  if (scales[1] >= 1.0) r->top += sz.y;
  else if (scales[1]>0.0) r->top += (int) (sz.y*scales[1]);

  if (scales[2] >= 1.0) r->right += sz.x;
  else if (scales[2]>0.0) r->right += (int) (sz.x*scales[2]);

  if (scales[3] >= 1.0) r->bottom += sz.y;
  else if (scales[3]>0.0) r->bottom += (int) (sz.y*scales[3]);

  r->left += m_margins.left;
  r->right += m_margins.left;
  r->top += m_margins.top;
  r->bottom += m_margins.top;

  if (r->bottom < r->top) r->bottom=r->top;
  if (r->right < r->left) r->right=r->left;
}

void WDL_WndSizer::onResize(HWND only, int notouch, int xtranslate, int ytranslate)
{
  if (!m_hwnd) return;

  RECT new_rect;

  GetClientRect(m_hwnd,&new_rect);
#ifdef _WIN32

  m_enum_rgn=CreateRectRgn(new_rect.left,new_rect.top,new_rect.right,new_rect.bottom);
 // EnumChildWindows(m_hwnd,enum_RegionRemove,(LPARAM)this);

  HDWP hdwndpos=NULL;
  int has_dfwp=0;
#endif
  WDL_WndSizer__rec *rec=(WDL_WndSizer__rec *) ((char *)m_list.Get());
  int cnt=m_list.GetSize() / sizeof(WDL_WndSizer__rec);

  int x;
  for (x = 0; x < cnt; x ++)
  {

    if ((rec->vwnd && !only) || (rec->hwnd && (!only || only == rec->hwnd)))
    {
      RECT r=rec->orig;
      transformRect(&r,rec->scales,&new_rect);

      rec->last = r;

      if (!notouch)
      {
        if (rec->hwnd)
        {
#ifdef _WIN32
          if (!has_dfwp)
          {
            has_dfwp=1;
            if (!only && GetVersion() < 0x80000000) hdwndpos=BeginDeferWindowPos(cnt);
          }

          if (IsWindow(rec->hwnd))
          {
            if (!hdwndpos)
#endif
              SetWindowPos(rec->hwnd, NULL, r.left+xtranslate,r.top+ytranslate,r.right-r.left,r.bottom-r.top, SWP_NOZORDER|SWP_NOACTIVATE);

#ifdef _WIN32
            else
            {
              hdwndpos=DeferWindowPos(hdwndpos, rec->hwnd, NULL, r.left+xtranslate,r.top+ytranslate,r.right-r.left,r.bottom-r.top, SWP_NOZORDER|SWP_NOACTIVATE);
            }
          }
#endif
        }
        if (rec->vwnd)
        {
          rec->vwnd->SetPosition(&r);
        }
      }
    }
    rec++;
  }
#ifdef _WIN32
  if (hdwndpos) EndDeferWindowPos(hdwndpos);

  EnumChildWindows(m_hwnd,enum_RegionRemove,(LPARAM)this);
  InvalidateRgn(m_hwnd,m_enum_rgn,FALSE);
  DeleteObject(m_enum_rgn);
#endif
}

WDL_WndSizer__rec *WDL_WndSizer::get_itembyindex(int id)
{
  if (id >= 0 && id < (m_list.GetSize() / (int)sizeof(WDL_WndSizer__rec)))
  {
    return ((WDL_WndSizer__rec *) m_list.Get())+id;
  }
  return NULL;
}

WDL_WndSizer__rec *WDL_WndSizer::get_itembywnd(HWND h)
{
  if (h)
  {
    WDL_WndSizer__rec *rec=(WDL_WndSizer__rec *) ((char *)m_list.Get());
    int cnt=m_list.GetSize() / sizeof(WDL_WndSizer__rec);
    while (cnt--)
    {
      if (rec->hwnd == h) return rec;
      rec++;
    }
  }
  return 0;
}

WDL_WndSizer__rec *WDL_WndSizer::get_itembyvirt(WDL_VirtualWnd *vwnd)
{
  if (!vwnd) return 0;
  WDL_WndSizer__rec *rec=(WDL_WndSizer__rec *) ((char *)m_list.Get());
  int cnt=m_list.GetSize() / sizeof(WDL_WndSizer__rec);
  while (cnt--)
  {
    if (rec->vwnd == vwnd) return rec;
    rec++;
  }
  return 0;
}

WDL_WndSizer__rec *WDL_WndSizer::get_item(int dlg_id)
{
  WDL_WndSizer__rec *rec=(WDL_WndSizer__rec *) ((char *)m_list.Get());
  int cnt=m_list.GetSize() / sizeof(WDL_WndSizer__rec);
  while (cnt--)
  {
    if (rec->vwnd && rec->vwnd->GetID() == dlg_id) return rec;
    rec++;
  }

  return get_itembywnd(GetDlgItem(m_hwnd,dlg_id));
}
<|endoftext|>