<commit_before>int* predo(string pattern){
    int* dp = new int[pattern.size()];
    dp[0] = 0;
    for(int i=1;i<pattern.size();i++){
        dp[i] = dp[i-1];
        while(dp[i] > 0 && pattern[dp[i]] != pattern[i])dp[i] = dp[dp[i]-1];
        if(pattern[dp[i]] == pattern[i])dp[i]++;
    }
    return dp;
}

void KMP(string text,string pattern){
    int* dp = predo(pattern);
    for(int i=0,match=0;i<text.size();i++){
        while(match > 0 && pattern[match] != text[i])match = dp[match-1];
        if(pattern[match] == text[i])match++;
        if(match == pattern.size()){
            cout << i-pattern.size()+1 << endl;
            match = dp[match-1];
        }
    }
    delete [] dp;
}
<commit_msg>Update KMP.cpp<commit_after>// Complexity : O(T+P)
void predo(string pattern,int dp[]){
    dp[0] = 0;
    for(int i=1;i<pattern.size();i++){
        dp[i] = dp[i-1];
        while(dp[i] > 0 && pattern[dp[i]] != pattern[i]) dp[i] = dp[dp[i]-1];
        if(pattern[dp[i]] == pattern[i]) dp[i]++;
    }
}

void KMP(string text,string pattern){
    int dp[pattern.size()];predo(pattern,dp);
    for(int i=0,match=0;i<text.size();i++){
        while(match > 0 && pattern[match] != text[i]) match = dp[match-1];
        if(pattern[match] == text[i]) match++;
        if(match == pattern.size()){
            // do something with i-pattern.size()+1
            match = dp[match-1];
        }
    }
}
<|endoftext|>


<commit_before>#pragma once

// `krbn::observer::device_observer` can be used safely in a multi-threaded environment.

#include "event_queue.hpp"
#include "grabber_client.hpp"
#include "iokit_utility.hpp"
#include "logger.hpp"
#include "types.hpp"
#include <pqrs/dispatcher.hpp>
#include <pqrs/osx/iokit_hid_manager.hpp>
#include <pqrs/osx/iokit_hid_queue_value_monitor.hpp>
#include <pqrs/osx/iokit_types.hpp>

namespace krbn {
namespace observer {
class device_observer final : public pqrs::dispatcher::extra::dispatcher_client {
public:
  device_observer(const device_observer&) = delete;

  device_observer(std::weak_ptr<grabber_client> grabber_client) : dispatcher_client(),
                                                                  grabber_client_(grabber_client) {
    // hid_manager_

    std::vector<pqrs::cf::cf_ptr<CFDictionaryRef>> matching_dictionaries{
        pqrs::osx::iokit_hid_manager::make_matching_dictionary(
            pqrs::osx::iokit_hid_usage_page_generic_desktop,
            pqrs::osx::iokit_hid_usage_generic_desktop_keyboard),

        pqrs::osx::iokit_hid_manager::make_matching_dictionary(
            pqrs::osx::iokit_hid_usage_page_generic_desktop,
            pqrs::osx::iokit_hid_usage_generic_desktop_mouse),

        pqrs::osx::iokit_hid_manager::make_matching_dictionary(
            pqrs::osx::iokit_hid_usage_page_generic_desktop,
            pqrs::osx::iokit_hid_usage_generic_desktop_pointer),
    };

    hid_manager_ = std::make_unique<pqrs::osx::iokit_hid_manager>(weak_dispatcher_,
                                                                  matching_dictionaries,
                                                                  std::chrono::milliseconds(3000));

    hid_manager_->device_matched.connect([this](auto&& registry_entry_id, auto&& device_ptr) {
      if (device_ptr) {
        iokit_utility::log_matching_device(registry_entry_id, *device_ptr);

        auto device_id = make_device_id(registry_entry_id);
        auto device_name = iokit_utility::make_device_name_for_log(device_id,
                                                                   *device_ptr);

        auto hid_queue_value_monitor = std::make_shared<pqrs::osx::iokit_hid_queue_value_monitor>(weak_dispatcher_,
                                                                                *device_ptr);
        hid_queue_value_monitors_[device_id] = hid_queue_value_monitor;

        if (iokit_utility::is_karabiner_virtual_hid_device(*device_ptr)) {
          // Handle caps_lock_state_changed event only if the hid is Karabiner-VirtualHIDDevice.
          hid_queue_value_monitor->values_arrived.connect([this, device_id](auto&& values_ptr) {
            auto event_queue = event_queue::utility::make_queue(device_id,
                                                                iokit_utility::make_hid_values(values_ptr));
            for (const auto& e : event_queue->get_entries()) {
              if (e.get_event().get_type() == event_queue::event::type::caps_lock_state_changed) {
                if (auto client = grabber_client_.lock()) {
                  if (auto state = e.get_event().get_integer_value()) {
                    client->async_caps_lock_state_changed(*state);
                  }
                }
              }
            }
          });
        } else {
          hid_queue_value_monitor->values_arrived.connect([this, device_id](auto&& values_ptr) {
            auto event_queue = event_queue::utility::make_queue(device_id,
                                                                iokit_utility::make_hid_values(values_ptr));
            for (const auto& entry : event_queue->get_entries()) {
              if (auto e = entry.get_event().make_key_down_up_valued_event()) {
                if (auto client = grabber_client_.lock()) {
                  client->async_key_down_up_valued_event_arrived(device_id,
                                                                 *e,
                                                                 entry.get_event_type(),
                                                                 entry.get_event_time_stamp().get_time_stamp());
                }
              }
            }
          });
        }

        hid_queue_value_monitor->started.connect([this, device_id, device_name] {
          logger::get_logger()->info("{0} is observed.", device_name);

          observed_devices_.insert(device_id);

          send_observed_devices();
        });

        hid_queue_value_monitor->async_start(kIOHIDOptionsTypeNone,
                                             std::chrono::milliseconds(3000));
      }

      async_rescan();
    });

    hid_manager_->device_terminated.connect([this](auto&& registry_entry_id) {
      auto device_id = make_device_id(registry_entry_id);

      logger::get_logger()->info("device_id:{0} is terminated.", type_safe::get(device_id));

      hid_queue_value_monitors_.erase(device_id);
      observed_devices_.erase(device_id);

      send_observed_devices();

      async_rescan();
    });

    hid_manager_->error_occurred.connect([](auto&& message, auto&& iokit_return) {
      logger::get_logger()->error("{0}: {1}", message, iokit_return.to_string());
    });
  }

  virtual ~device_observer(void) {
    detach_from_dispatcher([this] {
      hid_manager_ = nullptr;
      hid_queue_value_monitors_.clear();
    });

    logger::get_logger()->info("device_observer is stopped.");
  }

  void async_start(void) const {
    enqueue_to_dispatcher([this] {
      hid_manager_->async_start();

      logger::get_logger()->info("device_observer is started.");
    });
  }

  void async_rescan(void) const {
    enqueue_to_dispatcher([this] {
      hid_manager_->async_rescan();

      logger::get_logger()->info("rescan devices...");
    });
  }

  void async_send_observed_devices(void) const {
    enqueue_to_dispatcher([this] {
      send_observed_devices();
    });
  }

private:
  void send_observed_devices(void) const {
    if (auto client = grabber_client_.lock()) {
      client->async_observed_devices_updated(observed_devices_);
    }
  }

  std::weak_ptr<grabber_client> grabber_client_;

  std::unique_ptr<pqrs::osx::iokit_hid_manager> hid_manager_;
  std::unordered_map<device_id, std::shared_ptr<pqrs::osx::iokit_hid_queue_value_monitor>> hid_queue_value_monitors_;
  std::unordered_set<device_id> observed_devices_;
};
} // namespace observer
} // namespace krbn
<commit_msg>set device_matched_delay_ 0 @ observer<commit_after>#pragma once

// `krbn::observer::device_observer` can be used safely in a multi-threaded environment.

#include "event_queue.hpp"
#include "grabber_client.hpp"
#include "iokit_utility.hpp"
#include "logger.hpp"
#include "types.hpp"
#include <pqrs/dispatcher.hpp>
#include <pqrs/osx/iokit_hid_manager.hpp>
#include <pqrs/osx/iokit_hid_queue_value_monitor.hpp>
#include <pqrs/osx/iokit_types.hpp>

namespace krbn {
namespace observer {
class device_observer final : public pqrs::dispatcher::extra::dispatcher_client {
public:
  device_observer(const device_observer&) = delete;

  device_observer(std::weak_ptr<grabber_client> grabber_client) : dispatcher_client(),
                                                                  grabber_client_(grabber_client) {
    // hid_manager_

    std::vector<pqrs::cf::cf_ptr<CFDictionaryRef>> matching_dictionaries{
        pqrs::osx::iokit_hid_manager::make_matching_dictionary(
            pqrs::osx::iokit_hid_usage_page_generic_desktop,
            pqrs::osx::iokit_hid_usage_generic_desktop_keyboard),

        pqrs::osx::iokit_hid_manager::make_matching_dictionary(
            pqrs::osx::iokit_hid_usage_page_generic_desktop,
            pqrs::osx::iokit_hid_usage_generic_desktop_mouse),

        pqrs::osx::iokit_hid_manager::make_matching_dictionary(
            pqrs::osx::iokit_hid_usage_page_generic_desktop,
            pqrs::osx::iokit_hid_usage_generic_desktop_pointer),
    };

    hid_manager_ = std::make_unique<pqrs::osx::iokit_hid_manager>(weak_dispatcher_,
                                                                  matching_dictionaries,
                                                                  std::chrono::milliseconds(0));

    hid_manager_->device_matched.connect([this](auto&& registry_entry_id, auto&& device_ptr) {
      if (device_ptr) {
        iokit_utility::log_matching_device(registry_entry_id, *device_ptr);

        auto device_id = make_device_id(registry_entry_id);
        auto device_name = iokit_utility::make_device_name_for_log(device_id,
                                                                   *device_ptr);

        auto hid_queue_value_monitor = std::make_shared<pqrs::osx::iokit_hid_queue_value_monitor>(weak_dispatcher_,
                                                                                *device_ptr);
        hid_queue_value_monitors_[device_id] = hid_queue_value_monitor;

        if (iokit_utility::is_karabiner_virtual_hid_device(*device_ptr)) {
          // Handle caps_lock_state_changed event only if the hid is Karabiner-VirtualHIDDevice.
          hid_queue_value_monitor->values_arrived.connect([this, device_id](auto&& values_ptr) {
            auto event_queue = event_queue::utility::make_queue(device_id,
                                                                iokit_utility::make_hid_values(values_ptr));
            for (const auto& e : event_queue->get_entries()) {
              if (e.get_event().get_type() == event_queue::event::type::caps_lock_state_changed) {
                if (auto client = grabber_client_.lock()) {
                  if (auto state = e.get_event().get_integer_value()) {
                    client->async_caps_lock_state_changed(*state);
                  }
                }
              }
            }
          });
        } else {
          hid_queue_value_monitor->values_arrived.connect([this, device_id](auto&& values_ptr) {
            auto event_queue = event_queue::utility::make_queue(device_id,
                                                                iokit_utility::make_hid_values(values_ptr));
            for (const auto& entry : event_queue->get_entries()) {
              if (auto e = entry.get_event().make_key_down_up_valued_event()) {
                if (auto client = grabber_client_.lock()) {
                  client->async_key_down_up_valued_event_arrived(device_id,
                                                                 *e,
                                                                 entry.get_event_type(),
                                                                 entry.get_event_time_stamp().get_time_stamp());
                }
              }
            }
          });
        }

        hid_queue_value_monitor->started.connect([this, device_id, device_name] {
          logger::get_logger()->info("{0} is observed.", device_name);

          observed_devices_.insert(device_id);

          send_observed_devices();
        });

        hid_queue_value_monitor->async_start(kIOHIDOptionsTypeNone,
                                             std::chrono::milliseconds(3000));
      }

      async_rescan();
    });

    hid_manager_->device_terminated.connect([this](auto&& registry_entry_id) {
      auto device_id = make_device_id(registry_entry_id);

      logger::get_logger()->info("device_id:{0} is terminated.", type_safe::get(device_id));

      hid_queue_value_monitors_.erase(device_id);
      observed_devices_.erase(device_id);

      send_observed_devices();

      async_rescan();
    });

    hid_manager_->error_occurred.connect([](auto&& message, auto&& iokit_return) {
      logger::get_logger()->error("{0}: {1}", message, iokit_return.to_string());
    });
  }

