<commit_before>/***************************************************************************
 **
 ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
 ** All rights reserved.
 ** Contact: Nokia Corporation (testabilitydriver@nokia.com)
 **
 ** This file is part of Testability Driver Qt Agent
 **
 ** If you have questions regarding the use of this file, please contact
 ** Nokia at testabilitydriver@nokia.com .
 **
 ** 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
 ** and appearing in the file LICENSE.LGPL included in the packaging
 ** of this file.
 **
 ****************************************************************************/

#include "tasdeviceutils.h"

#if defined(TAS_MAEMO) && defined(HAVE_QAPP)
#include <MApplication>
#include <MWindow>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#endif
#ifdef TAS_MAEMO
#include <qmsystem2/qmdisplaystate.h>
#endif

#include <taslogger.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <X11/Xlib.h>
#include <X11/extensions/XTest.h>

#include <QEvent>

#if defined(TAS_MAEMO) && defined(HAVE_QAPP)
namespace {
int getOrientationForWidget(QWidget* widget)
{
    Display* display = QX11Info::display();
    Atom orientationAngleAtom = XInternAtom(display,
                                            "_MEEGOTOUCH_ORIENTATION_ANGLE", True);
    int orientation = -1;
    Atom actual_type;
    int actual_format;
    unsigned long nitems;
    unsigned long bytes_after;
    unsigned char *prop = 0;
    int status;
    if (widget && orientationAngleAtom != None) {
        TasLogger::logger()->debug("got widget and orientation angle");
        status = XGetWindowProperty(display, widget->effectiveWinId(),
                                    orientationAngleAtom, 0, 1024,
                                    False, AnyPropertyType,
                                    &actual_type, &actual_format, &nitems,
                                    &bytes_after,
                                    &prop);
        if (status!=0 || !prop || actual_format == None) {
            //NOP
        } else {
            TasLogger::logger()->debug("setting it!");
            orientation = prop[1] * 256;
            orientation += prop[0];
            if (prop) XFree(prop);
            return orientation;
        }
    }
    if (prop) XFree(prop);
    return -1;
}
}
#endif

TasDeviceUtils::TasDeviceUtils()
{
    gpuDetailsHandler = 0;
    pwrDetailsHandler = 0;
}

void TasDeviceUtils::resetInactivity()
{
#ifdef TAS_MAEMO
    TasLogger::logger()->debug("TasDeviceUtils:: resetting inactivity");
    MeeGo::QmDisplayState state;

    if (!state.set(MeeGo::QmDisplayState::On)) {
        TasLogger::logger()->warning("TasDeviceUtils:: setting displaystate failed!");
    }

    if (!state.setBlankingPause()) {
        TasLogger::logger()->warning("TasDeviceUtils:: setBlankingPause failed!");
    }
#endif
}

GpuMemDetails TasDeviceUtils::gpuMemDetails()
{
    GpuMemDetails details;
    details.isValid = false;
    return details;
}

PwrDetails TasDeviceUtils::pwrDetails()
{
    PwrDetails details;
    details.isValid = false;
    return details;
}

void TasDeviceUtils::stopPwrData()
{}

// TODO remove the duplicate code (maemo version)

/*!
  Returns the heap size of the process.
  -1 means not supported.
*/
int TasDeviceUtils::currentProcessHeapSize()
{
    char buf[30];
    unsigned size = -1; //       total program size
    // If needed later.
//    unsigned resident = -1;//   resident set size
//    unsigned share;//      shared pages
//    unsigned text;//       text (code)
//    unsigned lib;//        library
//    unsigned data;//       data/stack
//    unsigned dt;//         dirty pages (unused in Linux 2.6)

    snprintf(buf, 30, "/proc/%u/statm", (unsigned)getpid());
    FILE* pf = fopen(buf, "r");
    if (pf) {
        fscanf(pf, "%u "/* %u %u %u %u %u " */, &size /*,&resident, &share, &text, &lib, &data */);
    }
    fclose(pf);
    return size;
}

/*!
 * /proc/cpuinfo data
 */
void TasDeviceUtils::addSystemInformation(TasObject& object)
{
    QFile file("/proc/cpuinfo");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return;
    }

    TasObject& child = object.addObject();
    child.setName("/proc/cpuinfo");
    QTextStream in(&file);
    QString line = in.readLine();
    while (!line.isNull()) {
        QStringList list = line.split(":");
        if (list.size() == 2) {
            child.addAttribute(list[0].trimmed(),list[1].trimmed());
        }
        line = in.readLine();
    }
}

qreal TasDeviceUtils::currentProcessCpuTime()
{
    return -1;
}

/*!
  Not supported
*/
void TasDeviceUtils::addSystemMemoryStatus(TasObject& object)
{

    FILE *meminfo = fopen("/proc/meminfo", "r");
    int ram = -1;
    int ramFree = -1;
    int cached = -1;

    if(meminfo == NULL) {

    } else {
        char line[256];
        while(fgets(line, sizeof(line), meminfo)) {
            if (ram == -1) {
                sscanf(line, "MemTotal: %d kB", &ram);
            } else if (ramFree == -1) {
                sscanf(line, "MemFree: %d kB", &ramFree);
            } else if (cached == -1) {
                sscanf(line, "Cached: %d kB", &cached);
                break;
            }
        }

        object.addAttribute("total",QString::number(ram));
        object.addAttribute("available",QString::number(ramFree));
        object.addAttribute("cached",QString::number(ramFree));

        // If we got here, then we couldn't find the proper line in the meminfo file:
        // do something appropriate like return an error code, throw an exception, etc.
        fclose(meminfo);
    }

}

// void TasDeviceUtils::tapScreen(int x, int y, int duration)
// {

// }

void TasDeviceUtils::sendMouseEvent(int x, int y, Qt::MouseButton button, QEvent::Type type, uint /*pointerNumber*/)
{
    Display* dpy = 0;
    Window root = None;
    dpy = XOpenDisplay(NULL);
    root = DefaultRootWindow(dpy);
    if (!dpy) {
        TasLogger::logger()->error("TasDeviceUtils::sendMouseEvent No Display detected! Unable to run X commands");
        return;
    }

    int keycode = Button1;
    switch (button) {
    case Qt::LeftButton:
        keycode = Button1;
        break;
    case Qt::MidButton:
        keycode = Button2;
        break;
    case Qt::RightButton:
        keycode = Button3;
        break;
    default:
        break;
    }

    bool down = type == QEvent::MouseButtonPress ||
        type == QEvent::GraphicsSceneMousePress;
    if (down || type == QEvent::MouseMove) { // TODO how about dblclick?
        // Move the Cursor to given coords
        XWarpPointer(dpy, None, root, 0, 0, 0, 0,
                     x,y);
        XFlush(dpy);
    }

    if (type == QEvent::MouseButtonPress ||
        type == QEvent::MouseButtonRelease ||
        type == QEvent::GraphicsSceneMousePress ||
        type == QEvent::GraphicsSceneMouseRelease) {
        XTestFakeButtonEvent(dpy, keycode, down, CurrentTime);
        XFlush(dpy);
    }

    XCloseDisplay(dpy);
}

/*!
  Not implemented, true returned to avoid autostart.
*/
bool TasDeviceUtils::isServerRunning()
{
    return true;
}

int TasDeviceUtils::getOrientation()
{
    int orientation = -1;
#if defined(TAS_MAEMO) && defined(HAVE_QAPP)
    TasLogger::logger()->debug("how about active widget?");

    QWidget* widget = QApplication::activeWindow();
    if (widget) {
        orientation = getOrientationForWidget(widget);
    } else {
        // If the window doesn't any active window, take first one from the list.
        QWidgetList list = QApplication::topLevelWidgets();
        if (!list.isEmpty()) {
            foreach(QWidget* w, list) {
                orientation = getOrientationForWidget(w);
                if (orientation != -1) {
                    break;
                }

            }
        }
    }

    if (orientation == -1) {
        TasLogger::logger()->debug("setting orientation per meegoapp");
        MApplication* app = MApplication::instance();
        if (app) {
            // activeWindow() would SIGABORT if called without verifying the mapp instance
            MWindow *w = MApplication::activeWindow();
            if (w) {
                M::OrientationAngle angle = w->orientationAngle();
                switch(angle) {
                case M::Angle90:
                    orientation = 90;
                    break;
                case M::Angle180:
                    orientation = 180;
                    break;
                case M::Angle270:
                    orientation = 270;
                    break;
                case M::Angle0:
                default:
                    break;
                }
            }
        }
    }
#endif
    return orientation;
}

<commit_msg>More build/compile configs<commit_after>/***************************************************************************
 **
 ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
 ** All rights reserved.
 ** Contact: Nokia Corporation (testabilitydriver@nokia.com)
 **
 ** This file is part of Testability Driver Qt Agent
 **
 ** If you have questions regarding the use of this file, please contact
 ** Nokia at testabilitydriver@nokia.com .
 **
 ** 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
 ** and appearing in the file LICENSE.LGPL included in the packaging
 ** of this file.
 **
 ****************************************************************************/

#include "tasdeviceutils.h"

#if defined(TAS_MAEMO) && defined(HAVE_QAPP)
#include <MApplication>
#include <MWindow>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#endif
#ifdef TAS_MAEMO
#include <qmsystem2/qmdisplaystate.h>
#endif

#include <taslogger.h>
#include <stdlib.h>
#include <sys/resource.h>
#if defined(Q_WS_X11)
#include <X11/Xlib.h>
#include <X11/extensions/XTest.h>
#endif

#include <QEvent>

#if defined(TAS_MAEMO) && defined(HAVE_QAPP)
namespace {
int getOrientationForWidget(QWidget* widget)
{
    Display* display = QX11Info::display();
    Atom orientationAngleAtom = XInternAtom(display,
                                            "_MEEGOTOUCH_ORIENTATION_ANGLE", True);
    int orientation = -1;
    Atom actual_type;
    int actual_format;
    unsigned long nitems;
    unsigned long bytes_after;
    unsigned char *prop = 0;
    int status;
    if (widget && orientationAngleAtom != None) {
        TasLogger::logger()->debug("got widget and orientation angle");
        status = XGetWindowProperty(display, widget->effectiveWinId(),
                                    orientationAngleAtom, 0, 1024,
                                    False, AnyPropertyType,
                                    &actual_type, &actual_format, &nitems,
                                    &bytes_after,
                                    &prop);
        if (status!=0 || !prop || actual_format == None) {
            //NOP
        } else {
            TasLogger::logger()->debug("setting it!");
            orientation = prop[1] * 256;
            orientation += prop[0];
            if (prop) XFree(prop);
            return orientation;
        }
    }
    if (prop) XFree(prop);
    return -1;
}
}
#endif

TasDeviceUtils::TasDeviceUtils()
{
    gpuDetailsHandler = 0;
    pwrDetailsHandler = 0;
}

void TasDeviceUtils::resetInactivity()
{
#ifdef TAS_MAEMO
    TasLogger::logger()->debug("TasDeviceUtils:: resetting inactivity");
    MeeGo::QmDisplayState state;

    if (!state.set(MeeGo::QmDisplayState::On)) {
        TasLogger::logger()->warning("TasDeviceUtils:: setting displaystate failed!");
    }

    if (!state.setBlankingPause()) {
        TasLogger::logger()->warning("TasDeviceUtils:: setBlankingPause failed!");
    }
#endif
}