  virtual ~device_observer(void) {
    detach_from_dispatcher([this] {
      hid_manager_ = nullptr;
      hid_queue_value_monitors_.clear();
    });

    logger::get_logger()->info("device_observer is stopped.");
  }

  void async_start(void) const {
    enqueue_to_dispatcher([this] {
      hid_manager_->async_start();

      logger::get_logger()->info("device_observer is started.");
    });
  }

  void async_rescan(void) const {
    enqueue_to_dispatcher([this] {
      hid_manager_->async_rescan();

      logger::get_logger()->info("rescan devices...");
    });
  }

  void async_send_observed_devices(void) const {
    enqueue_to_dispatcher([this] {
      send_observed_devices();
    });
  }

private:
  void send_observed_devices(void) const {
    if (auto client = grabber_client_.lock()) {
      client->async_observed_devices_updated(observed_devices_);
    }
  }

  std::weak_ptr<grabber_client> grabber_client_;

  std::unique_ptr<pqrs::osx::iokit_hid_manager> hid_manager_;
  std::unordered_map<device_id, std::shared_ptr<pqrs::osx::iokit_hid_queue_value_monitor>> hid_queue_value_monitors_;
  std::unordered_set<device_id> observed_devices_;
};
} // namespace observer
} // namespace krbn
<|endoftext|>


<commit_before>// Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
//
// Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License.
//
// 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
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//

//  GEOM GEOMGUI : GUI for Geometry component
//  File   : OperationGUI_ExtrudedFeatureDlg.cxx
//  Author : Renaud NEDELEC, Open CASCADE S.A.S.

#include "OperationGUI.h"
#include "OperationGUI_ExtrudedFeatureDlg.h"

#include <SUIT_Session.h>
#include <SUIT_ResourceMgr.h>
#include <SalomeApp_Application.h>
#include <LightApp_SelectionMgr.h>

#include <GeometryGUI.h>
#include <GEOMBase.h>

#include <DlgRef.h>
#include <GEOM_Object.hxx>

// OCCT Includes
#include <TColStd_HSequenceOfTransient.hxx>

#include <GEOMImpl_Types.hxx>

//=================================================================================
// class    : OperationGUI_ExtrudedFeatureDlg()
// purpose  : Constructs a OperationGUI_ExtrudedCutDlg which is a child of 'parent',
//            with the name 'name' and widget flags set to 'f'.
//            The dialog will by default be modeless, unless you set 'modal' to
//            TRUE to construct a modal dialog.
//=================================================================================

OperationGUI_ExtrudedFeatureDlg::OperationGUI_ExtrudedFeatureDlg(const int theOperation,
                                                                 GeometryGUI* theGeometryGUI,
                                                                 QWidget* parent,bool modal,
                                                                 Qt::WindowFlags fl)
  : GEOMBase_Skeleton(theGeometryGUI, parent, modal, fl),
    myOperation(theOperation)
{
  SUIT_ResourceMgr* aResMgr = SUIT_Session::session()->resourceMgr();
  QPixmap image0;
  QPixmap image1 (aResMgr->loadPixmap("GEOM", tr("ICON_SELECT")));
  QPixmap image2 (aResMgr->loadPixmap("GEOM", tr("ICO_DRAFT")));
  QPixmap image3 (aResMgr->loadPixmap("GEOM", tr("ICON_DLG_CHANGE_DIRECTION")));
  QString aTitle;
  switch (myOperation)
  {
    case OperationGUI::BOSS:
      image0 = QPixmap(aResMgr->loadPixmap("GEOM", tr("ICO_EXTRUDED_BOSS")));
      aTitle = tr("GEOM_EXTRUDED_BOSS_TITLE");
      setHelpFileName("extruded_boss_operation_page.html");
      break;
    case OperationGUI::CUT:
      image0 = QPixmap( aResMgr->loadPixmap("GEOM", tr("ICO_EXTRUDED_CUT")));
      aTitle = tr("GEOM_EXTRUDED_CUT_TITLE");
      setHelpFileName("extruded_cut_operation_page.html");
      break;
  }

  setWindowTitle(aTitle);
  mainFrame()->GroupConstructors->setTitle(aTitle);
  mainFrame()->RadioButton1->setIcon(image0);
  mainFrame()->RadioButton2->setAttribute(Qt::WA_DeleteOnClose);
  mainFrame()->RadioButton2->close();
  mainFrame()->RadioButton3->setAttribute(Qt::WA_DeleteOnClose);
  mainFrame()->RadioButton3->close();

  mainFrame()->RadioButton1->setChecked(true);

  myGroup = new DlgRef_2Sel2Spin2Push(centralWidget());

  myGroup->GroupBox1->setTitle(tr("GEOM_ARGUMENTS"));

  myGroup->PushButton1->setIcon(image1);
  myGroup->PushButton2->setIcon(image1);
  myGroup->PushButton3->setIcon(image2);
  myGroup->PushButton4->setIcon(image3);
  myGroup->LineEdit1->setReadOnly(true);
  myGroup->LineEdit2->setReadOnly(true);
  myGroup->TextLabel1->setText(tr("GEOM_INIT_SHAPE"));
  myGroup->TextLabel2->setText(tr("GEOM_PROFILE"));
  myGroup->TextLabel3->setText(tr("GEOM_HEIGHT"));
  myGroup->TextLabel4->setText(tr("GEOM_DRAFT_ANGLE"));
  myGroup->TextLabel5->setText(tr("GEOM_CHANGE_DIRECTION"));

  QVBoxLayout* layout = new QVBoxLayout(centralWidget());
  layout->setMargin(0);
  layout->setSpacing(6);
  layout->addWidget(myGroup);

  Init();

}

//=================================================================================
// function : ~OperationGUI_ExtrudedFeatureDlg()
// purpose  : Destroys the object and frees any allocated resources
//=================================================================================
OperationGUI_ExtrudedFeatureDlg::~OperationGUI_ExtrudedFeatureDlg()
{
}

//=================================================================================
// function : Init()
// purpose  :
//=================================================================================
void OperationGUI_ExtrudedFeatureDlg::Init()
{
  // init variables
  myEditCurrentArgument = myGroup->LineEdit1;

  // Get setting of step value from file configuration
  SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
  double step = resMgr->doubleValue("Geometry", "SettingsGeomStep", 100);

  initSpinBox(myGroup->SpinBox_DX, COORD_MIN, COORD_MAX, step, "length_precision" );
  initSpinBox(myGroup->SpinBox_DY, COORD_MIN, COORD_MAX, step, "length_precision" );

  myGroup->LineEdit1->setText("");
  myGroup->LineEdit2->setText("");
  myGroup->SpinBox_DX->setValue(10.0);
  myGroup->SpinBox_DY->setValue(10.0);
  myGroup->SpinBox_DY->setEnabled(false);
  myObject1.nullify();
  myObject2.nullify();

  // signals and slots connections
  connect(buttonOk(),    SIGNAL(clicked()), this, SLOT(ClickOnOk()));
  connect(buttonApply(), SIGNAL(clicked()), this, SLOT(ClickOnApply()));

  connect(myGroup->PushButton1, SIGNAL(clicked()),     this, SLOT(SetEditCurrentArgument()));
  connect(myGroup->PushButton2, SIGNAL(clicked()),     this, SLOT(SetEditCurrentArgument()));
  connect(myGroup->PushButton3, SIGNAL(clicked(bool)), this, SLOT(ButtonClicked(bool)));
  connect(myGroup->PushButton4, SIGNAL(clicked(bool)), this, SLOT(ButtonClicked(bool)));
  connect(myGroup->SpinBox_DX,  SIGNAL(valueChanged(double)), this, SLOT(ValueChangedInSpinBox()));
  connect(myGroup->SpinBox_DY,  SIGNAL(valueChanged(double)), this, SLOT(ValueChangedInSpinBox()));

  connect(((SalomeApp_Application*)(SUIT_Session::session()->activeApplication()))->selectionMgr(),
           SIGNAL(currentSelectionChanged()), this, SLOT(SelectionIntoArgument()));

  switch (myOperation)
  {
    case OperationGUI::BOSS:
      initName(tr("GEOM_EXTRUDED_BOSS"));
      break;
    case OperationGUI::CUT:
      initName(tr("GEOM_EXTRUDED_CUT"));
      break;
  }

  mainFrame()->RadioButton1->setFocus();

  globalSelection(GEOM_ALLSHAPES);

  myGroup->PushButton1->click();
  SelectionIntoArgument();

  resize(minimumSizeHint());
}

//=================================================================================
// function : ClickOnOk()
// purpose  :
//=================================================================================
void OperationGUI_ExtrudedFeatureDlg::ClickOnOk()
{
  setIsApplyAndClose( true );
  if (ClickOnApply())
    ClickOnCancel();
}

//=================================================================================
// function : ClickOnApply()
// purpose  :
//=================================================================================
bool OperationGUI_ExtrudedFeatureDlg::ClickOnApply()
{
  if (!onAccept())
    return false;

  initName();
  // activate selection and connect selection manager
  myGroup->PushButton1->click();
  return true;
}

//=================================================================================
// function : SetEditCurrentArgument()
// purpose  :
//=================================================================================
void OperationGUI_ExtrudedFeatureDlg::SetEditCurrentArgument()
{
  QPushButton* send = (QPushButton*)sender();

  if (send == myGroup->PushButton1) {
    myEditCurrentArgument = myGroup->LineEdit1;

    myGroup->PushButton2->setDown(false);
    myGroup->LineEdit2->setEnabled(false);
  }
  else if (send == myGroup->PushButton2) {
    myEditCurrentArgument = myGroup->LineEdit2;

    myGroup->PushButton1->setDown(false);
    myGroup->LineEdit1->setEnabled(false);
  }

  // enable line edit
  myEditCurrentArgument->setEnabled(true);
  myEditCurrentArgument->setFocus();
  // after setFocus(), because it will be setDown(false) when loses focus
  send->setDown(true);
}

//=================================================================================
// function : SelectionIntoArgument()
// purpose  : Called when selection is changed or on dialog initialization or activation
//=================================================================================
void OperationGUI_ExtrudedFeatureDlg::SelectionIntoArgument()
{
  myEditCurrentArgument->setText("");

  QList<TopAbs_ShapeEnum> types;
  types<<TopAbs_SHAPE;

  if (myEditCurrentArgument == myGroup->LineEdit1)
  {
    types.clear();
    types<<TopAbs_COMPOUND<<TopAbs_SOLID;
  }
  if (myEditCurrentArgument == myGroup->LineEdit2)
  {
    types.clear();
    types << TopAbs_EDGE << TopAbs_WIRE << TopAbs_FACE;
  }

  GEOM::GeomObjPtr aSelectedObject = getSelected( types );
  TopoDS_Shape aShape;
  if ( aSelectedObject && GEOMBase::GetShape( aSelectedObject.get(), aShape ) && !aShape.IsNull() ) {
    QString aName = GEOMBase::GetName( aSelectedObject.get() );
    myEditCurrentArgument->setText( aName );

    // clear selection
    disconnect(myGeomGUI->getApp()->selectionMgr(), 0, this, 0);
    myGeomGUI->getApp()->selectionMgr()->clearSelected();
    connect(myGeomGUI->getApp()->selectionMgr(), SIGNAL(currentSelectionChanged()),
            this, SLOT(SelectionIntoArgument()));

    if (myEditCurrentArgument == myGroup->LineEdit1) {
      myObject1 = aSelectedObject;
      if (!myObject2)
        myGroup->PushButton2->click();
    }
    else if (myEditCurrentArgument == myGroup->LineEdit2) {
      myObject2 = aSelectedObject;
      if (!myObject1)
        myGroup->PushButton1->click();
    }

    displayPreview(true);
  }
  else {
    if      (myEditCurrentArgument == myGroup->LineEdit1) myObject1.nullify();
    else if (myEditCurrentArgument == myGroup->LineEdit2) myObject2.nullify();
  }
}