GpuMemDetails TasDeviceUtils::gpuMemDetails()
{
    GpuMemDetails details;
    details.isValid = false;
    return details;
}

PwrDetails TasDeviceUtils::pwrDetails()
{
    PwrDetails details;
    details.isValid = false;
    return details;
}

void TasDeviceUtils::stopPwrData()
{}

// TODO remove the duplicate code (maemo version)

/*!
  Returns the heap size of the process.
  -1 means not supported.
*/
int TasDeviceUtils::currentProcessHeapSize()
{
    char buf[30];
    unsigned size = -1; //       total program size
    // If needed later.
//    unsigned resident = -1;//   resident set size
//    unsigned share;//      shared pages
//    unsigned text;//       text (code)
//    unsigned lib;//        library
//    unsigned data;//       data/stack
//    unsigned dt;//         dirty pages (unused in Linux 2.6)

    snprintf(buf, 30, "/proc/%u/statm", (unsigned)getpid());
    FILE* pf = fopen(buf, "r");
    if (pf) {
        fscanf(pf, "%u "/* %u %u %u %u %u " */, &size /*,&resident, &share, &text, &lib, &data */);
    }
    fclose(pf);
    return size;
}

/*!
 * /proc/cpuinfo data
 */
void TasDeviceUtils::addSystemInformation(TasObject& object)
{
    QFile file("/proc/cpuinfo");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return;
    }

    TasObject& child = object.addObject();
    child.setName("/proc/cpuinfo");
    QTextStream in(&file);
    QString line = in.readLine();
    while (!line.isNull()) {
        QStringList list = line.split(":");
        if (list.size() == 2) {
            child.addAttribute(list[0].trimmed(),list[1].trimmed());
        }
        line = in.readLine();
    }
}

qreal TasDeviceUtils::currentProcessCpuTime()
{
    return -1;
}

/*!
  Not supported
*/
void TasDeviceUtils::addSystemMemoryStatus(TasObject& object)
{

    FILE *meminfo = fopen("/proc/meminfo", "r");
    int ram = -1;
    int ramFree = -1;
    int cached = -1;

    if(meminfo == NULL) {

    } else {
        char line[256];
        while(fgets(line, sizeof(line), meminfo)) {
            if (ram == -1) {
                sscanf(line, "MemTotal: %d kB", &ram);
            } else if (ramFree == -1) {
                sscanf(line, "MemFree: %d kB", &ramFree);
            } else if (cached == -1) {
                sscanf(line, "Cached: %d kB", &cached);
                break;
            }
        }

        object.addAttribute("total",QString::number(ram));
        object.addAttribute("available",QString::number(ramFree));
        object.addAttribute("cached",QString::number(ramFree));

        // If we got here, then we couldn't find the proper line in the meminfo file:
        // do something appropriate like return an error code, throw an exception, etc.
        fclose(meminfo);
    }

}

// void TasDeviceUtils::tapScreen(int x, int y, int duration)
// {

// }

void TasDeviceUtils::sendMouseEvent(int x, int y, Qt::MouseButton button, QEvent::Type type, uint /*pointerNumber*/)
{
#if defined(Q_WS_X11)
    Display* dpy = 0;
    Window root = None;
    dpy = XOpenDisplay(NULL);
    root = DefaultRootWindow(dpy);
    if (!dpy) {
        TasLogger::logger()->error("TasDeviceUtils::sendMouseEvent No Display detected! Unable to run X commands");
        return;
    }

    int keycode = Button1;
    switch (button) {
    case Qt::LeftButton:
        keycode = Button1;
        break;
    case Qt::MidButton:
        keycode = Button2;
        break;
    case Qt::RightButton:
        keycode = Button3;
        break;
    default:
        break;
    }

    bool down = type == QEvent::MouseButtonPress ||
        type == QEvent::GraphicsSceneMousePress;
    if (down || type == QEvent::MouseMove) { // TODO how about dblclick?
        // Move the Cursor to given coords
        XWarpPointer(dpy, None, root, 0, 0, 0, 0,
                     x,y);
        XFlush(dpy);
    }

    if (type == QEvent::MouseButtonPress ||
        type == QEvent::MouseButtonRelease ||
        type == QEvent::GraphicsSceneMousePress ||
        type == QEvent::GraphicsSceneMouseRelease) {
        XTestFakeButtonEvent(dpy, keycode, down, CurrentTime);
        XFlush(dpy);
    }

    XCloseDisplay(dpy);
#elif defined(TAS_WAYLAND)
#endif
}

/*!
  Not implemented, true returned to avoid autostart.
*/
bool TasDeviceUtils::isServerRunning()
{
    return true;
}

int TasDeviceUtils::getOrientation()
{
    int orientation = -1;
#if defined(TAS_MAEMO) && defined(HAVE_QAPP)
    TasLogger::logger()->debug("how about active widget?");

    QWidget* widget = QApplication::activeWindow();
    if (widget) {
        orientation = getOrientationForWidget(widget);
    } else {
        // If the window doesn't any active window, take first one from the list.
        QWidgetList list = QApplication::topLevelWidgets();
        if (!list.isEmpty()) {
            foreach(QWidget* w, list) {
                orientation = getOrientationForWidget(w);
                if (orientation != -1) {
                    break;
                }

            }
        }
    }

    if (orientation == -1) {
        TasLogger::logger()->debug("setting orientation per meegoapp");
        MApplication* app = MApplication::instance();
        if (app) {
            // activeWindow() would SIGABORT if called without verifying the mapp instance
            MWindow *w = MApplication::activeWindow();
            if (w) {
                M::OrientationAngle angle = w->orientationAngle();
                switch(angle) {
                case M::Angle90:
                    orientation = 90;
                    break;
                case M::Angle180:
                    orientation = 180;
                    break;
                case M::Angle270:
                    orientation = 270;
                    break;
                case M::Angle0:
                default:
                    break;
                }
            }
        }
    }
#endif
    return orientation;
}

<|endoftext|>


<commit_before>// Copyright (c) 2011 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 "chrome/browser/ui/views/tab_contents/native_tab_contents_container_gtk.h"

#include "chrome/browser/ui/view_ids.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_container.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_view_views.h"
#include "content/browser/renderer_host/render_widget_host_view.h"
#include "content/public/browser/interstitial_page.h"
#include "content/public/browser/web_contents.h"
#include "ui/base/accessibility/accessible_view_state.h"
#include "ui/views/focus/focus_manager.h"

using content::WebContents;

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsContainerGtk, public:

NativeTabContentsContainerGtk::NativeTabContentsContainerGtk(
    TabContentsContainer* container)
    : container_(container),
      focus_callback_id_(0) {
  set_id(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW);
}