//=================================================================================
// function : ActivateThisDialog()
// purpose  :
//=================================================================================
void OperationGUI_ExtrudedFeatureDlg::ActivateThisDialog()
{
  GEOMBase_Skeleton::ActivateThisDialog();

  connect( myGeomGUI->getApp()->selectionMgr(), SIGNAL( currentSelectionChanged() ),
           this, SLOT( SelectionIntoArgument() ) );
  processPreview();
}

//=================================================================================
// function : enterEvent()
// purpose  : when mouse enter onto the QWidget
//=================================================================================
void OperationGUI_ExtrudedFeatureDlg::enterEvent (QEvent*)
{
  if (!mainFrame()->GroupConstructors->isEnabled())
    ActivateThisDialog();
}

//=================================================================================
// function : ValueChangedInSpinBox()
// purpose  :
//=================================================================================
void OperationGUI_ExtrudedFeatureDlg::ValueChangedInSpinBox()
{
  displayPreview(true);
}

//=================================================================================
// function : ButtonClicked(bool checked)
// purpose  :
//=================================================================================
void OperationGUI_ExtrudedFeatureDlg::ButtonClicked(bool checked)
{
  QPushButton* send = (QPushButton*)sender();
  if (send == myGroup->PushButton3)
    myGroup->SpinBox_DY->setEnabled(checked);

  displayPreview(true);
}

//=================================================================================
// function : createOperation
// purpose  :
//=================================================================================
GEOM::GEOM_IOperations_ptr OperationGUI_ExtrudedFeatureDlg::createOperation()
{
  return getGeomEngine()->GetI3DPrimOperations(getStudyId());
}

//=================================================================================
// function : isValid
// purpose  :
//=================================================================================
bool OperationGUI_ExtrudedFeatureDlg::isValid (QString&)
{
  return myObject1 && myObject2;
}

//=================================================================================
// function : execute
// purpose  :
//=================================================================================
bool OperationGUI_ExtrudedFeatureDlg::execute (ObjectList& objects)
{
  GEOM::GEOM_I3DPrimOperations_var anOper = GEOM::GEOM_I3DPrimOperations::_narrow(getOperation());

  double angle=0.0;
  double aHeight = myGroup->SpinBox_DX->value();

  if (myGroup->PushButton3->isChecked())
    angle=myGroup->SpinBox_DY->value();

  if (myGroup->PushButton4->isChecked())
  {
    aHeight = -aHeight;
    angle   = -angle;
  }

  bool isProtrusion = (myOperation == OperationGUI::BOSS);

  // Hide the initial shape in order to see the modifications on the preview
  erase(myObject1.get(),false);

  GEOM::GEOM_Object_var anObj = anOper->MakeDraftPrism(myObject1.get(), myObject2.get(),
                                                       aHeight,
                                                       angle,
                                                       isProtrusion);
  if (!anObj->_is_nil())
    objects.push_back(anObj._retn());

  return true;
}

// //=================================================================================
// // function : addSubshapeToStudy
// // purpose  : virtual method to add new SubObjects if local selection
// //=================================================================================
// void OperationGUI_ExtrudedFeatureDlg::addSubshapesToStudy()
// {
//   GEOMBase::PublishSubObject( myObject2.get() );
// }
<commit_msg>GEOM porting to CMake<commit_after>// Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
//
// Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License.
//
// 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
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//

//  GEOM GEOMGUI : GUI for Geometry component
//  File   : OperationGUI_ExtrudedFeatureDlg.cxx
//  Author : Renaud NEDELEC, Open CASCADE S.A.S.

#include "OperationGUI.h"
#include "OperationGUI_ExtrudedFeatureDlg.h"

#include <SUIT_Session.h>
#include <SUIT_ResourceMgr.h>
#include <SalomeApp_Application.h>
#include <LightApp_SelectionMgr.h>

#include <GeometryGUI.h>
#include <GEOMBase.h>

#include <DlgRef.h>

// OCCT Includes
#include <TColStd_HSequenceOfTransient.hxx>

#include <GEOMImpl_Types.hxx>

//=================================================================================
// class    : OperationGUI_ExtrudedFeatureDlg()
// purpose  : Constructs a OperationGUI_ExtrudedCutDlg which is a child of 'parent',
//            with the name 'name' and widget flags set to 'f'.
//            The dialog will by default be modeless, unless you set 'modal' to
//            TRUE to construct a modal dialog.
//=================================================================================

OperationGUI_ExtrudedFeatureDlg::OperationGUI_ExtrudedFeatureDlg(const int theOperation,
                                                                 GeometryGUI* theGeometryGUI,
                                                                 QWidget* parent,bool modal,
                                                                 Qt::WindowFlags fl)
  : GEOMBase_Skeleton(theGeometryGUI, parent, modal, fl),
    myOperation(theOperation)
{
  SUIT_ResourceMgr* aResMgr = SUIT_Session::session()->resourceMgr();
  QPixmap image0;
  QPixmap image1 (aResMgr->loadPixmap("GEOM", tr("ICON_SELECT")));
  QPixmap image2 (aResMgr->loadPixmap("GEOM", tr("ICO_DRAFT")));
  QPixmap image3 (aResMgr->loadPixmap("GEOM", tr("ICON_DLG_CHANGE_DIRECTION")));
  QString aTitle;
  switch (myOperation)
  {
    case OperationGUI::BOSS:
      image0 = QPixmap(aResMgr->loadPixmap("GEOM", tr("ICO_EXTRUDED_BOSS")));
      aTitle = tr("GEOM_EXTRUDED_BOSS_TITLE");
      setHelpFileName("extruded_boss_operation_page.html");
      break;
    case OperationGUI::CUT:
      image0 = QPixmap( aResMgr->loadPixmap("GEOM", tr("ICO_EXTRUDED_CUT")));
      aTitle = tr("GEOM_EXTRUDED_CUT_TITLE");
      setHelpFileName("extruded_cut_operation_page.html");
      break;
  }

  setWindowTitle(aTitle);
  mainFrame()->GroupConstructors->setTitle(aTitle);
  mainFrame()->RadioButton1->setIcon(image0);
  mainFrame()->RadioButton2->setAttribute(Qt::WA_DeleteOnClose);
  mainFrame()->RadioButton2->close();
  mainFrame()->RadioButton3->setAttribute(Qt::WA_DeleteOnClose);
  mainFrame()->RadioButton3->close();

  mainFrame()->RadioButton1->setChecked(true);

  myGroup = new DlgRef_2Sel2Spin2Push(centralWidget());

  myGroup->GroupBox1->setTitle(tr("GEOM_ARGUMENTS"));

  myGroup->PushButton1->setIcon(image1);
  myGroup->PushButton2->setIcon(image1);
  myGroup->PushButton3->setIcon(image2);
  myGroup->PushButton4->setIcon(image3);
  myGroup->LineEdit1->setReadOnly(true);
  myGroup->LineEdit2->setReadOnly(true);
  myGroup->TextLabel1->setText(tr("GEOM_INIT_SHAPE"));
  myGroup->TextLabel2->setText(tr("GEOM_PROFILE"));
  myGroup->TextLabel3->setText(tr("GEOM_HEIGHT"));
  myGroup->TextLabel4->setText(tr("GEOM_DRAFT_ANGLE"));
  myGroup->TextLabel5->setText(tr("GEOM_CHANGE_DIRECTION"));

  QVBoxLayout* layout = new QVBoxLayout(centralWidget());
  layout->setMargin(0);
  layout->setSpacing(6);
  layout->addWidget(myGroup);

  Init();

}

//=================================================================================
// function : ~OperationGUI_ExtrudedFeatureDlg()
// purpose  : Destroys the object and frees any allocated resources
//=================================================================================
OperationGUI_ExtrudedFeatureDlg::~OperationGUI_ExtrudedFeatureDlg()
{
}

//=================================================================================
// function : Init()
// purpose  :
//=================================================================================
void OperationGUI_ExtrudedFeatureDlg::Init()
{
  // init variables
  myEditCurrentArgument = myGroup->LineEdit1;

  // Get setting of step value from file configuration
  SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
  double step = resMgr->doubleValue("Geometry", "SettingsGeomStep", 100);

  initSpinBox(myGroup->SpinBox_DX, COORD_MIN, COORD_MAX, step, "length_precision" );
  initSpinBox(myGroup->SpinBox_DY, COORD_MIN, COORD_MAX, step, "length_precision" );

  myGroup->LineEdit1->setText("");
  myGroup->LineEdit2->setText("");
  myGroup->SpinBox_DX->setValue(10.0);
  myGroup->SpinBox_DY->setValue(10.0);
  myGroup->SpinBox_DY->setEnabled(false);
  myObject1.nullify();
  myObject2.nullify();

  // signals and slots connections
  connect(buttonOk(),    SIGNAL(clicked()), this, SLOT(ClickOnOk()));
  connect(buttonApply(), SIGNAL(clicked()), this, SLOT(ClickOnApply()));

  connect(myGroup->PushButton1, SIGNAL(clicked()),     this, SLOT(SetEditCurrentArgument()));
  connect(myGroup->PushButton2, SIGNAL(clicked()),     this, SLOT(SetEditCurrentArgument()));
  connect(myGroup->PushButton3, SIGNAL(clicked(bool)), this, SLOT(ButtonClicked(bool)));
  connect(myGroup->PushButton4, SIGNAL(clicked(bool)), this, SLOT(ButtonClicked(bool)));
  connect(myGroup->SpinBox_DX,  SIGNAL(valueChanged(double)), this, SLOT(ValueChangedInSpinBox()));
  connect(myGroup->SpinBox_DY,  SIGNAL(valueChanged(double)), this, SLOT(ValueChangedInSpinBox()));

  connect(((SalomeApp_Application*)(SUIT_Session::session()->activeApplication()))->selectionMgr(),
           SIGNAL(currentSelectionChanged()), this, SLOT(SelectionIntoArgument()));

  switch (myOperation)
  {
    case OperationGUI::BOSS:
      initName(tr("GEOM_EXTRUDED_BOSS"));
      break;
    case OperationGUI::CUT:
      initName(tr("GEOM_EXTRUDED_CUT"));
      break;
  }

  mainFrame()->RadioButton1->setFocus();

  globalSelection(GEOM_ALLSHAPES);

  myGroup->PushButton1->click();
  SelectionIntoArgument();

  resize(minimumSizeHint());
}

//=================================================================================
// function : ClickOnOk()
// purpose  :
//=================================================================================
void OperationGUI_ExtrudedFeatureDlg::ClickOnOk()
{
  setIsApplyAndClose( true );
  if (ClickOnApply())
    ClickOnCancel();
}

//=================================================================================
// function : ClickOnApply()
// purpose  :
//=================================================================================
bool OperationGUI_ExtrudedFeatureDlg::ClickOnApply()
{
  if (!onAccept())
    return false;

  initName();
  // activate selection and connect selection manager
  myGroup->PushButton1->click();
  return true;
}

//=================================================================================
// function : SetEditCurrentArgument()
// purpose  :
//=================================================================================
void OperationGUI_ExtrudedFeatureDlg::SetEditCurrentArgument()
{
  QPushButton* send = (QPushButton*)sender();

  if (send == myGroup->PushButton1) {
    myEditCurrentArgument = myGroup->LineEdit1;

    myGroup->PushButton2->setDown(false);
    myGroup->LineEdit2->setEnabled(false);
  }
  else if (send == myGroup->PushButton2) {
    myEditCurrentArgument = myGroup->LineEdit2;

    myGroup->PushButton1->setDown(false);
    myGroup->LineEdit1->setEnabled(false);
  }

  // enable line edit
  myEditCurrentArgument->setEnabled(true);
  myEditCurrentArgument->setFocus();
  // after setFocus(), because it will be setDown(false) when loses focus
  send->setDown(true);
}

//=================================================================================
// function : SelectionIntoArgument()
// purpose  : Called when selection is changed or on dialog initialization or activation
//=================================================================================
void OperationGUI_ExtrudedFeatureDlg::SelectionIntoArgument()
{
  myEditCurrentArgument->setText("");

  QList<TopAbs_ShapeEnum> types;
  types<<TopAbs_SHAPE;

  if (myEditCurrentArgument == myGroup->LineEdit1)
  {
    types.clear();
    types<<TopAbs_COMPOUND<<TopAbs_SOLID;
  }
  if (myEditCurrentArgument == myGroup->LineEdit2)
  {
    types.clear();
    types << TopAbs_EDGE << TopAbs_WIRE << TopAbs_FACE;
  }

  GEOM::GeomObjPtr aSelectedObject = getSelected( types );
  TopoDS_Shape aShape;
  if ( aSelectedObject && GEOMBase::GetShape( aSelectedObject.get(), aShape ) && !aShape.IsNull() ) {
    QString aName = GEOMBase::GetName( aSelectedObject.get() );
    myEditCurrentArgument->setText( aName );

    // clear selection
    disconnect(myGeomGUI->getApp()->selectionMgr(), 0, this, 0);
    myGeomGUI->getApp()->selectionMgr()->clearSelected();
    connect(myGeomGUI->getApp()->selectionMgr(), SIGNAL(currentSelectionChanged()),
            this, SLOT(SelectionIntoArgument()));

    if (myEditCurrentArgument == myGroup->LineEdit1) {
      myObject1 = aSelectedObject;
      if (!myObject2)
        myGroup->PushButton2->click();
    }
    else if (myEditCurrentArgument == myGroup->LineEdit2) {
      myObject2 = aSelectedObject;
      if (!myObject1)
        myGroup->PushButton1->click();
    }

    displayPreview(true);
  }
  else {
    if      (myEditCurrentArgument == myGroup->LineEdit1) myObject1.nullify();
    else if (myEditCurrentArgument == myGroup->LineEdit2) myObject2.nullify();
  }
}

//=================================================================================
// function : ActivateThisDialog()
// purpose  :
//=================================================================================
void OperationGUI_ExtrudedFeatureDlg::ActivateThisDialog()
{
  GEOMBase_Skeleton::ActivateThisDialog();

  connect( myGeomGUI->getApp()->selectionMgr(), SIGNAL( currentSelectionChanged() ),
           this, SLOT( SelectionIntoArgument() ) );
  processPreview();
}

//=================================================================================
// function : enterEvent()
// purpose  : when mouse enter onto the QWidget
//=================================================================================
void OperationGUI_ExtrudedFeatureDlg::enterEvent (QEvent*)
{
  if (!mainFrame()->GroupConstructors->isEnabled())
    ActivateThisDialog();
}

//=================================================================================
// function : ValueChangedInSpinBox()
// purpose  :
//=================================================================================
void OperationGUI_ExtrudedFeatureDlg::ValueChangedInSpinBox()
{
  displayPreview(true);
}

//=================================================================================
// function : ButtonClicked(bool checked)
// purpose  :
//=================================================================================
void OperationGUI_ExtrudedFeatureDlg::ButtonClicked(bool checked)
{
  QPushButton* send = (QPushButton*)sender();
  if (send == myGroup->PushButton3)
    myGroup->SpinBox_DY->setEnabled(checked);

  displayPreview(true);
}

//=================================================================================
// function : createOperation
// purpose  :
//=================================================================================
GEOM::GEOM_IOperations_ptr OperationGUI_ExtrudedFeatureDlg::createOperation()
{
  return getGeomEngine()->GetI3DPrimOperations(getStudyId());
}

//=================================================================================
// function : isValid
// purpose  :
//=================================================================================
bool OperationGUI_ExtrudedFeatureDlg::isValid (QString&)
{
  return myObject1 && myObject2;
}

//=================================================================================
// function : execute
// purpose  :
//=================================================================================
bool OperationGUI_ExtrudedFeatureDlg::execute (ObjectList& objects)
{
  GEOM::GEOM_I3DPrimOperations_var anOper = GEOM::GEOM_I3DPrimOperations::_narrow(getOperation());

  double angle=0.0;
  double aHeight = myGroup->SpinBox_DX->value();

  if (myGroup->PushButton3->isChecked())
    angle=myGroup->SpinBox_DY->value();

  if (myGroup->PushButton4->isChecked())
  {
    aHeight = -aHeight;
    angle   = -angle;
  }

  bool isProtrusion = (myOperation == OperationGUI::BOSS);

  // Hide the initial shape in order to see the modifications on the preview
  erase(myObject1.get(),false);

  GEOM::GEOM_Object_var anObj = anOper->MakeDraftPrism(myObject1.get(), myObject2.get(),
                                                       aHeight,
                                                       angle,
                                                       isProtrusion);
  if (!anObj->_is_nil())
    objects.push_back(anObj._retn());

  return true;
}

// //=================================================================================
// // function : addSubshapeToStudy
// // purpose  : virtual method to add new SubObjects if local selection
// //=================================================================================
// void OperationGUI_ExtrudedFeatureDlg::addSubshapesToStudy()
// {
//   GEOMBase::PublishSubObject( myObject2.get() );
// }
<|endoftext|>


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

#include "SkColorPriv.h"
#include "SkShader.h"

namespace skiagm {

class BigMatrixGM : public GM {
public:
    BigMatrixGM() {
        this->setBGColor(0xFF66AA99);
    }

protected:
    virtual SkString onShortName() {
        return SkString("bigmatrix");
    }

    virtual SkISize onISize() {
        return make_isize(50, 50);
    }

    virtual void onDraw(SkCanvas* canvas) {
        SkMatrix m;
        m.reset();
        m.setRotate(33 * SK_Scalar1);
        m.postScale(3000 * SK_Scalar1, 3000 * SK_Scalar1);
        m.postTranslate(6000 * SK_Scalar1, -5000 * SK_Scalar1);
        canvas->concat(m);

        SkPaint paint;
        paint.setColor(SK_ColorRED);
        paint.setAntiAlias(true);

        m.invert(&m);

        SkPath path;

        SkPoint pt = {10 * SK_Scalar1, 10 * SK_Scalar1};
        SkScalar small = 1 / (500 * SK_Scalar1);

        m.mapPoints(&pt, 1);
        path.addCircle(pt.fX, pt.fY, small);
        canvas->drawPath(path, paint);

        pt.set(30 * SK_Scalar1, 10 * SK_Scalar1);
        m.mapPoints(&pt, 1);
        SkRect rect = {pt.fX - small, pt.fY - small,
                       pt.fX + small, pt.fY + small};
        canvas->drawRect(rect, paint);

        SkBitmap bmp;
        bmp.setConfig(SkBitmap::kARGB_8888_Config, 2, 2);
        bmp.allocPixels();
        bmp.lockPixels();
        uint32_t* pixels = reinterpret_cast<uint32_t*>(bmp.getPixels());
        pixels[0] = SkPackARGB32(0xFF, 0xFF, 0x00, 0x00);
        pixels[1] = SkPackARGB32(0xFF, 0x00, 0xFF, 0x00);
        pixels[2] = SkPackARGB32(0x80, 0x00, 0x00, 0x00);
        pixels[3] = SkPackARGB32(0xFF, 0x00, 0x00, 0xFF);
        bmp.unlockPixels();
        pt.set(30 * SK_Scalar1, 30 * SK_Scalar1);
        m.mapPoints(&pt, 1);
        SkShader* shader = SkShader::CreateBitmapShader(
                                            bmp,
                                            SkShader::kRepeat_TileMode,
                                            SkShader::kRepeat_TileMode);
        SkMatrix s;
        s.reset();
        s.setScale(SK_Scalar1 / 1000, SK_Scalar1 / 1000);
        shader->setLocalMatrix(s);
        paint.setShader(shader)->unref();
        paint.setAntiAlias(false);
        paint.setFilterBitmap(true);
        rect.setLTRB(pt.fX - small, pt.fY - small,
                     pt.fX + small, pt.fY + small);
        canvas->drawRect(rect, paint);
    }

private:
    typedef GM INHERITED;
};

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

static GM* MyFactory(void*) { return new BigMatrixGM; }
static GMRegistry reg(MyFactory);

}

<commit_msg>silence warning<commit_after>
/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "gm.h"

#include "SkColorPriv.h"
#include "SkShader.h"

namespace skiagm {

class BigMatrixGM : public GM {
public:
    BigMatrixGM() {
        this->setBGColor(0xFF66AA99);
    }

protected:
    virtual SkString onShortName() {
        return SkString("bigmatrix");
    }

    virtual SkISize onISize() {
        return make_isize(50, 50);
    }

    virtual void onDraw(SkCanvas* canvas) {
        SkMatrix m;
        m.reset();
        m.setRotate(33 * SK_Scalar1);
        m.postScale(3000 * SK_Scalar1, 3000 * SK_Scalar1);
        m.postTranslate(6000 * SK_Scalar1, -5000 * SK_Scalar1);
        canvas->concat(m);

        SkPaint paint;
        paint.setColor(SK_ColorRED);
        paint.setAntiAlias(true);

        bool success = m.invert(&m);

        SkPath path;

        SkPoint pt = {10 * SK_Scalar1, 10 * SK_Scalar1};
        SkScalar small = 1 / (500 * SK_Scalar1);

        m.mapPoints(&pt, 1);
        path.addCircle(pt.fX, pt.fY, small);
        canvas->drawPath(path, paint);

        pt.set(30 * SK_Scalar1, 10 * SK_Scalar1);
        m.mapPoints(&pt, 1);
        SkRect rect = {pt.fX - small, pt.fY - small,
                       pt.fX + small, pt.fY + small};
        canvas->drawRect(rect, paint);

        SkBitmap bmp;
        bmp.setConfig(SkBitmap::kARGB_8888_Config, 2, 2);
        bmp.allocPixels();
        bmp.lockPixels();
        uint32_t* pixels = reinterpret_cast<uint32_t*>(bmp.getPixels());
        pixels[0] = SkPackARGB32(0xFF, 0xFF, 0x00, 0x00);
        pixels[1] = SkPackARGB32(0xFF, 0x00, 0xFF, 0x00);
        pixels[2] = SkPackARGB32(0x80, 0x00, 0x00, 0x00);
        pixels[3] = SkPackARGB32(0xFF, 0x00, 0x00, 0xFF);
        bmp.unlockPixels();
        pt.set(30 * SK_Scalar1, 30 * SK_Scalar1);
        m.mapPoints(&pt, 1);
        SkShader* shader = SkShader::CreateBitmapShader(
                                            bmp,
                                            SkShader::kRepeat_TileMode,
                                            SkShader::kRepeat_TileMode);
        SkMatrix s;
        s.reset();
        s.setScale(SK_Scalar1 / 1000, SK_Scalar1 / 1000);
        shader->setLocalMatrix(s);
        paint.setShader(shader)->unref();
        paint.setAntiAlias(false);
        paint.setFilterBitmap(true);
        rect.setLTRB(pt.fX - small, pt.fY - small,
                     pt.fX + small, pt.fY + small);
        canvas->drawRect(rect, paint);
    }

private:
    typedef GM INHERITED;
};

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

static GM* MyFactory(void*) { return new BigMatrixGM; }
static GMRegistry reg(MyFactory);

}

<|endoftext|>


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

#include "gm.h"
#include "SkGeometry.h"
#include "SkPaint.h"
#include "SkPath.h"
#include "SkPoint.h"
#include "SkRandom.h"

#include <math.h>

namespace skiagm {

// Slices paths into sliver-size contours shaped like ice cream cones.
class MandolineSlicer {
public:
    static constexpr int kDefaultSubdivisions = 10;