NativeTabContentsContainerGtk::~NativeTabContentsContainerGtk() {
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsContainerGtk, NativeTabContentsContainer overrides:

void NativeTabContentsContainerGtk::AttachContents(WebContents* contents) {
  Attach(contents->GetNativeView());
}

void NativeTabContentsContainerGtk::DetachContents(WebContents* contents) {
  gtk_widget_hide(contents->GetNativeView());

  // Now detach the TabContents.
  Detach();

  static_cast<TabContentsViewViews*>(contents->GetView())->Unparent();
}

void NativeTabContentsContainerGtk::SetFastResize(bool fast_resize) {
  set_fast_resize(fast_resize);
}

bool NativeTabContentsContainerGtk::GetFastResize() const {
  return fast_resize();
}

bool NativeTabContentsContainerGtk::FastResizeAtLastLayout() const {
  return fast_resize_at_last_layout();
}

void NativeTabContentsContainerGtk::RenderViewHostChanged(
    RenderViewHost* old_host,
    RenderViewHost* new_host) {
  // If we are focused, we need to pass the focus to the new RenderViewHost.
  if (GetFocusManager()->GetFocusedView() == this)
    OnFocus();
}

views::View* NativeTabContentsContainerGtk::GetView() {
  return this;
}

void NativeTabContentsContainerGtk::WebContentsFocused(WebContents* contents) {
  // Called when the tab contents native view gets focused (typically through a
  // user click).  We make ourself the focused view, so the focus is restored
  // properly when the browser window is deactivated/reactivated.
  views::FocusManager* focus_manager = GetFocusManager();
  if (!focus_manager) {
    NOTREACHED();
    return;
  }
  focus_manager->SetFocusedView(this);
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsContainerGtk, views::View overrides:

bool NativeTabContentsContainerGtk::SkipDefaultKeyEventProcessing(
    const views::KeyEvent& e) {
  // Don't look-up accelerators or tab-traverse if we are showing a non-crashed
  // TabContents.
  // We'll first give the page a chance to process the key events.  If it does
  // not process them, they'll be returned to us and we'll treat them as
  // accelerators then.
  return container_->web_contents() &&
         !container_->web_contents()->IsCrashed();
}

views::FocusTraversable* NativeTabContentsContainerGtk::GetFocusTraversable() {
  return NULL;
}

bool NativeTabContentsContainerGtk::IsFocusable() const {
  // We need to be focusable when our contents is not a view hierarchy, as
  // clicking on the contents needs to focus us.
  return container_->web_contents() != NULL;
}

void NativeTabContentsContainerGtk::OnFocus() {
  if (container_->web_contents())
    container_->web_contents()->Focus();
}

void NativeTabContentsContainerGtk::RequestFocus() {
  // This is a hack to circumvent the fact that a view does not explicitly get
  // a call to set the focus if it already has the focus. This causes a problem
  // with tabs such as the TabContents that instruct the RenderView that it got
  // focus when they actually get the focus. When switching from one TabContents
  // tab that has focus to another TabContents tab that had focus, since the
  // TabContentsContainerView already has focus, OnFocus() would not be called
  // and the RenderView would not get notified it got focused.
  // By clearing the focused view before-hand, we ensure OnFocus() will be
  // called.
  views::FocusManager* focus_manager = GetFocusManager();
  if (focus_manager)
    focus_manager->SetFocusedView(NULL);
  View::RequestFocus();
}

void NativeTabContentsContainerGtk::AboutToRequestFocusFromTabTraversal(
    bool reverse) {
  if (!container_->web_contents())
    return;
  // Give an opportunity to the tab to reset its focus.
  if (container_->web_contents()->GetInterstitialPage()) {
    container_->web_contents()->GetInterstitialPage()->FocusThroughTabTraversal(
        reverse);
    return;
  }
  container_->web_contents()->FocusThroughTabTraversal(reverse);
}

void NativeTabContentsContainerGtk::GetAccessibleState(
    ui::AccessibleViewState* state) {
  state->role = ui::AccessibilityTypes::ROLE_GROUPING;
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsContainer, public:

// static
NativeTabContentsContainer* NativeTabContentsContainer::CreateNativeContainer(
    TabContentsContainer* container) {
  return new NativeTabContentsContainerGtk(container);
}
<commit_msg>Fix ChromeOS GTK build failure after r120840. This code was duplicating logic already in WebContents. Review URL: https://chromiumcodereview.appspot.com/9372005<commit_after>// Copyright (c) 2011 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 "chrome/browser/ui/views/tab_contents/native_tab_contents_container_gtk.h"

#include "chrome/browser/ui/view_ids.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_container.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_view_views.h"
#include "content/browser/renderer_host/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "ui/base/accessibility/accessible_view_state.h"
#include "ui/views/focus/focus_manager.h"

using content::WebContents;

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsContainerGtk, public:

NativeTabContentsContainerGtk::NativeTabContentsContainerGtk(
    TabContentsContainer* container)
    : container_(container),
      focus_callback_id_(0) {
  set_id(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW);
}

NativeTabContentsContainerGtk::~NativeTabContentsContainerGtk() {
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsContainerGtk, NativeTabContentsContainer overrides:

void NativeTabContentsContainerGtk::AttachContents(WebContents* contents) {
  Attach(contents->GetNativeView());
}

void NativeTabContentsContainerGtk::DetachContents(WebContents* contents) {
  gtk_widget_hide(contents->GetNativeView());

  // Now detach the TabContents.
  Detach();

  static_cast<TabContentsViewViews*>(contents->GetView())->Unparent();
}

void NativeTabContentsContainerGtk::SetFastResize(bool fast_resize) {
  set_fast_resize(fast_resize);
}

bool NativeTabContentsContainerGtk::GetFastResize() const {
  return fast_resize();
}

bool NativeTabContentsContainerGtk::FastResizeAtLastLayout() const {
  return fast_resize_at_last_layout();
}

void NativeTabContentsContainerGtk::RenderViewHostChanged(
    RenderViewHost* old_host,
    RenderViewHost* new_host) {
  // If we are focused, we need to pass the focus to the new RenderViewHost.
  if (GetFocusManager()->GetFocusedView() == this)
    OnFocus();
}

views::View* NativeTabContentsContainerGtk::GetView() {
  return this;
}

void NativeTabContentsContainerGtk::WebContentsFocused(WebContents* contents) {
  // Called when the tab contents native view gets focused (typically through a
  // user click).  We make ourself the focused view, so the focus is restored
  // properly when the browser window is deactivated/reactivated.
  views::FocusManager* focus_manager = GetFocusManager();
  if (!focus_manager) {
    NOTREACHED();
    return;
  }
  focus_manager->SetFocusedView(this);
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsContainerGtk, views::View overrides:

bool NativeTabContentsContainerGtk::SkipDefaultKeyEventProcessing(
    const views::KeyEvent& e) {
  // Don't look-up accelerators or tab-traverse if we are showing a non-crashed
  // TabContents.
  // We'll first give the page a chance to process the key events.  If it does
  // not process them, they'll be returned to us and we'll treat them as
  // accelerators then.
  return container_->web_contents() &&
         !container_->web_contents()->IsCrashed();
}

views::FocusTraversable* NativeTabContentsContainerGtk::GetFocusTraversable() {
  return NULL;
}

bool NativeTabContentsContainerGtk::IsFocusable() const {
  // We need to be focusable when our contents is not a view hierarchy, as
  // clicking on the contents needs to focus us.
  return container_->web_contents() != NULL;
}

void NativeTabContentsContainerGtk::OnFocus() {
  if (container_->web_contents())
    container_->web_contents()->Focus();
}

void NativeTabContentsContainerGtk::RequestFocus() {
  // This is a hack to circumvent the fact that a view does not explicitly get
  // a call to set the focus if it already has the focus. This causes a problem
  // with tabs such as the TabContents that instruct the RenderView that it got
  // focus when they actually get the focus. When switching from one TabContents
  // tab that has focus to another TabContents tab that had focus, since the
  // TabContentsContainerView already has focus, OnFocus() would not be called
  // and the RenderView would not get notified it got focused.
  // By clearing the focused view before-hand, we ensure OnFocus() will be
  // called.
  views::FocusManager* focus_manager = GetFocusManager();
  if (focus_manager)
    focus_manager->SetFocusedView(NULL);
  View::RequestFocus();
}

void NativeTabContentsContainerGtk::AboutToRequestFocusFromTabTraversal(
    bool reverse) {
  if (!container_->web_contents())
    return;
  container_->web_contents()->FocusThroughTabTraversal(reverse);
}

void NativeTabContentsContainerGtk::GetAccessibleState(
    ui::AccessibleViewState* state) {
  state->role = ui::AccessibilityTypes::ROLE_GROUPING;
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsContainer, public:

// static
NativeTabContentsContainer* NativeTabContentsContainer::CreateNativeContainer(
    TabContentsContainer* container) {
  return new NativeTabContentsContainerGtk(container);
}
<|endoftext|>


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

#include "Helper.h"
#include "ReconstructionData.h"

#include <sstream>

// VTK includes
#include "vtkDoubleArray.h"
#include "vtkImageData.h"
#include "vtkMatrix3x3.h"
#include "vtkMatrix4x4.h"
#include "vtkPointData.h"
#include "vtkSmartPointer.h"
#include "vtkTransform.h"
#include "vtkUnsignedCharArray.h"
#include "vtkXMLImageDataReader.h"

ReconstructionData::ReconstructionData()
{
  this->DepthMap = nullptr;
  this->MatrixK = nullptr;
  this->MatrixTR = nullptr;
}

ReconstructionData::ReconstructionData(std::string depthPath,
                                       std::string matrixPath)
                                       :ReconstructionData()
{
  // Read DEPTH MAP an fill this->DepthMap
  this->DepthMap = vtkImageData::New();
  ReconstructionData::ReadDepthMap(depthPath, this->DepthMap);

  this->TransformWorldToCamera = vtkTransform::New();
  this->TransformCameraToDepthMap = vtkTransform::New();

  // Read KRTD FILE
  vtkNew<vtkMatrix3x3> K;
  vtkNew<vtkMatrix4x4> RT;
  this->MatrixTR = vtkMatrix4x4::New();
  this->MatrixK = vtkMatrix3x3::New();
  this->Matrix4K = vtkMatrix4x4::New();
  help::ReadKrtdFile(matrixPath, K.Get(), RT.Get());

  // Set matrix K to  create matrix4x4 for K
  this->SetMatrixK(K.Get());
  this->SetMatrixTR(RT.Get());
}

ReconstructionData::~ReconstructionData()
{
  if (this->DepthMap)
    this->DepthMap->Delete();
  if (this->MatrixK)
    this->MatrixK->Delete();
  if (this->MatrixTR)
    this->MatrixTR->Delete();
  if (this->Matrix4K)
    this->Matrix4K->Delete();
}

void ReconstructionData::GetColorValue(int* pixelPosition, double rgb[3])
{
  vtkUnsignedCharArray* color =
    vtkUnsignedCharArray::SafeDownCast(this->DepthMap->GetPointData()->GetArray("Color"));

  if (color == nullptr)
    {
    std::cerr << "Error, no 'Color' array exists" << std::endl;
    return;
    }

  int* depthDims = this->DepthMap->GetDimensions();

  int pix[3];
  pix[0] = pixelPosition[0];
  pix[1] = depthDims[1] - 1 - pixelPosition[1];
  pix[2] = 0;

  int id = this->DepthMap->ComputePointId(pix);
  double* temp = color->GetTuple3(id);
  for (size_t i = 0; i < 3; i++)
  {
    rgb[i] = temp[i];
  }
}

vtkImageData* ReconstructionData::GetDepthMap()
{
  return this->DepthMap;
}

vtkMatrix3x3* ReconstructionData::Get3MatrixK()
{
  return this->MatrixK;
}

vtkMatrix4x4* ReconstructionData::Get4MatrixK()
{
  return this->Matrix4K;
}

vtkMatrix4x4* ReconstructionData::GetMatrixTR()
{
  return this->MatrixTR;
}

void ReconstructionData::ApplyDepthThresholdFilter(double thresholdBestCost)
{
  if (this->DepthMap == nullptr)
    return;

  vtkDoubleArray* depths =
    vtkDoubleArray::SafeDownCast(this->DepthMap->GetPointData()->GetArray("Depths"));
  vtkDoubleArray* bestCost =
    vtkDoubleArray::SafeDownCast(this->DepthMap->GetPointData()->GetArray("Best Cost Values"));

  if (depths == nullptr)
    {
    std::cerr << "Error during threshold, depths is empty" << std::endl;
    return;
    }

  int nbTuples = depths->GetNumberOfTuples();

  if (bestCost->GetNumberOfTuples() != nbTuples)
    return;

  for (int i = 0; i < nbTuples; i++)
    {
    double v_bestCost = bestCost->GetTuple1(i);
    if (v_bestCost > thresholdBestCost)
      {
      depths->SetTuple1(i, -1);
      }
    }
}

void ReconstructionData::TransformWorldToDepthMapPosition(const double* worldCoordinate,
                                                          int pixelCoordinate[2])
{
  double cameraCoordinate[3];
  this->TransformWorldToCamera->TransformPoint(worldCoordinate, cameraCoordinate);
  double depthMapCoordinate[3];
  this->TransformCameraToDepthMap->TransformVector(cameraCoordinate, depthMapCoordinate);

  depthMapCoordinate[0] = depthMapCoordinate[0] / depthMapCoordinate[2];
  depthMapCoordinate[1] = depthMapCoordinate[1] / depthMapCoordinate[2];

  pixelCoordinate[0] = std::round(depthMapCoordinate[0]);
  pixelCoordinate[1] = std::round(depthMapCoordinate[1]);
}

void ReconstructionData::SetDepthMap(vtkImageData* data)
{
  if (this->DepthMap != nullptr)
    this->DepthMap->Delete();
  this->DepthMap = data;
  this->DepthMap->Register(0);
}

void ReconstructionData::SetMatrixK(vtkMatrix3x3* matrix)
{
  if (this->MatrixK != nullptr)
    this->MatrixK->Delete();
  this->MatrixK = matrix;
  this->MatrixK->Register(0);

  if (this->Matrix4K != nullptr)
    this->Matrix4K->Delete();
  this->Matrix4K = vtkMatrix4x4::New();
  this->Matrix4K->Identity();
  for (int i = 0; i < 3; i++)
    {
    for (int j = 0; j < 3; j++)
      {
      this->Matrix4K->SetElement(i, j, this->MatrixK->GetElement(i, j));
      }
    }

  this->TransformCameraToDepthMap->SetMatrix(this->Matrix4K);
}

void ReconstructionData::SetMatrixTR(vtkMatrix4x4* matrix)
{
  if (this->MatrixTR != nullptr)
    this->MatrixTR->Delete();
  this->MatrixTR = matrix;
  this->MatrixTR->Register(0);
  this->TransformWorldToCamera->SetMatrix(this->MatrixTR);
}

void ReconstructionData::ReadDepthMap(std::string path, vtkImageData* out)
{
  vtkSmartPointer<vtkXMLImageDataReader> depthMapReader = vtkSmartPointer<vtkXMLImageDataReader>::New();
  depthMapReader->SetFileName(path.c_str());
  depthMapReader->Update();
  out->ShallowCopy(depthMapReader->GetOutput());
}
<commit_msg>added missing include for std::round<commit_after>// Copyright(c) 2016, Kitware SAS
// www.kitware.fr
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met :
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and
// / or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "Helper.h"
#include "ReconstructionData.h"

#include <sstream>
#include <cmath>

// VTK includes
#include "vtkDoubleArray.h"
#include "vtkImageData.h"
#include "vtkMatrix3x3.h"
#include "vtkMatrix4x4.h"
#include "vtkPointData.h"
#include "vtkSmartPointer.h"
#include "vtkTransform.h"
#include "vtkUnsignedCharArray.h"
#include "vtkXMLImageDataReader.h"

ReconstructionData::ReconstructionData()
{
  this->DepthMap = nullptr;
  this->MatrixK = nullptr;
  this->MatrixTR = nullptr;
}

ReconstructionData::ReconstructionData(std::string depthPath,
                                       std::string matrixPath)
                                       :ReconstructionData()
{
  // Read DEPTH MAP an fill this->DepthMap
  this->DepthMap = vtkImageData::New();
  ReconstructionData::ReadDepthMap(depthPath, this->DepthMap);

  this->TransformWorldToCamera = vtkTransform::New();
  this->TransformCameraToDepthMap = vtkTransform::New();

  // Read KRTD FILE
  vtkNew<vtkMatrix3x3> K;
  vtkNew<vtkMatrix4x4> RT;
  this->MatrixTR = vtkMatrix4x4::New();
  this->MatrixK = vtkMatrix3x3::New();
  this->Matrix4K = vtkMatrix4x4::New();
  help::ReadKrtdFile(matrixPath, K.Get(), RT.Get());

  // Set matrix K to  create matrix4x4 for K
  this->SetMatrixK(K.Get());
  this->SetMatrixTR(RT.Get());
}

ReconstructionData::~ReconstructionData()
{
  if (this->DepthMap)
    this->DepthMap->Delete();
  if (this->MatrixK)
    this->MatrixK->Delete();
  if (this->MatrixTR)
    this->MatrixTR->Delete();
  if (this->Matrix4K)
    this->Matrix4K->Delete();
}

void ReconstructionData::GetColorValue(int* pixelPosition, double rgb[3])
{
  vtkUnsignedCharArray* color =
    vtkUnsignedCharArray::SafeDownCast(this->DepthMap->GetPointData()->GetArray("Color"));

  if (color == nullptr)
    {
    std::cerr << "Error, no 'Color' array exists" << std::endl;
    return;
    }

  int* depthDims = this->DepthMap->GetDimensions();

  int pix[3];
  pix[0] = pixelPosition[0];
  pix[1] = depthDims[1] - 1 - pixelPosition[1];
  pix[2] = 0;

  int id = this->DepthMap->ComputePointId(pix);
  double* temp = color->GetTuple3(id);
  for (size_t i = 0; i < 3; i++)
  {
    rgb[i] = temp[i];
  }
}

vtkImageData* ReconstructionData::GetDepthMap()
{
  return this->DepthMap;
}

vtkMatrix3x3* ReconstructionData::Get3MatrixK()
{
  return this->MatrixK;
}

vtkMatrix4x4* ReconstructionData::Get4MatrixK()
{
  return this->Matrix4K;
}

vtkMatrix4x4* ReconstructionData::GetMatrixTR()
{
  return this->MatrixTR;
}

void ReconstructionData::ApplyDepthThresholdFilter(double thresholdBestCost)
{
  if (this->DepthMap == nullptr)
    return;

  vtkDoubleArray* depths =
    vtkDoubleArray::SafeDownCast(this->DepthMap->GetPointData()->GetArray("Depths"));
  vtkDoubleArray* bestCost =
    vtkDoubleArray::SafeDownCast(this->DepthMap->GetPointData()->GetArray("Best Cost Values"));

  if (depths == nullptr)
    {
    std::cerr << "Error during threshold, depths is empty" << std::endl;
    return;
    }

  int nbTuples = depths->GetNumberOfTuples();

  if (bestCost->GetNumberOfTuples() != nbTuples)
    return;

  for (int i = 0; i < nbTuples; i++)
    {
    double v_bestCost = bestCost->GetTuple1(i);
    if (v_bestCost > thresholdBestCost)
      {
      depths->SetTuple1(i, -1);
      }
    }
}

void ReconstructionData::TransformWorldToDepthMapPosition(const double* worldCoordinate,
                                                          int pixelCoordinate[2])
{
  double cameraCoordinate[3];
  this->TransformWorldToCamera->TransformPoint(worldCoordinate, cameraCoordinate);
  double depthMapCoordinate[3];
  this->TransformCameraToDepthMap->TransformVector(cameraCoordinate, depthMapCoordinate);

  depthMapCoordinate[0] = depthMapCoordinate[0] / depthMapCoordinate[2];
  depthMapCoordinate[1] = depthMapCoordinate[1] / depthMapCoordinate[2];

  pixelCoordinate[0] = std::round(depthMapCoordinate[0]);
  pixelCoordinate[1] = std::round(depthMapCoordinate[1]);
}

void ReconstructionData::SetDepthMap(vtkImageData* data)
{
  if (this->DepthMap != nullptr)
    this->DepthMap->Delete();
  this->DepthMap = data;
  this->DepthMap->Register(0);
}

void ReconstructionData::SetMatrixK(vtkMatrix3x3* matrix)
{
  if (this->MatrixK != nullptr)
    this->MatrixK->Delete();
  this->MatrixK = matrix;
  this->MatrixK->Register(0);

  if (this->Matrix4K != nullptr)
    this->Matrix4K->Delete();
  this->Matrix4K = vtkMatrix4x4::New();
  this->Matrix4K->Identity();
  for (int i = 0; i < 3; i++)
    {
    for (int j = 0; j < 3; j++)
      {
      this->Matrix4K->SetElement(i, j, this->MatrixK->GetElement(i, j));
      }
    }

  this->TransformCameraToDepthMap->SetMatrix(this->Matrix4K);
}

void ReconstructionData::SetMatrixTR(vtkMatrix4x4* matrix)
{
  if (this->MatrixTR != nullptr)
    this->MatrixTR->Delete();
  this->MatrixTR = matrix;
  this->MatrixTR->Register(0);
  this->TransformWorldToCamera->SetMatrix(this->MatrixTR);
}

void ReconstructionData::ReadDepthMap(std::string path, vtkImageData* out)
{
  vtkSmartPointer<vtkXMLImageDataReader> depthMapReader = vtkSmartPointer<vtkXMLImageDataReader>::New();
  depthMapReader->SetFileName(path.c_str());
  depthMapReader->Update();
  out->ShallowCopy(depthMapReader->GetOutput());
}
<|endoftext|>


<commit_before>#include <cassert>
#include <iostream>
#include <fstream>

#include <string>
#include <map>
#include "Renamer.h"
#include "ClassFile.h"

using namespace std;

map<string, string> classRemap;
map<SourceId, string> memberRemap;

namespace
{
string getString(ClassFile const& class_, int index)
{
  return class_.const_pool[index].utf8;
}

void replaceAll(std::string& str, const std::string& from, const std::string& to)
{
  if(from.empty())
    return;

  size_t i = 0;

  while((i = str.find(from, i)) != std::string::npos)
  {
    str.replace(i, from.length(), to);
    i += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
  }
}

void remapDescriptorQuickAndDirty(ConstPoolInfo& desc)
{
  assert(desc.tag == CONSTANT::Utf8);

  for(auto& remapping : classRemap)
  {
    auto const from = "L" + remapping.first + ";";
    auto const to = "L" + remapping.second + ";";
    replaceAll(desc.utf8, from, to);
  }
}

void remapFieldDescriptor(ConstPoolInfo& desc)
{
  assert(desc.tag == CONSTANT::Utf8);

  if(desc.utf8[0] == 'L')
  {
    assert(desc.utf8.back() == ';');

    auto const origClassName = desc.utf8.substr(1, desc.utf8.size() - 2);
    auto i_newName = classRemap.find(origClassName);

    if(i_newName != classRemap.end())
      desc.utf8 = "L" + i_newName->second + ";";
  }
}

int addUtf8(ClassFile& class_, string text)
{
  auto const idx = (int)class_.const_pool.size();
  class_.const_pool_count++;
  class_.const_pool.push_back({ CONSTANT::Utf8, {}, text });
  return idx;
}

void renameClasses(ClassFile& class_)
{
  for(auto& constant : class_.const_pool)
  {
    if(constant.tag == CONSTANT::Class)
    {
      auto& classNameEntry = class_.const_pool[constant.name_index];

      auto const& origClassName = classNameEntry.utf8;
      auto i_newName = classRemap.find(origClassName);

      if(i_newName != classRemap.end())
        constant.name_index = addUtf8(class_, i_newName->second);
    }
    else if(constant.tag == CONSTANT::NameAndType)
    {
      auto& typeNameEntry = class_.const_pool[constant.descriptor_index];
      remapDescriptorQuickAndDirty(typeNameEntry);
    }
  }

  for(auto& field : class_.fields)
  {
    auto& desc = class_.const_pool[field.descriptor_index];
    remapFieldDescriptor(desc);
  }

  // rename class names in method signatures
  for(auto& method : class_.methods)
  {
    auto& desc = class_.const_pool[method.descriptor_index];
    remapDescriptorQuickAndDirty(desc);
  }
}

void renameFields(ClassFile& class_, map<SourceId, string> const& remap)
{
  // the fields I'm referring to as a class file
  for(auto& constant : class_.const_pool)
  {
    if(constant.tag == CONSTANT::Fieldref)
    {
      auto const& className = getString(class_, class_.const_pool[constant.class_index].name_index);
      auto& nameAndType = class_.const_pool[constant.name_and_type_index];
      auto const& origName = getString(class_, nameAndType.name_index);

      auto i_newName = remap.find({ false, className, origName });

      if(i_newName != remap.end())
        nameAndType.name_index = addUtf8(class_, i_newName->second);
    }
  }

  // the fields I'm declaring as a class file
  for(auto& field : class_.fields)
  {
    auto const& className = getString(class_, class_.const_pool[class_.this_class].name_index);
    auto const& origName = getString(class_, field.name_index);

    auto i_newName = remap.find({ false, className, origName });

    if(i_newName != remap.end())
      field.name_index = addUtf8(class_, i_newName->second);
  }
}

void renameMethods(ClassFile& class_, map<SourceId, string> const& remap)
{
  // the methods I'm referring to as a class file
  for(auto& constant : class_.const_pool)
  {
    if(constant.tag == CONSTANT::Methodref)
    {
      auto const& className = getString(class_, class_.const_pool[constant.class_index].name_index);
      auto& nameAndType = class_.const_pool[constant.name_and_type_index];
      auto const& origName = getString(class_, nameAndType.name_index);

      auto i_newName = remap.find({ true, className, origName });

      if(i_newName != remap.end())
        nameAndType.name_index = addUtf8(class_, i_newName->second);
    }
  }

  // the methods I'm declaring as a class file
  for(auto& method : class_.methods)
  {
    auto const& className = getString(class_, class_.const_pool[class_.this_class].name_index);
    auto const& fieldOrigName = getString(class_, method.name_index);

    auto i_newName = remap.find({ true, className, fieldOrigName });

    if(i_newName != remap.end())
      method.name_index = addUtf8(class_, i_newName->second);
  }
}
}

void doRenamings(ClassFile& class_)
{
  // HACK: avoid array re-allocation when adding new utf8 descriptors
  class_.const_pool.reserve(class_.const_pool.size() * 4);

  renameClasses(class_);
  renameFields(class_, memberRemap);
  renameMethods(class_, memberRemap);

  class_.const_pool.shrink_to_fit();
}

<commit_msg>Factorize renameFields and renameMethods to 'renameMembers'<commit_after>#include <cassert>
#include <iostream>
#include <fstream>

#include <string>
#include <map>
#include "Renamer.h"
#include "ClassFile.h"

using namespace std;

map<string, string> classRemap;
map<SourceId, string> memberRemap;

namespace
{
string getString(ClassFile const& class_, int index)
{
  return class_.const_pool[index].utf8;
}

void replaceAll(std::string& str, const std::string& from, const std::string& to)
{
  if(from.empty())
    return;

  size_t i = 0;

  while((i = str.find(from, i)) != std::string::npos)
  {
    str.replace(i, from.length(), to);
    i += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
  }
}

void remapDescriptorQuickAndDirty(ConstPoolInfo& desc)
{
  assert(desc.tag == CONSTANT::Utf8);

  for(auto& remapping : classRemap)
  {
    auto const from = "L" + remapping.first + ";";
    auto const to = "L" + remapping.second + ";";
    replaceAll(desc.utf8, from, to);
  }
}

void remapFieldDescriptor(ConstPoolInfo& desc)
{
  assert(desc.tag == CONSTANT::Utf8);

  if(desc.utf8[0] == 'L')
  {
    assert(desc.utf8.back() == ';');

    auto const origClassName = desc.utf8.substr(1, desc.utf8.size() - 2);
    auto i_newName = classRemap.find(origClassName);

    if(i_newName != classRemap.end())
      desc.utf8 = "L" + i_newName->second + ";";
  }
}

int addUtf8(ClassFile& class_, string text)
{
  auto const idx = (int)class_.const_pool.size();
  class_.const_pool_count++;
  class_.const_pool.push_back({ CONSTANT::Utf8, {}, text });
  return idx;
}

void renameClasses(ClassFile& class_)
{
  for(auto& constant : class_.const_pool)
  {
    if(constant.tag == CONSTANT::Class)
    {
      auto& classNameEntry = class_.const_pool[constant.name_index];

      auto const& origClassName = classNameEntry.utf8;
      auto i_newName = classRemap.find(origClassName);

      if(i_newName != classRemap.end())
        constant.name_index = addUtf8(class_, i_newName->second);
    }
    else if(constant.tag == CONSTANT::NameAndType)
    {
      auto& typeNameEntry = class_.const_pool[constant.descriptor_index];
      remapDescriptorQuickAndDirty(typeNameEntry);
    }
  }

  for(auto& field : class_.fields)
  {
    auto& desc = class_.const_pool[field.descriptor_index];
    remapFieldDescriptor(desc);
  }

  // rename class names in method signatures
  for(auto& method : class_.methods)
  {
    auto& desc = class_.const_pool[method.descriptor_index];
    remapDescriptorQuickAndDirty(desc);
  }
}

void renameMembers(ClassFile& class_, map<SourceId, string> const& remap)
{
  // the other class members I'm referring to
  for(auto& constant : class_.const_pool)
  {
    if(constant.tag == CONSTANT::Fieldref || constant.tag == CONSTANT::Methodref)
    {
      auto const isMethod = constant.tag == CONSTANT::Methodref;
      auto const& className = getString(class_, class_.const_pool[constant.class_index].name_index);
      auto& nameAndType = class_.const_pool[constant.name_and_type_index];
      auto const& origName = getString(class_, nameAndType.name_index);

      auto i_newName = remap.find({ isMethod, className, origName });

      if(i_newName != remap.end())
        nameAndType.name_index = addUtf8(class_, i_newName->second);
    }
  }

  // the members I'm declaring
  for(auto& field : class_.fields)
  {
    auto const& className = getString(class_, class_.const_pool[class_.this_class].name_index);
    auto const& origName = getString(class_, field.name_index);

    auto i_newName = remap.find({ false, className, origName });

    if(i_newName != remap.end())
      field.name_index = addUtf8(class_, i_newName->second);
  }

  for(auto& method : class_.methods)
  {
    auto const& className = getString(class_, class_.const_pool[class_.this_class].name_index);
    auto const& fieldOrigName = getString(class_, method.name_index);

    auto i_newName = remap.find({ true, className, fieldOrigName });

    if(i_newName != remap.end())
      method.name_index = addUtf8(class_, i_newName->second);
  }
}
}

void doRenamings(ClassFile& class_)
{
  // HACK: avoid array re-allocation when adding new utf8 descriptors
  class_.const_pool.reserve(class_.const_pool.size() * 4);

  renameClasses(class_);
  renameMembers(class_, memberRemap);

  class_.const_pool.shrink_to_fit();
}

<|endoftext|>


<commit_before>/*
 +----------------------------------------------------------------------+
 | PHP-OpenCV                                                           |
 +----------------------------------------------------------------------+
 | This source file is subject to version 2.0 of the Apache license,    |
 | that is bundled with this package in the file LICENSE, and is        |
 | available through the world-wide-web at the following url:           |
 | http://www.apache.org/licenses/LICENSE-2.0.html                      |
 | If you did not receive a copy of the Apache2.0 license and are unable|
 | to obtain it through the world-wide-web, please send a note to       |
 | hihozhou@gmail.com so we can mail you a copy immediately.            |
 +----------------------------------------------------------------------+
 | Author: HaiHao Zhou  <hihozhou@gmail.com>                            |
 +----------------------------------------------------------------------+
 */

/* $Id$ */

extern "C" {
	#ifdef HAVE_CONFIG_H
	#include "config.h"
	#endif

	#include "php.h"
	#include "php_ini.h"
	#include "ext/standard/info.h"
}
#include "php_opencv.h"
#include "source/opencv2/opencv_imgcodecs.h"
#include "source/opencv2/opencv_highgui.h"
#include "source/opencv2/opencv_imgproc.h"
#include "source/opencv2/core/opencv_type.h"
#include "source/opencv2/core/opencv_mat.h"
#include "source/opencv2/core/hal/opencv_interface.h"
#include "opencv_exception.h"
#include "source/opencv2/opencv_core.h"
#include "source/opencv2/core/opencv_base.h"
#include "source/opencv2/core/opencv_persistence.h"
#include "source/opencv2/opencv_objdetect.h"
#include "source/opencv2/opencv_videoio.h"
#include "source/opencv2/opencv_face.h"

/* If you declare any globals in php_opencv.h uncomment this:
ZEND_DECLARE_MODULE_GLOBALS(opencv)
*/

/* True global resources - no need for thread safety here */
static int le_opencv;

/* {{{ PHP_INI
 */
/* Remove comments and fill if you need to have entries in php.ini
PHP_INI_BEGIN()
    STD_PHP_INI_ENTRY("opencv.global_value",      "42", PHP_INI_ALL, OnUpdateLong, global_value, zend_opencv_globals, opencv_globals)
    STD_PHP_INI_ENTRY("opencv.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_opencv_globals, opencv_globals)
PHP_INI_END()
*/
/* }}} */

/* Remove the following function when you have successfully modified config.m4
   so that your module can be compiled into PHP, it exists only for testing
   purposes. */

/* Every user-visible function in PHP should document itself in the source */
/* {{{ proto string confirm_opencv_compiled(string arg)
   Return a string to confirm that the module is compiled in */
PHP_FUNCTION(confirm_opencv_compiled)
{
    char *arg = NULL;
	size_t arg_len, len;
	zend_string *strg;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &arg, &arg_len) == FAILURE) {
		return;
	}

	strg = strpprintf(0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "opencv", arg);

	RETURN_STR(strg);
}

/* }}} */
/* The previous line is meant for vim and emacs, so it can correctly fold and
   unfold functions in source code. See the corresponding marks just before
   function definition, where the functions purpose is also documented. Please
   follow this convention for the convenience of others editing your code.
*/

/* {{{ php_opencv_init_globals
 */
/* Uncomment this function if you have INI entries
static void php_opencv_init_globals(zend_opencv_globals *opencv_globals)
{
	opencv_globals->global_value = 0;
	opencv_globals->global_string = NULL;
}
*/
/* }}} */

/* {{{ PHP_MINIT_FUNCTION
 */
PHP_MINIT_FUNCTION(opencv)
{
	/* If you have INI entries, uncomment these lines
	REGISTER_INI_ENTRIES();
	*/
    opencv_interface_init(module_number);
    opencv_imgcodecs_init(module_number);
    opencv_highgui_init(module_number);
    opencv_exception_init();
    opencv_mat_init();
    opencv_type_init(module_number);
    opencv_imgproc_init(module_number);
	opencv_core_init(module_number);
    opencv_border_types_init(module_number);
	opencv_file_storage_init(module_number);
	opencv_objdetect_init(module_number);
	opencv_videoio_init(module_number);
    opencv_face_init(module_number);

	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MSHUTDOWN_FUNCTION
 */
PHP_MSHUTDOWN_FUNCTION(opencv)
{
	/* uncomment this line if you have INI entries
	UNREGISTER_INI_ENTRIES();
	*/
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
 */
PHP_RINIT_FUNCTION(opencv)
{
#if defined(COMPILE_DL_OPENCV) && defined(ZTS)
	ZEND_TSRMLS_CACHE_UPDATE();
#endif
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
 */
PHP_RSHUTDOWN_FUNCTION(opencv)
{
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MINFO_FUNCTION
 */
PHP_MINFO_FUNCTION(opencv)
{
	php_info_print_table_start();
	php_info_print_table_header(2, "opencv support", "enabled");
	php_info_print_table_end();

	/* Remove comments if you have entries in php.ini
	DISPLAY_INI_ENTRIES();
	*/
}
/* }}} */

/* {{{ opencv_functions[]
 *
 * Every user visible function must have an entry in opencv_functions[].
 */
const zend_function_entry opencv_functions[] = {
	PHP_FE(confirm_opencv_compiled,	NULL)		/* For testing, remove later. */
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_8UC, ZEND_FN(opencv_cv_8uc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_8SC, ZEND_FN(opencv_cv_8sc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_16UC, ZEND_FN(opencv_cv_16uc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_16SC, ZEND_FN(opencv_cv_16sc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_32SC, ZEND_FN(opencv_cv_32sc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_32FC, ZEND_FN(opencv_cv_32fc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_64FC, ZEND_FN(opencv_cv_64fc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, imread, ZEND_FN(opencv_imread), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, imwrite, ZEND_FN(opencv_imwrite), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, imshow, ZEND_FN(opencv_imshow), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, waitKey, ZEND_FN(opencv_wait_key), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, namedWindow, ZEND_FN(opencv_named_window), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, cvtColor, ZEND_FN(opencv_cv_t_color), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, ellipse, ZEND_FN(opencv_ellipse), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, circle, ZEND_FN(opencv_circle), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, line, ZEND_FN(opencv_line), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, rectangle, ZEND_FN(opencv_rectangle), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, rectangleByPoint, ZEND_FN(opencv_rectangle_by_point), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, rectangleByRect, ZEND_FN(opencv_rectangle_by_rect), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, addWeighted, ZEND_FN(opencv_add_weighted), opencv_add_weighted_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, split, ZEND_FN(opencv_split), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, merge, ZEND_FN(opencv_merge), opencv_merge_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, createTrackbar, ZEND_FN(opencv_create_trackbar), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, destroyWindow, ZEND_FN(opencv_destroy_window), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, getOptimalDFTSize, ZEND_FN(opencv_get_optimal_dft_size), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, copyMakeBorder, ZEND_FN(opencv_copy_make_border), opencv_copy_make_border_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, dft, ZEND_FN(opencv_dft), opencv_dft_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, magnitude, ZEND_FN(opencv_magnitude), opencv_magnitude_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, add, ZEND_FN(opencv_add), opencv_add_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, log, ZEND_FN(opencv_log), opencv_log_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, normalize, ZEND_FN(opencv_normalize), opencv_normalize_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, equalizeHist, ZEND_FN(opencv_equalize_hist), opencv_equalize_hist_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, resize, ZEND_FN(opencv_resize), opencv_resize_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, putText, ZEND_FN(opencv_put_text), NULL)
	PHP_FE_END	/* Must be the last line in opencv_functions[] */
};
/* }}} */

/* {{{ opencv_module_entry
 */
zend_module_entry opencv_module_entry = {
	STANDARD_MODULE_HEADER,
	"opencv",
	opencv_functions,
	PHP_MINIT(opencv),
	PHP_MSHUTDOWN(opencv),
	PHP_RINIT(opencv),		/* Replace with NULL if there's nothing to do at request start */
	PHP_RSHUTDOWN(opencv),	/* Replace with NULL if there's nothing to do at request end */
	PHP_MINFO(opencv),
	PHP_OPENCV_VERSION,
	STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_OPENCV
#ifdef ZTS
ZEND_TSRMLS_CACHE_DEFINE()
#endif
ZEND_GET_MODULE(opencv)
#endif

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */
<commit_msg>添加opencv_absdiff<commit_after>/*
 +----------------------------------------------------------------------+
 | PHP-OpenCV                                                           |
 +----------------------------------------------------------------------+
 | This source file is subject to version 2.0 of the Apache license,    |
 | that is bundled with this package in the file LICENSE, and is        |
 | available through the world-wide-web at the following url:           |
 | http://www.apache.org/licenses/LICENSE-2.0.html                      |
 | If you did not receive a copy of the Apache2.0 license and are unable|
 | to obtain it through the world-wide-web, please send a note to       |
 | hihozhou@gmail.com so we can mail you a copy immediately.            |
 +----------------------------------------------------------------------+
 | Author: HaiHao Zhou  <hihozhou@gmail.com>                            |
 +----------------------------------------------------------------------+
 */

/* $Id$ */

extern "C" {
	#ifdef HAVE_CONFIG_H
	#include "config.h"
	#endif

	#include "php.h"
	#include "php_ini.h"
	#include "ext/standard/info.h"
}
#include "php_opencv.h"
#include "source/opencv2/opencv_imgcodecs.h"
#include "source/opencv2/opencv_highgui.h"
#include "source/opencv2/opencv_imgproc.h"
#include "source/opencv2/core/opencv_type.h"
#include "source/opencv2/core/opencv_mat.h"
#include "source/opencv2/core/hal/opencv_interface.h"
#include "opencv_exception.h"
#include "source/opencv2/opencv_core.h"
#include "source/opencv2/core/opencv_base.h"
#include "source/opencv2/core/opencv_persistence.h"
#include "source/opencv2/opencv_objdetect.h"
#include "source/opencv2/opencv_videoio.h"
#include "source/opencv2/opencv_face.h"

/* If you declare any globals in php_opencv.h uncomment this:
ZEND_DECLARE_MODULE_GLOBALS(opencv)
*/

/* True global resources - no need for thread safety here */
static int le_opencv;

/* {{{ PHP_INI
 */
/* Remove comments and fill if you need to have entries in php.ini
PHP_INI_BEGIN()
    STD_PHP_INI_ENTRY("opencv.global_value",      "42", PHP_INI_ALL, OnUpdateLong, global_value, zend_opencv_globals, opencv_globals)
    STD_PHP_INI_ENTRY("opencv.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_opencv_globals, opencv_globals)
PHP_INI_END()
*/
/* }}} */

/* Remove the following function when you have successfully modified config.m4
   so that your module can be compiled into PHP, it exists only for testing
   purposes. */

/* Every user-visible function in PHP should document itself in the source */
/* {{{ proto string confirm_opencv_compiled(string arg)
   Return a string to confirm that the module is compiled in */
PHP_FUNCTION(confirm_opencv_compiled)
{
    char *arg = NULL;
	size_t arg_len, len;
	zend_string *strg;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &arg, &arg_len) == FAILURE) {
		return;
	}

	strg = strpprintf(0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "opencv", arg);

	RETURN_STR(strg);
}

/* }}} */
/* The previous line is meant for vim and emacs, so it can correctly fold and
   unfold functions in source code. See the corresponding marks just before
   function definition, where the functions purpose is also documented. Please
   follow this convention for the convenience of others editing your code.
*/

/* {{{ php_opencv_init_globals
 */
/* Uncomment this function if you have INI entries
static void php_opencv_init_globals(zend_opencv_globals *opencv_globals)
{
	opencv_globals->global_value = 0;
	opencv_globals->global_string = NULL;
}
*/
/* }}} */

/* {{{ PHP_MINIT_FUNCTION
 */
PHP_MINIT_FUNCTION(opencv)
{
	/* If you have INI entries, uncomment these lines
	REGISTER_INI_ENTRIES();
	*/
    opencv_interface_init(module_number);
    opencv_imgcodecs_init(module_number);
    opencv_highgui_init(module_number);
    opencv_exception_init();
    opencv_mat_init();
    opencv_type_init(module_number);
    opencv_imgproc_init(module_number);
	opencv_core_init(module_number);
    opencv_border_types_init(module_number);
	opencv_file_storage_init(module_number);
	opencv_objdetect_init(module_number);
	opencv_videoio_init(module_number);
    opencv_face_init(module_number);

	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MSHUTDOWN_FUNCTION
 */
PHP_MSHUTDOWN_FUNCTION(opencv)
{
	/* uncomment this line if you have INI entries
	UNREGISTER_INI_ENTRIES();
	*/
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
 */
PHP_RINIT_FUNCTION(opencv)
{
#if defined(COMPILE_DL_OPENCV) && defined(ZTS)
	ZEND_TSRMLS_CACHE_UPDATE();
#endif
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
 */
PHP_RSHUTDOWN_FUNCTION(opencv)
{
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MINFO_FUNCTION
 */
PHP_MINFO_FUNCTION(opencv)
{
	php_info_print_table_start();
	php_info_print_table_header(2, "opencv support", "enabled");
	php_info_print_table_end();

	/* Remove comments if you have entries in php.ini
	DISPLAY_INI_ENTRIES();
	*/
}
/* }}} */

/* {{{ opencv_functions[]
 *
 * Every user visible function must have an entry in opencv_functions[].
 */
const zend_function_entry opencv_functions[] = {
	PHP_FE(confirm_opencv_compiled,	NULL)		/* For testing, remove later. */
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_8UC, ZEND_FN(opencv_cv_8uc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_8SC, ZEND_FN(opencv_cv_8sc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_16UC, ZEND_FN(opencv_cv_16uc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_16SC, ZEND_FN(opencv_cv_16sc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_32SC, ZEND_FN(opencv_cv_32sc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_32FC, ZEND_FN(opencv_cv_32fc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_64FC, ZEND_FN(opencv_cv_64fc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, imread, ZEND_FN(opencv_imread), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, imwrite, ZEND_FN(opencv_imwrite), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, imshow, ZEND_FN(opencv_imshow), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, waitKey, ZEND_FN(opencv_wait_key), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, namedWindow, ZEND_FN(opencv_named_window), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, cvtColor, ZEND_FN(opencv_cv_t_color), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, ellipse, ZEND_FN(opencv_ellipse), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, circle, ZEND_FN(opencv_circle), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, line, ZEND_FN(opencv_line), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, rectangle, ZEND_FN(opencv_rectangle), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, rectangleByPoint, ZEND_FN(opencv_rectangle_by_point), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, rectangleByRect, ZEND_FN(opencv_rectangle_by_rect), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, addWeighted, ZEND_FN(opencv_add_weighted), opencv_add_weighted_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, split, ZEND_FN(opencv_split), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, merge, ZEND_FN(opencv_merge), opencv_merge_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, createTrackbar, ZEND_FN(opencv_create_trackbar), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, destroyWindow, ZEND_FN(opencv_destroy_window), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, getOptimalDFTSize, ZEND_FN(opencv_get_optimal_dft_size), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, copyMakeBorder, ZEND_FN(opencv_copy_make_border), opencv_copy_make_border_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, dft, ZEND_FN(opencv_dft), opencv_dft_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, magnitude, ZEND_FN(opencv_magnitude), opencv_magnitude_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, add, ZEND_FN(opencv_add), opencv_add_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, log, ZEND_FN(opencv_log), opencv_log_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, normalize, ZEND_FN(opencv_normalize), opencv_normalize_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, equalizeHist, ZEND_FN(opencv_equalize_hist), opencv_equalize_hist_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, resize, ZEND_FN(opencv_resize), opencv_resize_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, putText, ZEND_FN(opencv_put_text), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, absdiff, ZEND_FN(opencv_absdiff), opencv_absdiff_arginfo)
	PHP_FE_END	/* Must be the last line in opencv_functions[] */
};
/* }}} */

/* {{{ opencv_module_entry
 */
zend_module_entry opencv_module_entry = {
	STANDARD_MODULE_HEADER,
	"opencv",
	opencv_functions,
	PHP_MINIT(opencv),
	PHP_MSHUTDOWN(opencv),
	PHP_RINIT(opencv),		/* Replace with NULL if there's nothing to do at request start */
	PHP_RSHUTDOWN(opencv),	/* Replace with NULL if there's nothing to do at request end */
	PHP_MINFO(opencv),
	PHP_OPENCV_VERSION,
	STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_OPENCV
#ifdef ZTS
ZEND_TSRMLS_CACHE_DEFINE()
#endif
ZEND_GET_MODULE(opencv)
#endif

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */
<|endoftext|>


<commit_before>//
// jemalloc_example.cpp
//

#include "jemalloc_example.h"
#include "jemalloc/jemalloc.h"

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char * argv[])
{
    void *p;
    printf("Hello world!\n\n");

    // If you use jemalloc through the static lib,
    // must be manual initialize jemalloc first.
    je_init();

    p = (void *)je_malloc(128);
    if (p) {
        printf("malloc(%u) result ptr = 0x%016"PRIXPTR"\n\n", 128, p);
        je_free(p);
    }

    p = (void *)je_malloc(256);
    if (p) {
        printf("malloc(%u) result ptr = 0x%016"PRIXPTR"\n\n", 256, p);
        je_free(p);
    }

    // Unload the jemalloc
    je_uninit();

    system("pause");
	return 0;
}
<commit_msg>warning C4477: 'printf' : format string '%016llX' requires an argument of type 'unsigned __int64', but variadic argument 2 has type 'void *'<commit_after>//
// jemalloc_example.cpp
//

#include "jemalloc_example.h"
#include "jemalloc/jemalloc.h"

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char * argv[])
{
    void *p;
    printf("Hello world!\n\n");

    // If you use jemalloc through the static lib,
    // must be manual initialize jemalloc first.
    je_init();

    p = (void *)je_malloc(128);
    if (p) {
        printf("malloc(%u) result ptr = 0x%p\n\n", 128, p);
        je_free(p);
    }

    p = (void *)je_malloc(256);
    if (p) {
        printf("malloc(%u) result ptr = 0x%p\n\n", 256, p);
        je_free(p);
    }

    // Unload the jemalloc
    je_uninit();

    system("pause");
	return 0;
}
<|endoftext|>


<commit_before>//
// Implements the following classes:
//
// AutoDialog - An improvement to wxDialog which makes validation easier.
//
// AutoPanel - An improvement to wxPanel which makes validation easier.
//
// wxNumericValidator - A validator capable of transfering numeric values.
//
// Copyright (c) 2001-2007 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#include "wx/wxprec.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "vtdata/vtString.h"
#include "AutoDialog.h"

/////////////////////////////////////////////////
//

wxNumericValidator::wxNumericValidator(short *val) : wxValidator()
{
	Initialize();
	m_pValShort = val;
}

wxNumericValidator::wxNumericValidator(int *val) : wxValidator()
{
	Initialize();
	m_pValInt = val;
}

wxNumericValidator::wxNumericValidator(float *val, int digits) : wxValidator()
{
	Initialize();
	m_pValFloat = val;
	m_iDigits = digits;
}

wxNumericValidator::wxNumericValidator(double *val, int digits) : wxValidator()
{
	Initialize();
	m_pValDouble = val;
	m_iDigits = digits;
}

wxNumericValidator::wxNumericValidator(const wxNumericValidator& val)
{
	Initialize();
	Copy(val);
}

/*
  Called by constructors to initialize ALL data members
*/
void wxNumericValidator::Initialize()
{
	m_pValShort = NULL;
	m_pValInt = NULL;
	m_pValFloat = NULL;
	m_pValDouble = NULL;
	m_iDigits = 0;
	m_bEnabled = true;
}

bool wxNumericValidator::Copy(const wxNumericValidator& val)
{
	wxValidator::Copy(val);

	m_pValShort = val.m_pValShort;
	m_pValInt = val.m_pValInt;
	m_pValFloat = val.m_pValFloat;
	m_pValDouble = val.m_pValDouble;
	m_iDigits = val.m_iDigits;

	return true;
}

// Called to transfer data to the window
bool wxNumericValidator::TransferToWindow()
{
	if ( !m_validatorWindow )
		return false;

	if ( !m_bEnabled )
		return true;

	// Compare existing string to new string; don't update unless the actual
	//  numeric value has changed.
	wxString OldString;
	if (m_validatorWindow->IsKindOf(CLASSINFO(wxStaticText)) )
	{
		wxStaticText* pControl = (wxStaticText*) m_validatorWindow;
		if (pControl)
			OldString = pControl->GetLabel() ;
	}
	else if (m_validatorWindow->IsKindOf(CLASSINFO(wxTextCtrl)) )
	{
		wxTextCtrl* pControl = (wxTextCtrl*) m_validatorWindow;
		if (pControl)
			OldString = pControl->GetValue() ;
	}
	else
		return false;

	wxString str, format;
	long OldIntValue;
	double OldDoubleValue;
	if (m_pValShort)
	{
		OldString.ToLong(&OldIntValue);
		if (OldIntValue == (long)*m_pValShort)
			return true;

		str.Printf(_T("%d"), *m_pValShort);
	}
	else if (m_pValInt)
	{
		OldString.ToLong(&OldIntValue);
		if (OldIntValue == (long)*m_pValInt)
			return true;

		str.Printf(_T("%d"), *m_pValInt);
	}
	else if (m_pValFloat)
	{
		OldString.ToDouble(&OldDoubleValue);
		if (OldDoubleValue == (double)*m_pValFloat)
			return true;

		if (m_iDigits != -1)
		{
			format.Printf(_T("%%.%df"), m_iDigits);
			str.Printf(format, *m_pValFloat);
		}
		else
			str.Printf(_T("%.8g"), *m_pValFloat);	// 8 significant digits
	}
	else if (m_pValDouble)
	{
		OldString.ToDouble(&OldDoubleValue);
		if (OldDoubleValue == *m_pValDouble)
			return true;

		if (m_iDigits != -1)
		{
			format.Printf(_T("%%.%dlf"), m_iDigits);
			str.Printf(format, *m_pValDouble);
		}
		else
			str.Printf(_T("%.16lg"), *m_pValDouble);	// 16 significant digits
	}

	if (m_validatorWindow->IsKindOf(CLASSINFO(wxStaticText)) )
	{
		wxStaticText* pControl = (wxStaticText*) m_validatorWindow;
		if (pControl)
		{
			pControl->SetLabel(str);
			return true;
		}
	}
	else
	if (m_validatorWindow->IsKindOf(CLASSINFO(wxTextCtrl)) )
	{
		wxTextCtrl* pControl = (wxTextCtrl*) m_validatorWindow;
		if (pControl)
		{
			pControl->SetValue(str);
			return true;
		}
	}

	// unrecognized control, or bad pointer
	return false;
}

// Called to transfer data from the window
bool wxNumericValidator::TransferFromWindow()
{
	if ( !m_validatorWindow )
		return false;

	if ( !m_bEnabled )
		return true;

	// string controls
	wxString str;
	if (m_validatorWindow->IsKindOf(CLASSINFO(wxStaticText)) )
	{
		wxStaticText* pControl = (wxStaticText*) m_validatorWindow;
		if (pControl)
			str = pControl->GetLabel();
	}
	else if (m_validatorWindow->IsKindOf(CLASSINFO(wxTextCtrl)) )
	{
		wxTextCtrl* pControl = (wxTextCtrl*) m_validatorWindow;
		if (pControl)
			str = pControl->GetValue();
	}
	else // unrecognized control, or bad pointer
		return false;

	if (str != _T(""))
	{
		vtString ccs = (const char *) str.mb_str(*wxConvCurrent);
		if (m_pValShort)
			sscanf(ccs, "%d", m_pValShort);
		if (m_pValInt)
			sscanf(ccs, "%d", m_pValInt);
		if (m_pValFloat)
			sscanf(ccs, "%f", m_pValFloat);
		if (m_pValDouble)
			sscanf(ccs, "%lf", m_pValDouble);
		return true;
	}
	return false;
}

/////////////////////////////////////////////////
//

void AutoDialog::AddValidator(long id, wxString *sptr)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return;
	pWin->SetValidator(wxGenericValidator(sptr));	// actually clones the one we pass in
}

void AutoDialog::AddValidator(long id, bool *bptr)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return;
	pWin->SetValidator(wxGenericValidator(bptr));	// actually clones the one we pass in
}

void AutoDialog::AddValidator(long id, int *iptr)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return;
	pWin->SetValidator(wxGenericValidator(iptr));	// actually clones the one we pass in
}

wxNumericValidator *AutoDialog::AddNumValidator(long id, short *sptr)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return NULL;

	// actually clones the one we pass in
	pWin->SetValidator(wxNumericValidator(sptr));
	return (wxNumericValidator*) pWin->GetValidator();
}

wxNumericValidator *AutoDialog::AddNumValidator(long id, int *iptr)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return NULL;

	// actually clones the one we pass in
	pWin->SetValidator(wxNumericValidator(iptr));
	return (wxNumericValidator*) pWin->GetValidator();
}

wxNumericValidator *AutoDialog::AddNumValidator(long id, float *fptr, int digits)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return NULL;

	// actually clones the one we pass in
	pWin->SetValidator(wxNumericValidator(fptr, digits));
	return (wxNumericValidator*) pWin->GetValidator();
}

wxNumericValidator *AutoDialog::AddNumValidator(long id, double *dptr, int digits)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return NULL;

	// actually clones the one we pass in
	pWin->SetValidator(wxNumericValidator(dptr, digits));
	return (wxNumericValidator*) pWin->GetValidator();
}

/////////////////////////////////////////////////
//

void AutoPanel::AddValidator(long id, wxString *sptr)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return;
	pWin->SetValidator(wxGenericValidator(sptr));	// actually clones the one we pass in
}

void AutoPanel::AddValidator(long id, bool *bptr)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return;
	pWin->SetValidator(wxGenericValidator(bptr));	// actually clones the one we pass in
}

void AutoPanel::AddValidator(long id, int *iptr)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return;
	pWin->SetValidator(wxGenericValidator(iptr));	// actually clones the one we pass in
}

wxNumericValidator *AutoPanel::AddNumValidator(long id, int *iptr)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return NULL;

	// actually clones the one we pass in
	pWin->SetValidator(wxNumericValidator(iptr));
	return (wxNumericValidator *) pWin->GetValidator();
}

wxNumericValidator *AutoPanel::AddNumValidator(long id, float *fptr, int digits)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return NULL;

	// actually clones the one we pass in
	pWin->SetValidator(wxNumericValidator(fptr, digits));
	return (wxNumericValidator *) pWin->GetValidator();
}

wxNumericValidator *AutoPanel::AddNumValidator(long id, double *dptr, int digits)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return NULL;

	pWin->SetValidator(wxNumericValidator(dptr, digits));
	// actually clones the one we pass in
	return (wxNumericValidator *) pWin->GetValidator();
}

<commit_msg>avoid meaningless value comparison on empty string<commit_after>//
// Implements the following classes:
//
// AutoDialog - An improvement to wxDialog which makes validation easier.
//
// AutoPanel - An improvement to wxPanel which makes validation easier.
//
// wxNumericValidator - A validator capable of transfering numeric values.
//
// Copyright (c) 2001-2007 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#include "wx/wxprec.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "vtdata/vtString.h"
#include "AutoDialog.h"

/////////////////////////////////////////////////
//

wxNumericValidator::wxNumericValidator(short *val) : wxValidator()
{
	Initialize();
	m_pValShort = val;
}

wxNumericValidator::wxNumericValidator(int *val) : wxValidator()
{
	Initialize();
	m_pValInt = val;
}

wxNumericValidator::wxNumericValidator(float *val, int digits) : wxValidator()
{
	Initialize();
	m_pValFloat = val;
	m_iDigits = digits;
}

wxNumericValidator::wxNumericValidator(double *val, int digits) : wxValidator()
{
	Initialize();
	m_pValDouble = val;
	m_iDigits = digits;
}

wxNumericValidator::wxNumericValidator(const wxNumericValidator& val)
{
	Initialize();
	Copy(val);
}

/*
  Called by constructors to initialize ALL data members
*/
void wxNumericValidator::Initialize()
{
	m_pValShort = NULL;
	m_pValInt = NULL;
	m_pValFloat = NULL;
	m_pValDouble = NULL;
	m_iDigits = 0;
	m_bEnabled = true;
}

bool wxNumericValidator::Copy(const wxNumericValidator& val)
{
	wxValidator::Copy(val);

	m_pValShort = val.m_pValShort;
	m_pValInt = val.m_pValInt;
	m_pValFloat = val.m_pValFloat;
	m_pValDouble = val.m_pValDouble;
	m_iDigits = val.m_iDigits;

	return true;
}

// Called to transfer data to the window
bool wxNumericValidator::TransferToWindow()
{
	if ( !m_validatorWindow )
		return false;

	if ( !m_bEnabled )
		return true;

	// Compare existing string to new string; don't update unless the actual
	//  numeric value has changed.
	wxString OldString;
	if (m_validatorWindow->IsKindOf(CLASSINFO(wxStaticText)) )
	{
		wxStaticText* pControl = (wxStaticText*) m_validatorWindow;
		if (pControl)
			OldString = pControl->GetLabel() ;
	}
	else if (m_validatorWindow->IsKindOf(CLASSINFO(wxTextCtrl)) )
	{
		wxTextCtrl* pControl = (wxTextCtrl*) m_validatorWindow;
		if (pControl)
			OldString = pControl->GetValue() ;
	}
	else
		return false;

	wxString str, format;
	long OldIntValue;
	double OldDoubleValue;
	if (m_pValShort)
	{
		if (OldString != _T(""))
		{
			OldString.ToLong(&OldIntValue);
			if (OldIntValue == (long)*m_pValShort)
				return true;
		}

		str.Printf(_T("%d"), *m_pValShort);
	}
	else if (m_pValInt)
	{
		if (OldString != _T(""))
		{
			OldString.ToLong(&OldIntValue);
			if (OldIntValue == (long)*m_pValInt)
				return true;
		}

		str.Printf(_T("%d"), *m_pValInt);
	}
	else if (m_pValFloat)
	{
		if (OldString != _T(""))
		{
			OldString.ToDouble(&OldDoubleValue);
			if (OldDoubleValue == (double)*m_pValFloat)
				return true;
		}

		if (m_iDigits != -1)
		{
			format.Printf(_T("%%.%df"), m_iDigits);
			str.Printf(format, *m_pValFloat);
		}
		else
			str.Printf(_T("%.8g"), *m_pValFloat);	// 8 significant digits
	}
	else if (m_pValDouble)
	{
		if (OldString != _T(""))
		{
			OldString.ToDouble(&OldDoubleValue);
			if (OldDoubleValue == *m_pValDouble)
				return true;
		}

		if (m_iDigits != -1)
		{
			format.Printf(_T("%%.%dlf"), m_iDigits);
			str.Printf(format, *m_pValDouble);
		}
		else
			str.Printf(_T("%.16lg"), *m_pValDouble);	// 16 significant digits
	}

	if (m_validatorWindow->IsKindOf(CLASSINFO(wxStaticText)) )
	{
		wxStaticText* pControl = (wxStaticText*) m_validatorWindow;
		if (pControl)
		{
			pControl->SetLabel(str);
			return true;
		}
	}
	else
	if (m_validatorWindow->IsKindOf(CLASSINFO(wxTextCtrl)) )
	{
		wxTextCtrl* pControl = (wxTextCtrl*) m_validatorWindow;
		if (pControl)
		{
			pControl->SetValue(str);
			return true;
		}
	}

	// unrecognized control, or bad pointer
	return false;
}

// Called to transfer data from the window
bool wxNumericValidator::TransferFromWindow()
{
	if ( !m_validatorWindow )
		return false;

	if ( !m_bEnabled )
		return true;

	// string controls
	wxString str;
	if (m_validatorWindow->IsKindOf(CLASSINFO(wxStaticText)) )
	{
		wxStaticText* pControl = (wxStaticText*) m_validatorWindow;
		if (pControl)
			str = pControl->GetLabel();
	}
	else if (m_validatorWindow->IsKindOf(CLASSINFO(wxTextCtrl)) )
	{
		wxTextCtrl* pControl = (wxTextCtrl*) m_validatorWindow;
		if (pControl)
			str = pControl->GetValue();
	}
	else // unrecognized control, or bad pointer
		return false;

	if (str != _T(""))
	{
		vtString ccs = (const char *) str.mb_str(*wxConvCurrent);
		if (m_pValShort)
			sscanf(ccs, "%d", m_pValShort);
		if (m_pValInt)
			sscanf(ccs, "%d", m_pValInt);
		if (m_pValFloat)
			sscanf(ccs, "%f", m_pValFloat);
		if (m_pValDouble)
			sscanf(ccs, "%lf", m_pValDouble);
		return true;
	}
	return false;
}

/////////////////////////////////////////////////
//

void AutoDialog::AddValidator(long id, wxString *sptr)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return;
	pWin->SetValidator(wxGenericValidator(sptr));	// actually clones the one we pass in
}

void AutoDialog::AddValidator(long id, bool *bptr)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return;
	pWin->SetValidator(wxGenericValidator(bptr));	// actually clones the one we pass in
}

void AutoDialog::AddValidator(long id, int *iptr)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return;
	pWin->SetValidator(wxGenericValidator(iptr));	// actually clones the one we pass in
}

wxNumericValidator *AutoDialog::AddNumValidator(long id, short *sptr)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return NULL;

	// actually clones the one we pass in
	pWin->SetValidator(wxNumericValidator(sptr));
	return (wxNumericValidator*) pWin->GetValidator();
}

wxNumericValidator *AutoDialog::AddNumValidator(long id, int *iptr)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return NULL;

	// actually clones the one we pass in
	pWin->SetValidator(wxNumericValidator(iptr));
	return (wxNumericValidator*) pWin->GetValidator();
}

wxNumericValidator *AutoDialog::AddNumValidator(long id, float *fptr, int digits)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return NULL;

	// actually clones the one we pass in
	pWin->SetValidator(wxNumericValidator(fptr, digits));
	return (wxNumericValidator*) pWin->GetValidator();
}

wxNumericValidator *AutoDialog::AddNumValidator(long id, double *dptr, int digits)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return NULL;

	// actually clones the one we pass in
	pWin->SetValidator(wxNumericValidator(dptr, digits));
	return (wxNumericValidator*) pWin->GetValidator();
}

/////////////////////////////////////////////////
//

void AutoPanel::AddValidator(long id, wxString *sptr)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return;
	pWin->SetValidator(wxGenericValidator(sptr));	// actually clones the one we pass in
}

void AutoPanel::AddValidator(long id, bool *bptr)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return;
	pWin->SetValidator(wxGenericValidator(bptr));	// actually clones the one we pass in
}