    MandolineSlicer(SkPoint anchorPt) {
        fPath.setFillType(SkPath::kEvenOdd_FillType);
        fPath.setIsVolatile(true);
        this->reset(anchorPt);
    }

    void reset(SkPoint anchorPt) {
        fPath.reset();
        fLastPt = fAnchorPt = anchorPt;
    }

    void sliceLine(SkPoint pt, int numSubdivisions = kDefaultSubdivisions) {
        if (numSubdivisions <= 0) {
            fPath.moveTo(fAnchorPt);
            fPath.lineTo(fLastPt);
            fPath.lineTo(pt);
            fPath.close();
            fLastPt = pt;
            return;
        }
        float T = this->chooseChopT(numSubdivisions);
        if (0 == T) {
            fPath.lineTo(fLastPt);
            this->sliceLine(pt, numSubdivisions - 1);
            return;
        }
        SkPoint midpt = fLastPt * (1 - T) + pt * T;
        this->sliceLine(midpt, numSubdivisions - 1);
        this->sliceLine(pt, numSubdivisions - 1);
    }

    void sliceQuadratic(SkPoint p1, SkPoint p2, int numSubdivisions = kDefaultSubdivisions) {
        if (numSubdivisions <= 0) {
            fPath.moveTo(fAnchorPt);
            fPath.lineTo(fLastPt);
            fPath.quadTo(p1, p2);
            fPath.close();
            fLastPt = p2;
            return;
        }
        float T = this->chooseChopT(numSubdivisions);
        if (0 == T) {
            fPath.quadTo(fLastPt, fLastPt);
            this->sliceQuadratic(p1, p2, numSubdivisions - 1);
            return;
        }
        SkPoint P[3] = {fLastPt, p1, p2}, PP[5];
        SkChopQuadAt(P, PP, T);
        this->sliceQuadratic(PP[1], PP[2], numSubdivisions - 1);
        this->sliceQuadratic(PP[3], PP[4], numSubdivisions - 1);
    }

    void sliceCubic(SkPoint p1, SkPoint p2, SkPoint p3,
                    int numSubdivisions = kDefaultSubdivisions) {
        if (numSubdivisions <= 0) {
            fPath.moveTo(fAnchorPt);
            fPath.lineTo(fLastPt);
            fPath.cubicTo(p1, p2, p3);
            fPath.close();
            fLastPt = p3;
            return;
        }
        float T = this->chooseChopT(numSubdivisions);
        if (0 == T) {
            fPath.cubicTo(fLastPt, fLastPt, fLastPt);
            this->sliceCubic(p1, p2, p3, numSubdivisions - 1);
            return;
        }
        SkPoint P[4] = {fLastPt, p1, p2, p3}, PP[7];
        SkChopCubicAt(P, PP, T);
        this->sliceCubic(PP[1], PP[2], PP[3], numSubdivisions - 1);
        this->sliceCubic(PP[4], PP[5], PP[6], numSubdivisions - 1);
    }

    void sliceConic(SkPoint p1, SkPoint p2, float w, int numSubdivisions = kDefaultSubdivisions) {
        if (numSubdivisions <= 0) {
            fPath.moveTo(fAnchorPt);
            fPath.lineTo(fLastPt);
            fPath.conicTo(p1, p2, w);
            fPath.close();
            fLastPt = p2;
            return;
        }
        float T = this->chooseChopT(numSubdivisions);
        if (0 == T) {
            fPath.conicTo(fLastPt, fLastPt, w);
            this->sliceConic(p1, p2, w, numSubdivisions - 1);
            return;
        }
        SkConic conic(fLastPt, p1, p2, w), halves[2];
        if (!conic.chopAt(T, halves)) {
            SK_ABORT("SkConic::chopAt failed");
        }
        this->sliceConic(halves[0].fPts[1], halves[0].fPts[2], halves[0].fW, numSubdivisions - 1);
        this->sliceConic(halves[1].fPts[1], halves[1].fPts[2], halves[1].fW, numSubdivisions - 1);
    }

    const SkPath& path() const { return fPath; }

private:
    float chooseChopT(int numSubdivisions) {
        SkASSERT(numSubdivisions > 0);
        if (numSubdivisions > 1) {
            return .5f;
        }
        float T = (0 == fRand.nextU() % 10) ? 0 : scalbnf(1, -(int)fRand.nextRangeU(10, 149));
        SkASSERT(T >= 0 && T < 1);
        return T;
    }

    SkRandom fRand;
    SkPath fPath;
    SkPoint fAnchorPt;
    SkPoint fLastPt;
};

class SliverPathsGM : public GM {
public:
    SliverPathsGM() {
        this->setBGColor(SK_ColorBLACK);
    }

protected:
    SkString onShortName() override {
        return SkString("mandoline");
    }

    SkISize onISize() override {
        return SkISize::Make(560, 475);
    }

    void onDraw(SkCanvas* canvas) override {
        SkPaint paint;
        paint.setColor(SK_ColorWHITE);
        paint.setAntiAlias(true);

        MandolineSlicer mandoline({41, 43});
        mandoline.sliceCubic({5, 277}, {381, -74}, {243, 162});
        mandoline.sliceLine({41, 43});
        canvas->drawPath(mandoline.path(), paint);

        mandoline.reset({357.049988f, 446.049988f});
        mandoline.sliceCubic({472.750000f, -71.950012f}, {639.750000f, 531.950012f},
                             {309.049988f, 347.950012f});
        mandoline.sliceLine({309.049988f, 419});
        mandoline.sliceLine({357.049988f, 446.049988f});
        canvas->drawPath(mandoline.path(), paint);

        canvas->save();
        canvas->translate(421, 105);
        canvas->scale(100, 81);
        mandoline.reset({-cosf(SkDegreesToRadians(-60)), sinf(SkDegreesToRadians(-60))});
        mandoline.sliceConic({-2, 0},
                             {-cosf(SkDegreesToRadians(60)), sinf(SkDegreesToRadians(60))}, .5f);
        mandoline.sliceConic({-cosf(SkDegreesToRadians(120))*2, sinf(SkDegreesToRadians(120))*2},
                             {1, 0}, .5f);
        mandoline.sliceLine({0, 0});
        mandoline.sliceLine({-cosf(SkDegreesToRadians(-60)), sinf(SkDegreesToRadians(-60))});
        canvas->drawPath(mandoline.path(), paint);
        canvas->restore();

        canvas->save();
        canvas->translate(150, 300);
        canvas->scale(75, 75);
        mandoline.reset({1, 0});
        constexpr int nquads = 5;
        for (int i = 0; i < nquads; ++i) {
            float theta1 = 2*SK_ScalarPI/nquads * (i + .5f);
            float theta2 = 2*SK_ScalarPI/nquads * (i + 1);
            mandoline.sliceQuadratic({cosf(theta1)*2, sinf(theta1)*2},
                                     {cosf(theta2), sinf(theta2)});
        }
        canvas->drawPath(mandoline.path(), paint);
        canvas->restore();
    }
};

DEF_GM(return new SliverPathsGM;)

}
<commit_msg>modify gm to avoid creating t-junctions between degernate curves and lines<commit_after>/*
 * Copyright 2018 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "gm.h"
#include "SkGeometry.h"
#include "SkPaint.h"
#include "SkPath.h"
#include "SkPoint.h"
#include "SkRandom.h"

#include <math.h>

namespace skiagm {

// Slices paths into sliver-size contours shaped like ice cream cones.
class MandolineSlicer {
public:
    static constexpr int kDefaultSubdivisions = 10;

    MandolineSlicer(SkPoint anchorPt) {
        fPath.setFillType(SkPath::kEvenOdd_FillType);
        fPath.setIsVolatile(true);
        this->reset(anchorPt);
    }

    void reset(SkPoint anchorPt) {
        fPath.reset();
        fLastPt = fAnchorPt = anchorPt;
    }

    void sliceLine(SkPoint pt, int numSubdivisions = kDefaultSubdivisions) {
        if (numSubdivisions <= 0) {
            fPath.moveTo(fAnchorPt);
            fPath.lineTo(fLastPt);
            fPath.lineTo(pt);
            fPath.close();
            fLastPt = pt;
            return;
        }
        float T = this->chooseChopT(numSubdivisions);
        if (0 == T) {
            return;
        }
        SkPoint midpt = fLastPt * (1 - T) + pt * T;
        this->sliceLine(midpt, numSubdivisions - 1);
        this->sliceLine(pt, numSubdivisions - 1);
    }

    void sliceQuadratic(SkPoint p1, SkPoint p2, int numSubdivisions = kDefaultSubdivisions) {
        if (numSubdivisions <= 0) {
            fPath.moveTo(fAnchorPt);
            fPath.lineTo(fLastPt);
            fPath.quadTo(p1, p2);
            fPath.close();
            fLastPt = p2;
            return;
        }
        float T = this->chooseChopT(numSubdivisions);
        if (0 == T) {
            return;
        }
        SkPoint P[3] = {fLastPt, p1, p2}, PP[5];
        SkChopQuadAt(P, PP, T);
        this->sliceQuadratic(PP[1], PP[2], numSubdivisions - 1);
        this->sliceQuadratic(PP[3], PP[4], numSubdivisions - 1);
    }

    void sliceCubic(SkPoint p1, SkPoint p2, SkPoint p3,
                    int numSubdivisions = kDefaultSubdivisions) {
        if (numSubdivisions <= 0) {
            fPath.moveTo(fAnchorPt);
            fPath.lineTo(fLastPt);
            fPath.cubicTo(p1, p2, p3);
            fPath.close();
            fLastPt = p3;
            return;
        }
        float T = this->chooseChopT(numSubdivisions);
        if (0 == T) {
            return;
        }
        SkPoint P[4] = {fLastPt, p1, p2, p3}, PP[7];
        SkChopCubicAt(P, PP, T);
        this->sliceCubic(PP[1], PP[2], PP[3], numSubdivisions - 1);
        this->sliceCubic(PP[4], PP[5], PP[6], numSubdivisions - 1);
    }

    void sliceConic(SkPoint p1, SkPoint p2, float w, int numSubdivisions = kDefaultSubdivisions) {
        if (numSubdivisions <= 0) {
            fPath.moveTo(fAnchorPt);
            fPath.lineTo(fLastPt);
            fPath.conicTo(p1, p2, w);
            fPath.close();
            fLastPt = p2;
            return;
        }
        float T = this->chooseChopT(numSubdivisions);
        if (0 == T) {
            return;
        }
        SkConic conic(fLastPt, p1, p2, w), halves[2];
        if (!conic.chopAt(T, halves)) {
            SK_ABORT("SkConic::chopAt failed");
        }
        this->sliceConic(halves[0].fPts[1], halves[0].fPts[2], halves[0].fW, numSubdivisions - 1);
        this->sliceConic(halves[1].fPts[1], halves[1].fPts[2], halves[1].fW, numSubdivisions - 1);
    }

    const SkPath& path() const { return fPath; }

private:
    float chooseChopT(int numSubdivisions) {
        SkASSERT(numSubdivisions > 0);
        if (numSubdivisions > 1) {
            return .5f;
        }
        float T = (0 == fRand.nextU() % 10) ? 0 : scalbnf(1, -(int)fRand.nextRangeU(10, 149));
        SkASSERT(T >= 0 && T < 1);
        return T;
    }

    SkRandom fRand;
    SkPath fPath;
    SkPoint fAnchorPt;
    SkPoint fLastPt;
};

class SliverPathsGM : public GM {
public:
    SliverPathsGM() {
        this->setBGColor(SK_ColorBLACK);
    }

protected:
    SkString onShortName() override {
        return SkString("mandoline");
    }

    SkISize onISize() override {
        return SkISize::Make(560, 475);
    }

    void onDraw(SkCanvas* canvas) override {
        SkPaint paint;
        paint.setColor(SK_ColorWHITE);
        paint.setAntiAlias(true);

        MandolineSlicer mandoline({41, 43});
        mandoline.sliceCubic({5, 277}, {381, -74}, {243, 162});
        mandoline.sliceLine({41, 43});
        canvas->drawPath(mandoline.path(), paint);

        mandoline.reset({357.049988f, 446.049988f});
        mandoline.sliceCubic({472.750000f, -71.950012f}, {639.750000f, 531.950012f},
                             {309.049988f, 347.950012f});
        mandoline.sliceLine({309.049988f, 419});
        mandoline.sliceLine({357.049988f, 446.049988f});
        canvas->drawPath(mandoline.path(), paint);

        canvas->save();
        canvas->translate(421, 105);
        canvas->scale(100, 81);
        mandoline.reset({-cosf(SkDegreesToRadians(-60)), sinf(SkDegreesToRadians(-60))});
        mandoline.sliceConic({-2, 0},
                             {-cosf(SkDegreesToRadians(60)), sinf(SkDegreesToRadians(60))}, .5f);
        mandoline.sliceConic({-cosf(SkDegreesToRadians(120))*2, sinf(SkDegreesToRadians(120))*2},
                             {1, 0}, .5f);
        mandoline.sliceLine({0, 0});
        mandoline.sliceLine({-cosf(SkDegreesToRadians(-60)), sinf(SkDegreesToRadians(-60))});
        canvas->drawPath(mandoline.path(), paint);
        canvas->restore();

        canvas->save();
        canvas->translate(150, 300);
        canvas->scale(75, 75);
        mandoline.reset({1, 0});
        constexpr int nquads = 5;
        for (int i = 0; i < nquads; ++i) {
            float theta1 = 2*SK_ScalarPI/nquads * (i + .5f);
            float theta2 = 2*SK_ScalarPI/nquads * (i + 1);
            mandoline.sliceQuadratic({cosf(theta1)*2, sinf(theta1)*2},
                                     {cosf(theta2), sinf(theta2)});
        }
        canvas->drawPath(mandoline.path(), paint);
        canvas->restore();
    }
};

DEF_GM(return new SliverPathsGM;)

}
<|endoftext|>


<commit_before>/*
  The MIT License (MIT)

  Copyright (c) 2016 G. Beard

  Permission is hereby granted, free of charge, to any person obtaining a
  copy of this software and associated documentation files (the "Software"),
  to deal in the Software without restriction, including without limitation
  the rights to use, copy, modify, merge, publish, distribute, sublicense,
  and/or sell copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included
  in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  DEALINGS IN THE SOFTWARE.
*/
#ifndef TEST_HPP_INCLUDED
#define TEST_HPP_INCLUDED

#include <iostream>
#include <vector>
#include <tuple>

namespace gmb { namespace test
{
  size_t error_count;
  using test_case_t = void(*)(char const*);
  std::vector<std::pair<test_case_t, char const*>> list;
} }

#define TEST_STRINGIFY_IMPL(str) #str
#define TEST_STRINGIFY(str) TEST_STRINGIFY_IMPL(str)
#define TEST_CONCAT_IMPL(x, y) x##y
#define TEST_CONCAT(x, y) TEST_CONCAT_IMPL(x, y)

#define TEST_CASE(name) \
  void name(char const*); \
  struct name##_helper_t \
  { \
    name##_helper_t() \
    { \
      ::gmb::test::list.push_back(std::make_pair( \
        name, TEST_STRINGIFY(name))); \
    } \
  } name##_instance; \
  void name(char const* _test_name_)

#define DEFINE_TEST_MAIN \
  int main() \
  { \
    for(auto&& t : ::gmb::test::list) { \
      std::get<0>(t)(std::get<1>(t)); \
    } \
    TEST_EXIT(); \
  }

#define TEST_LOG_DEBUG(str) \
  do { \
    std::cout << "LOG: " TEST_CONCAT(<<, str) \
    << " [" << __FILE__ << ", " << _test_name_ << ", line " \
          << __LINE__ << "] " << std::endl; \
  } \
  while(0)

#define TEST_PRINT_POSITION \
  " [" << __FILE__ << ", " << _test_name_ << \
  ", line " << __LINE__ << "]" \

#define TEST_ASSERT(x) \
  do { \
    if( !(x) ) { \
      ::gmb::test::error_count++; \
      std::cerr << "ASSERTION FAILED: \"" TEST_STRINGIFY(x) \
        << "\"" << TEST_PRINT_POSITION \
        << std::endl; \
    } \
  } \
  while(0)

#define TEST_EXPECT_THROW(x) \
  do { \
    try { \
      x; \
      ::gmb::test::error_count++; \
      std::cerr << "EXPECT EXCEPTION FAILED: \"" TEST_STRINGIFY(x) \
        << "\"" << TEST_PRINT_POSITION \
        << std::endl; \
    } \
    catch(...) { } \
  } \
  while(0)

#define THIS_(expr) \
  do { \
    char const* _expr_str_  = \
      TEST_STRINGIFY(expr); \
    if ([&]() -> bool { return (expr); }

#define _SHOULD_BE_(expected) \
  () != (expected) ) \
    { \
      ::gmb::test::error_count++; \
      std::cerr << "ASSERTION FAILED: \"" << \
        _expr_str_ << " != " << TEST_STRINGIFY(expected) \
        << "\"" \
        << TEST_PRINT_POSITION \
        << std::endl; \
    } \
  } \
  while(0)

#define _SHOULD_BE_TRUE \
  () == false ) \
    { \
      ::gmb::test::error_count++; \
      std::cerr << "ASSERTION FAILED: \"" << \
        _expr_str_ << "\"" \
        << TEST_PRINT_POSITION \
        << std::endl; \
    } \
  } \
  while(0)

#define _SHOULD_BE_FALSE \
  () == true ) \
    { \
      ::gmb::test::error_count++; \
      std::cerr << "ASSERTION FAILED: \"" << \
        _expr_str_ << "\"" \
        << TEST_PRINT_POSITION \
        << std::endl; \
    } \
  } \
  while(0)

#define TEST_EXPECT_NO_THROW(x) \
  do { \
    try { \
      x; \
    } \
    catch(...) { \
      ::gmb::test::error_count++; \
      std::cerr << "EXPECT NO EXCEPTION FAILED: " TEST_STRINGIFY(x) \
        << TEST_PRINT_POSITION \
        << std::endl; \
    } \
  } \
  while(0)

#define TEST_EXIT() \
  do { \
    if(::gmb::test::error_count > 0) { \
      std::cerr << ::gmb::test::error_count << " TESTS FAILED!" \
        << std::endl; \
      return 1; \
    } \
    else { \
      std::cout << "NO FAILURES" << std::endl; \
      return 0; \
    } \
  } \
  while(0)

#endif //TEST_HPP_INCLUDED
<commit_msg>Added static linkage to internal tracking variables<commit_after>/*
  The MIT License (MIT)

  Copyright (c) 2016 G. Beard

  Permission is hereby granted, free of charge, to any person obtaining a
  copy of this software and associated documentation files (the "Software"),
  to deal in the Software without restriction, including without limitation
  the rights to use, copy, modify, merge, publish, distribute, sublicense,
  and/or sell copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included
  in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  DEALINGS IN THE SOFTWARE.
*/
#ifndef TEST_HPP_INCLUDED
#define TEST_HPP_INCLUDED

#include <iostream>
#include <vector>
#include <tuple>

namespace gmb { namespace test
{
  static size_t error_count;
  using test_case_t = void(*)(char const*);
  static std::vector<std::pair<test_case_t, char const*>> list;
} }

#define TEST_STRINGIFY_IMPL(str) #str
#define TEST_STRINGIFY(str) TEST_STRINGIFY_IMPL(str)
#define TEST_CONCAT_IMPL(x, y) x##y
#define TEST_CONCAT(x, y) TEST_CONCAT_IMPL(x, y)

#define TEST_CASE(name) \
  void name(char const*); \
  struct name##_helper_t \
  { \
    name##_helper_t() \
    { \
      ::gmb::test::list.push_back(std::make_pair( \
        name, TEST_STRINGIFY(name))); \
    } \
  } name##_instance; \
  void name(char const* _test_name_)

#define DEFINE_TEST_MAIN \
  int main() \
  { \
    for(auto&& t : ::gmb::test::list) { \
      std::get<0>(t)(std::get<1>(t)); \
    } \
    TEST_EXIT(); \
  }

#define TEST_LOG_DEBUG(str) \
  do { \
    std::cout << "LOG: " TEST_CONCAT(<<, str) \
    << " [" << __FILE__ << ", " << _test_name_ << ", line " \
          << __LINE__ << "] " << std::endl; \
  } \
  while(0)

#define TEST_PRINT_POSITION \
  " [" << __FILE__ << ", " << _test_name_ << \
  ", line " << __LINE__ << "]" \

#define TEST_ASSERT(x) \
  do { \
    if( !(x) ) { \
      ::gmb::test::error_count++; \
      std::cerr << "ASSERTION FAILED: \"" TEST_STRINGIFY(x) \
        << "\"" << TEST_PRINT_POSITION \
        << std::endl; \
    } \
  } \
  while(0)

#define TEST_EXPECT_THROW(x) \
  do { \
    try { \
      x; \
      ::gmb::test::error_count++; \
      std::cerr << "EXPECT EXCEPTION FAILED: \"" TEST_STRINGIFY(x) \
        << "\"" << TEST_PRINT_POSITION \
        << std::endl; \
    } \
    catch(...) { } \
  } \
  while(0)

#define THIS_(expr) \
  do { \
    char const* _expr_str_  = \
      TEST_STRINGIFY(expr); \
    if ([&]() -> bool { return (expr); }

#define _SHOULD_BE_(expected) \
  () != (expected) ) \
    { \
      ::gmb::test::error_count++; \
      std::cerr << "ASSERTION FAILED: \"" << \
        _expr_str_ << " != " << TEST_STRINGIFY(expected) \
        << "\"" \
        << TEST_PRINT_POSITION \
        << std::endl; \
    } \
  } \
  while(0)

#define _SHOULD_BE_TRUE \
  () == false ) \
    { \
      ::gmb::test::error_count++; \
      std::cerr << "ASSERTION FAILED: \"" << \
        _expr_str_ << "\"" \
        << TEST_PRINT_POSITION \
        << std::endl; \
    } \
  } \
  while(0)

#define _SHOULD_BE_FALSE \
  () == true ) \
    { \
      ::gmb::test::error_count++; \
      std::cerr << "ASSERTION FAILED: \"" << \
        _expr_str_ << "\"" \
        << TEST_PRINT_POSITION \
        << std::endl; \
    } \
  } \
  while(0)

#define TEST_EXPECT_NO_THROW(x) \
  do { \
    try { \
      x; \
    } \
    catch(...) { \
      ::gmb::test::error_count++; \
      std::cerr << "EXPECT NO EXCEPTION FAILED: " TEST_STRINGIFY(x) \
        << TEST_PRINT_POSITION \
        << std::endl; \
    } \
  } \
  while(0)

#define TEST_EXIT() \
  do { \
    if(::gmb::test::error_count > 0) { \
      std::cerr << ::gmb::test::error_count << " TESTS FAILED!" \
        << std::endl; \
      return 1; \
    } \
    else { \
      std::cout << "NO FAILURES" << std::endl; \
      return 0; \
    } \
  } \
  while(0)

#endif //TEST_HPP_INCLUDED
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2012 The WebM project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "third_party/googletest/src/include/gtest/gtest.h"

#include "./vp9_rtcd.h"
#include "./vpx_config.h"
#include "./vpx_dsp_rtcd.h"
#include "test/acm_random.h"
#include "test/clear_system_state.h"
#include "test/register_state_check.h"
#include "vp9/common/vp9_blockd.h"
#include "vpx_mem/vpx_mem.h"

typedef void (*SubtractFunc)(int rows, int cols,
                             int16_t *diff_ptr, ptrdiff_t diff_stride,
                             const uint8_t *src_ptr, ptrdiff_t src_stride,
                             const uint8_t *pred_ptr, ptrdiff_t pred_stride);