void AutoPanel::AddValidator(long id, int *iptr)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return;
	pWin->SetValidator(wxGenericValidator(iptr));	// actually clones the one we pass in
}

wxNumericValidator *AutoPanel::AddNumValidator(long id, int *iptr)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return NULL;

	// actually clones the one we pass in
	pWin->SetValidator(wxNumericValidator(iptr));
	return (wxNumericValidator *) pWin->GetValidator();
}

wxNumericValidator *AutoPanel::AddNumValidator(long id, float *fptr, int digits)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return NULL;

	// actually clones the one we pass in
	pWin->SetValidator(wxNumericValidator(fptr, digits));
	return (wxNumericValidator *) pWin->GetValidator();
}

wxNumericValidator *AutoPanel::AddNumValidator(long id, double *dptr, int digits)
{
	wxWindow *pWin = FindWindow(id);
	if (!pWin) return NULL;

	pWin->SetValidator(wxNumericValidator(dptr, digits));
	// actually clones the one we pass in
	return (wxNumericValidator *) pWin->GetValidator();
}

<|endoftext|>


<commit_before>#include "Storage.h"

#include <fstream>
#include <functional>
#include <random>
#include <algorithm>
#include <locale>
#include <codecvt>
#include <cstdlib>

namespace cefpdf {

Storage::Storage() {
    m_temp = GetTempPath();
}

std::string Storage::Reserve()
{
    std::string letters = "9876543210ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    std::random_device rd;
    std::mt19937 g(rd());
    std::shuffle(letters.begin(), letters.end(), g);
    std::string path = m_temp + "cef_" + letters + ".pdf";

    std::ifstream file;
    file.open(path);
    bool isGood = file.good();
    file.close();

    return isGood ? Reserve() : path;
}

std::string Storage::Load(const std::string& path, bool remove)
{
    std::string content;
    std::ifstream output;

    output.open(path, std::ifstream::binary);
    if (output.good()) {
        content.assign((std::istreambuf_iterator<char>(output)), std::istreambuf_iterator<char>());
        output.close();
        if (remove) {
            Delete(path);
        }

        return content;
    }

    throw "Cannot open file: \"" + path + "\"";
}

bool Storage::Delete(const std::string& path)
{
    return 0 == std::remove(path.c_str());
}

std::string Storage::GetTempPath()
{
#if defined(OS_WIN)
    wchar_t lpBuffer[MAX_PATH];
    ::GetTempPathW(MAX_PATH, lpBuffer);
    return std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(lpBuffer);
#else
    const char* vars[4] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
    for (int i = 0; i < 4; ++i) {
        char* val = std::getenv(vars[i]);
        if (val) {
            return std::string(val) + "/";
        }
    }

    return "/tmp/";
#endif // OS_WIN
}

} // namespace cefpdf
<commit_msg>Switch to ascii version of ::GetTempPath()<commit_after>#include "Storage.h"

#include <fstream>
#include <functional>
#include <random>
#include <algorithm>
#include <cstdlib>

namespace cefpdf {

Storage::Storage() {
    m_temp = GetTempPath();
}

std::string Storage::Reserve()
{
    std::string letters = "9876543210ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    std::random_device rd;
    std::mt19937 g(rd());
    std::shuffle(letters.begin(), letters.end(), g);
    std::string path = m_temp + "cef_" + letters + ".pdf";

    std::ifstream file;
    file.open(path);
    bool isGood = file.good();
    file.close();

    return isGood ? Reserve() : path;
}

std::string Storage::Load(const std::string& path, bool remove)
{
    std::string content;
    std::ifstream output;

    output.open(path, std::ifstream::binary);
    if (output.good()) {
        content.assign((std::istreambuf_iterator<char>(output)), std::istreambuf_iterator<char>());
        output.close();
        if (remove) {
            Delete(path);
        }

        return content;
    }

    throw "Cannot open file: \"" + path + "\"";
}

bool Storage::Delete(const std::string& path)
{
    return 0 == std::remove(path.c_str());
}

std::string Storage::GetTempPath()
{
#if defined(OS_WIN)
    char lpBuffer[MAX_PATH];
    ::GetTempPathA(MAX_PATH, lpBuffer);
    return lpBuffer;
#else
    const char* vars[4] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
    for (int i = 0; i < 4; ++i) {
        char* val = std::getenv(vars[i]);
        if (val) {
            return std::string(val) + "/";
        }
    }

    return "/tmp/";
#endif // OS_WIN
}

} // namespace cefpdf
<|endoftext|>