namespace vp9 {

class VP9SubtractBlockTest : public ::testing::TestWithParam<SubtractFunc> {
 public:
  virtual void TearDown() {
    libvpx_test::ClearSystemState();
  }
};

using libvpx_test::ACMRandom;

TEST_P(VP9SubtractBlockTest, SimpleSubtract) {
  ACMRandom rnd(ACMRandom::DeterministicSeed());

  // FIXME(rbultje) split in its own file
  for (BLOCK_SIZE bsize = BLOCK_4X4; bsize < BLOCK_SIZES;
       bsize = static_cast<BLOCK_SIZE>(static_cast<int>(bsize) + 1)) {
    const int block_width = 4 * num_4x4_blocks_wide_lookup[bsize];
    const int block_height = 4 * num_4x4_blocks_high_lookup[bsize];
    int16_t *diff = reinterpret_cast<int16_t *>(
        vpx_memalign(16, sizeof(*diff) * block_width * block_height * 2));
    uint8_t *pred = reinterpret_cast<uint8_t *>(
        vpx_memalign(16, block_width * block_height * 2));
    uint8_t *src  = reinterpret_cast<uint8_t *>(
        vpx_memalign(16, block_width * block_height * 2));

    for (int n = 0; n < 100; n++) {
      for (int r = 0; r < block_height; ++r) {
        for (int c = 0; c < block_width * 2; ++c) {
          src[r * block_width * 2 + c] = rnd.Rand8();
          pred[r * block_width * 2 + c] = rnd.Rand8();
        }
      }

      GetParam()(block_height, block_width, diff, block_width,
                 src, block_width, pred, block_width);

      for (int r = 0; r < block_height; ++r) {
        for (int c = 0; c < block_width; ++c) {
          EXPECT_EQ(diff[r * block_width + c],
                    (src[r * block_width + c] -
                     pred[r * block_width + c])) << "r = " << r
                                                 << ", c = " << c
                                                 << ", bs = " << bsize;
        }
      }

      GetParam()(block_height, block_width, diff, block_width * 2,
                 src, block_width * 2, pred, block_width * 2);

      for (int r = 0; r < block_height; ++r) {
        for (int c = 0; c < block_width; ++c) {
          EXPECT_EQ(diff[r * block_width * 2 + c],
                    (src[r * block_width * 2 + c] -
                     pred[r * block_width * 2 + c])) << "r = " << r
                                                     << ", c = " << c
                                                     << ", bs = " << bsize;
        }
      }
    }
    vpx_free(diff);
    vpx_free(pred);
    vpx_free(src);
  }
}

INSTANTIATE_TEST_CASE_P(C, VP9SubtractBlockTest,
                        ::testing::Values(vpx_subtract_block_c));

#if HAVE_SSE2 && CONFIG_USE_X86INC
INSTANTIATE_TEST_CASE_P(SSE2, VP9SubtractBlockTest,
                        ::testing::Values(vpx_subtract_block_sse2));
#endif
#if HAVE_NEON
INSTANTIATE_TEST_CASE_P(NEON, VP9SubtractBlockTest,
                        ::testing::Values(vpx_subtract_block_neon));
#endif

}  // namespace vp9
<commit_msg>mips msa vpx subtract test added<commit_after>/*
 *  Copyright (c) 2012 The WebM project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "third_party/googletest/src/include/gtest/gtest.h"

#include "./vp9_rtcd.h"
#include "./vpx_config.h"
#include "./vpx_dsp_rtcd.h"
#include "test/acm_random.h"
#include "test/clear_system_state.h"
#include "test/register_state_check.h"
#include "vp9/common/vp9_blockd.h"
#include "vpx_mem/vpx_mem.h"

typedef void (*SubtractFunc)(int rows, int cols,
                             int16_t *diff_ptr, ptrdiff_t diff_stride,
                             const uint8_t *src_ptr, ptrdiff_t src_stride,
                             const uint8_t *pred_ptr, ptrdiff_t pred_stride);

namespace vp9 {

class VP9SubtractBlockTest : public ::testing::TestWithParam<SubtractFunc> {
 public:
  virtual void TearDown() {
    libvpx_test::ClearSystemState();
  }
};

using libvpx_test::ACMRandom;

TEST_P(VP9SubtractBlockTest, SimpleSubtract) {
  ACMRandom rnd(ACMRandom::DeterministicSeed());

  // FIXME(rbultje) split in its own file
  for (BLOCK_SIZE bsize = BLOCK_4X4; bsize < BLOCK_SIZES;
       bsize = static_cast<BLOCK_SIZE>(static_cast<int>(bsize) + 1)) {
    const int block_width = 4 * num_4x4_blocks_wide_lookup[bsize];
    const int block_height = 4 * num_4x4_blocks_high_lookup[bsize];
    int16_t *diff = reinterpret_cast<int16_t *>(
        vpx_memalign(16, sizeof(*diff) * block_width * block_height * 2));
    uint8_t *pred = reinterpret_cast<uint8_t *>(
        vpx_memalign(16, block_width * block_height * 2));
    uint8_t *src  = reinterpret_cast<uint8_t *>(
        vpx_memalign(16, block_width * block_height * 2));

    for (int n = 0; n < 100; n++) {
      for (int r = 0; r < block_height; ++r) {
        for (int c = 0; c < block_width * 2; ++c) {
          src[r * block_width * 2 + c] = rnd.Rand8();
          pred[r * block_width * 2 + c] = rnd.Rand8();
        }
      }

      GetParam()(block_height, block_width, diff, block_width,
                 src, block_width, pred, block_width);

      for (int r = 0; r < block_height; ++r) {
        for (int c = 0; c < block_width; ++c) {
          EXPECT_EQ(diff[r * block_width + c],
                    (src[r * block_width + c] -
                     pred[r * block_width + c])) << "r = " << r
                                                 << ", c = " << c
                                                 << ", bs = " << bsize;
        }
      }

      GetParam()(block_height, block_width, diff, block_width * 2,
                 src, block_width * 2, pred, block_width * 2);

      for (int r = 0; r < block_height; ++r) {
        for (int c = 0; c < block_width; ++c) {
          EXPECT_EQ(diff[r * block_width * 2 + c],
                    (src[r * block_width * 2 + c] -
                     pred[r * block_width * 2 + c])) << "r = " << r
                                                     << ", c = " << c
                                                     << ", bs = " << bsize;
        }
      }
    }
    vpx_free(diff);
    vpx_free(pred);
    vpx_free(src);
  }
}

INSTANTIATE_TEST_CASE_P(C, VP9SubtractBlockTest,
                        ::testing::Values(vpx_subtract_block_c));

#if HAVE_SSE2 && CONFIG_USE_X86INC
INSTANTIATE_TEST_CASE_P(SSE2, VP9SubtractBlockTest,
                        ::testing::Values(vpx_subtract_block_sse2));
#endif
#if HAVE_NEON
INSTANTIATE_TEST_CASE_P(NEON, VP9SubtractBlockTest,
                        ::testing::Values(vpx_subtract_block_neon));
#endif
#if HAVE_MSA
INSTANTIATE_TEST_CASE_P(MSA, VP9SubtractBlockTest,
                        ::testing::Values(vpx_subtract_block_msa));
#endif

}  // namespace vp9
<|endoftext|>


<commit_before>#include "mytablemodel.h"

int MyTableModel::rowCount(const QModelIndex &parent) const
{
    return m_data.size();
}

int MyTableModel::columnCount(const QModelIndex &parent) const
{
    return 2;
}

QVariant MyTableModel::data(const QModelIndex &index, int role) const
{
    if (role != Qt::DisplayRole)
        return QVariant();

    Record const& dataElem = m_data[index.row()];

    if (index.column() == 0)
        return QVariant(dataElem.label);
    else
        return QVariant(dataElem.number);
}

bool MyTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    return false;
}

Qt::ItemFlags MyTableModel::flags(const QModelIndex &index) const
{
    return QAbstractTableModel::flags(index);
}

void MyTableModel::insertRow()
{
    m_data.push_back({ "label", 0 });
    emit layoutChanged();
}
<commit_msg>Edit support<commit_after>#include "mytablemodel.h"

int MyTableModel::rowCount(const QModelIndex &parent) const
{
    return m_data.size();
}

int MyTableModel::columnCount(const QModelIndex &parent) const
{
    return 2;
}

QVariant MyTableModel::data(const QModelIndex &index, int role) const
{
    if (role != Qt::DisplayRole)
        return QVariant();

    Record const& dataElem = m_data[index.row()];

    if (index.column() == 0)
        return QVariant(dataElem.label);
    else
        return QVariant(dataElem.number);
}

bool MyTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (role != Qt::EditRole)
        return QAbstractTableModel::setData(index, value,role);

    Record &dataElem = m_data[index.row()];

    if (index.column() == 0)
        dataElem.label = value.toString();
    else
        dataElem.number = value.toInt();

    emit layoutChanged();
    return true;
}

Qt::ItemFlags MyTableModel::flags(const QModelIndex &index) const
{
    return QAbstractTableModel::flags(index) | Qt::ItemIsEditable;
}

void MyTableModel::insertRow()
{
    m_data.push_back({ "label", 0 });
    emit layoutChanged();
}
<|endoftext|>


<commit_before>/**
 * QueryProcessor.cc
 *
 * Process user queries.
 *
 * Copyright (c) 2008 Linas Vepstas <linas@linas.org>
 */
#include <stdio.h>

#include "AtomSpace.h"
#include "CogServer.h"
#include "Foreach.h"
#include "MindAgent.h"
#include "Node.h"
#include "PatternMatch.h"
#include "QueryProcessor.h"

using namespace opencog;

QueryProcessor::QueryProcessor(void)
{
}

QueryProcessor::~QueryProcessor()
{
}

void QueryProcessor::run(CogServer *server)
{
	AtomSpace *as = server->getAtomSpace();
	// Handle h = as->getHandle(qtype, "test");

	// Look for recently asserted assertions.
	Type atype = ClassServer::getType("AssertionLink");
	std::list<Handle> asrt_list;
	as->getHandleSet(back_inserter(asrt_list), atype, NULL);

	// Loop over all recent assertions, and take care of them.
	while(!asrt_list.empty())
	{
		Handle h = asrt_list.front();
		do_assertion(h);
		asrt_list.pop_front();
		if (h) as->removeAtom(h);
	}

	/* XXX HACK ALERT -- no scheduling, so just sleep */
	usleep(1000000);  // 1 second
	usleep(10000);  // 10 millisecs == 100HZ
}

/**
 * Set pointer to Node, if the node name is "match_name".
 */
bool QueryProcessor::match_node_name(Atom *arel)
{
	Node *n = dynamic_cast<Node *>(arel);
	if (n)
	{
		const std::string& name = n->getName();
		if (0 == strcmp(name.c_str(), match_name))
		{
			node = n;
			return true;
		}
	}
	return false;
}

/**
 * Search for queries
 */
bool QueryProcessor::check_for_query(Handle rel)
{
	match_name = "_$qVar";
	node = NULL;
	foreach_outgoing_atom(rel, &QueryProcessor::match_node_name, this);
	if (node)
	{
		printf ("found query its %s\n", node->toString().c_str());
		varlist.push_back(TLB::getHandle(node));
	}
}

/**
 * Process an assertion fed into the system.
 * Currently, this ignores all assertions that are not queries.
 */
void QueryProcessor::do_assertion(Handle h)
{
	printf ("duuuude found assertion handle=%p\n", h);

	// Look for unbound query variables
	varlist.clear();
	foreach_outgoing_handle(h, &QueryProcessor::check_for_query, this);

	// If a query, try to answer it.
	if (0 != varlist.size())
	{
		PatternMatch pm;
		pm.match(h, varlist);
	}
}

/* ======================= END OF FILE ==================== */
<commit_msg>whoops, bug fix<commit_after>/**
 * QueryProcessor.cc
 *
 * Process user queries.
 *
 * Copyright (c) 2008 Linas Vepstas <linas@linas.org>
 */
#include <stdio.h>

#include "AtomSpace.h"
#include "CogServer.h"
#include "Foreach.h"
#include "MindAgent.h"
#include "Node.h"
#include "PatternMatch.h"
#include "QueryProcessor.h"

using namespace opencog;

QueryProcessor::QueryProcessor(void)
{
}

QueryProcessor::~QueryProcessor()
{
}

void QueryProcessor::run(CogServer *server)
{
	AtomSpace *as = server->getAtomSpace();
	// Handle h = as->getHandle(qtype, "test");

	// Look for recently asserted assertions.
	Type atype = ClassServer::getType("AssertionLink");
	std::list<Handle> asrt_list;
	as->getHandleSet(back_inserter(asrt_list), atype, NULL);

	// Loop over all recent assertions, and take care of them.
	while(!asrt_list.empty())
	{
		Handle h = asrt_list.front();
		do_assertion(h);
		asrt_list.pop_front();
		if (h) as->removeAtom(h);
	}

	/* XXX HACK ALERT -- no scheduling, so just sleep */
	usleep(1000000);  // 1 second
	usleep(10000);  // 10 millisecs == 100HZ
}

/**
 * Set pointer to Node, if the node name is "match_name".
 */
bool QueryProcessor::match_node_name(Atom *atom)
{
	Node *n = dynamic_cast<Node *>(atom);
	if (n)
	{
		const std::string& name = n->getName();
		if (0 == strcmp(name.c_str(), match_name))
		{
			node = n;
			return true;
		}
	}
	return false;
}

/**
 * Search for queries
 */
bool QueryProcessor::check_for_query(Handle rel)
{
	match_name = "_$qVar";
	node = NULL;
	foreach_outgoing_atom(rel, &QueryProcessor::match_node_name, this);
	if (node)
	{
		// printf ("found query its %s\n", node->toString().c_str());
		varlist.push_back(TLB::getHandle(node));
	}
	return true;
}

/**
 * Process an assertion fed into the system.
 * Currently, this ignores all assertions that are not queries.
 */
void QueryProcessor::do_assertion(Handle h)
{
	printf ("duuuude found assertion handle=%p\n", h);

	// Look for unbound query variables
	varlist.clear();
	foreach_outgoing_handle(h, &QueryProcessor::check_for_query, this);

	// If a query, try to answer it.
	if (0 != varlist.size())
	{
		PatternMatch pm;
		pm.match(h, varlist);
	}
}

/* ======================= END OF FILE ==================== */
<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////////////
// Name:        copy_to_clipboard.cpp
// Author:      jean-pierre Charras
// Created:     18 aug 2006
// Licence:   License GNU
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
#pragma hdrstop
#endif

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

#include <ctype.h>
#include "wx/metafile.h"
#include "fctsys.h"

#include "common.h"
#include "id.h"

extern BASE_SCREEN * ActiveScreen;

static const bool s_PlotBlackAndWhite = FALSE;
static const bool Print_Sheet_Ref = TRUE;

static bool DrawPage(WinEDA_DrawPanel * panel);

/************************************************************/
void WinEDA_DrawFrame::CopyToClipboard(wxCommandEvent& event)
/************************************************************/
/* calls the function to copy the current page or the current bock to the clipboard
*/
{
	DrawPage(DrawPanel);

	if(  event.GetId() == ID_GEN_COPY_BLOCK_TO_CLIPBOARD )
	{
		if (GetScreen()->BlockLocate.m_Command != BLOCK_IDLE)
			DrawPanel->SetCursor(wxCursor(DrawPanel->m_PanelCursor = DrawPanel->m_PanelDefaultCursor) );

		if( DrawPanel->ManageCurseur && DrawPanel->ForceCloseManageCurseur )
		{
		wxClientDC dc(DrawPanel);
			DrawPanel->PrepareGraphicContext(&dc);
			DrawPanel->ForceCloseManageCurseur(DrawPanel, &dc);
		}
	}
}

/*****************************************************************/
bool DrawPage(WinEDA_DrawPanel * panel)
/*****************************************************************/
/* copy the current page or block to the clipboard ,
	to export drawings to other applications (word processing ...)
	Thi is not suitable for copy command within eeschema or pcbnew
*/
{
bool success = TRUE;

#ifdef __WINDOWS__
int tmpzoom;
wxPoint tmp_startvisu;
wxPoint old_org;
wxPoint DrawOffset;	// Offset de trace
int ClipboardSizeX, ClipboardSizeY;
bool DrawBlock = FALSE;
wxRect DrawArea;

	/* scale is the ratio resolution/internal units */
	float scale = 82.0 / panel->m_Parent->m_InternalUnits;

	if ( ActiveScreen->BlockLocate.m_Command != BLOCK_IDLE )
	{
		DrawBlock = TRUE;
		DrawArea.SetX((int)(ActiveScreen->BlockLocate.GetX()) );
		DrawArea.SetY((int)(ActiveScreen->BlockLocate.GetY()));
		DrawArea.SetWidth((int)(ActiveScreen->BlockLocate.GetWidth()));
		DrawArea.SetHeight((int)(ActiveScreen->BlockLocate.GetHeight()));
	}

	/* modification des cadrages et reglages locaux */
	tmp_startvisu = ActiveScreen->m_StartVisu;
	tmpzoom = ActiveScreen->GetZoom();
	old_org = ActiveScreen->m_DrawOrg;
	ActiveScreen->m_DrawOrg.x = ActiveScreen->m_DrawOrg.y = 0;
	ActiveScreen->m_StartVisu.x = ActiveScreen->m_StartVisu.y = 0;

	ActiveScreen->SetZoom(1);

wxMetafileDC dc/*(wxT(""), DrawArea.GetWidth(), DrawArea.GetHeight())*/;

	if ( ! dc.Ok() )
	{
		DisplayError(NULL, wxT("CopyToClipboard: DrawPage error: wxMetafileDC not OK"));
		success = FALSE;
	}

	else
	{
	EDA_Rect tmp = panel->m_ClipBox;
		GRResetPenAndBrush(&dc);
		GRForceBlackPen(s_PlotBlackAndWhite);
		g_IsPrinting = TRUE;
		dc.SetUserScale(scale, scale);
		ClipboardSizeX = dc.MaxX() + 10;
		ClipboardSizeY = dc.MaxY() + 10;
		panel->m_ClipBox.SetX(0);panel->m_ClipBox.SetY(0);
		panel->m_ClipBox.SetWidth(0x7FFFFF0); panel->m_ClipBox.SetHeight(0x7FFFFF0);

		if ( DrawBlock )
		{
			dc.SetClippingRegion( DrawArea );
		}
		panel->PrintPage(&dc, Print_Sheet_Ref, -1);
		g_IsPrinting = FALSE;
		panel->m_ClipBox = tmp;
		wxMetafile *mf = dc.Close();
		if (mf)
		{
			success = mf->SetClipboard(ClipboardSizeX, ClipboardSizeY);
			delete mf;
		}
	}

	GRForceBlackPen(FALSE);
	SetPenMinWidth(1);

	ActiveScreen->m_StartVisu = tmp_startvisu;
	ActiveScreen->m_DrawOrg = old_org;
	ActiveScreen->SetZoom(tmpzoom);
#endif

	return success;
}

<commit_msg>beautify<commit_after>/////////////////////////////////////////////////////////////////////////////

// Name:        copy_to_clipboard.cpp
// Author:      jean-pierre Charras
// Created:     18 aug 2006
// Licence:   License GNU
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
#pragma hdrstop
#endif

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

#include <ctype.h>
#include "wx/metafile.h"
#include "fctsys.h"

#include "common.h"
#include "id.h"

extern BASE_SCREEN* ActiveScreen;

static const bool   s_PlotBlackAndWhite = FALSE;
static const bool   Print_Sheet_Ref = TRUE;

static bool DrawPage( WinEDA_DrawPanel* panel );

/************************************************************/
void WinEDA_DrawFrame::CopyToClipboard( wxCommandEvent& event )
/************************************************************/

/* calls the function to copy the current page or the current bock to the clipboard
 */
{
    DrawPage( DrawPanel );

    if(  event.GetId() == ID_GEN_COPY_BLOCK_TO_CLIPBOARD )
    {
        if( GetScreen()->BlockLocate.m_Command != BLOCK_IDLE )
            DrawPanel->SetCursor( wxCursor( DrawPanel->m_PanelCursor =
                        DrawPanel->m_PanelDefaultCursor ) );

        if( DrawPanel->ManageCurseur && DrawPanel->ForceCloseManageCurseur )
        {
            wxClientDC dc( DrawPanel );

            DrawPanel->PrepareGraphicContext( &dc );
            DrawPanel->ForceCloseManageCurseur( DrawPanel, &dc );
        }
    }
}

/*****************************************************************/
bool DrawPage( WinEDA_DrawPanel* panel )
/*****************************************************************/

/* copy the current page or block to the clipboard ,
 * to export drawings to other applications (word processing ...)
 * Thi is not suitable for copy command within eeschema or pcbnew
 */
{
    bool    success = TRUE;

#ifdef __WINDOWS__
    int     tmpzoom;
    wxPoint tmp_startvisu;
    wxPoint old_org;
    wxPoint DrawOffset; // Offset de trace
    int     ClipboardSizeX, ClipboardSizeY;
    bool    DrawBlock = FALSE;
    wxRect  DrawArea;

    /* scale is the ratio resolution/internal units */
    float   scale = 82.0 / panel->m_Parent->m_InternalUnits;

    if( ActiveScreen->BlockLocate.m_Command != BLOCK_IDLE )
    {
        DrawBlock = TRUE;
        DrawArea.SetX( (int) ( ActiveScreen->BlockLocate.GetX() ) );
        DrawArea.SetY( (int) ( ActiveScreen->BlockLocate.GetY() ) );
        DrawArea.SetWidth( (int) ( ActiveScreen->BlockLocate.GetWidth() ) );
        DrawArea.SetHeight( (int) ( ActiveScreen->BlockLocate.GetHeight() ) );
    }

    /* modification des cadrages et reglages locaux */
    tmp_startvisu = ActiveScreen->m_StartVisu;
    tmpzoom = ActiveScreen->GetZoom();
    old_org = ActiveScreen->m_DrawOrg;
    ActiveScreen->m_DrawOrg.x   = ActiveScreen->m_DrawOrg.y = 0;
    ActiveScreen->m_StartVisu.x = ActiveScreen->m_StartVisu.y = 0;

    ActiveScreen->SetZoom( 1 );

    wxMetafileDC dc /*(wxT(""), DrawArea.GetWidth(), DrawArea.GetHeight())*/;

    if( !dc.Ok() )
    {
        DisplayError( NULL, wxT( "CopyToClipboard: DrawPage error: wxMetafileDC not OK" ) );
        success = FALSE;
    }
    else
    {
        EDA_Rect tmp = panel->m_ClipBox;
        GRResetPenAndBrush( &dc );
        GRForceBlackPen( s_PlotBlackAndWhite );
        g_IsPrinting = TRUE;
        dc.SetUserScale( scale, scale );
        ClipboardSizeX = dc.MaxX() + 10;
        ClipboardSizeY = dc.MaxY() + 10;
        panel->m_ClipBox.SetX( 0 ); panel->m_ClipBox.SetY( 0 );
        panel->m_ClipBox.SetWidth( 0x7FFFFF0 ); panel->m_ClipBox.SetHeight( 0x7FFFFF0 );

        if( DrawBlock )
        {
            dc.SetClippingRegion( DrawArea );
        }
        panel->PrintPage( &dc, Print_Sheet_Ref, -1 );
        g_IsPrinting     = FALSE;
        panel->m_ClipBox = tmp;
        wxMetafile* mf = dc.Close();
        if( mf )
        {
            success = mf->SetClipboard( ClipboardSizeX, ClipboardSizeY );
            delete mf;
        }
    }

    GRForceBlackPen( FALSE );
    SetPenMinWidth( 1 );

    ActiveScreen->m_StartVisu = tmp_startvisu;
    ActiveScreen->m_DrawOrg   = old_org;
    ActiveScreen->SetZoom( tmpzoom );
#endif

    return success;
}
<|endoftext|>