<commit_before>// inc order weird for these guys
#include <GL/glew.h>
#include <GLFW/glfw3.h>

//%deps(opengl, glfw)

#include "viewer/gl_aliases.hh"
#include "viewer/primitives/simple_geometry_primitives.hh"
#include "viewer/window_3d.hh"
#include "viewer/window_manager.hh"

#include "eigen_helpers.hh"

#include <map>
#include <thread>

//TODO
#include "viewer/text/gl_text.hh"

namespace viewer {
namespace {

void apply_view(const OrbitCamera &view, bool show_axes) {
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  glTransform(view.camera_from_anchor());
  glScaled(view.zoom(), view.zoom(), view.zoom());
  if (show_axes) {
    draw_axes({SE3(), 0.1 / view.zoom(), 3.0});
  }

  glTransform(view.anchor_from_world());
  if (show_axes) {
    draw_axes({SE3(), 0.2 / view.zoom(), 3.0});
  }
}

void prepare_to_render() {
  //
  // Flag soup
  //

  glShadeModel(GL_SMOOTH);

  // Check depth when rendering
  glEnable(GL_DEPTH_TEST);

  // Turn on lighting
  // glEnable(GL_LIGHTING);

  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  glEnable(GL_BLEND);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  glEnable(GL_LINE_SMOOTH);
  glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);

  glEnable(GL_MULTISAMPLE);
}

void set_perspective(const GlSize &gl_size, bool ortho = false) {
  glViewport(0, 0, gl_size.width, gl_size.height);
  glMatrixMode(GL_PROJECTION);

  glLoadIdentity();

  constexpr double NEAR_CLIP = 0.001;
  constexpr double FAR_CLIP = 1000.0;
  const double aspect_ratio =
      (static_cast<double>(gl_size.width) / static_cast<double>(gl_size.height));
  if (ortho) {
    glOrtho(-aspect_ratio, aspect_ratio, -1.0, 1.0, NEAR_CLIP, FAR_CLIP);
  } else {
    constexpr double FOV = 60.0;
    gluPerspective(FOV, aspect_ratio, NEAR_CLIP, FAR_CLIP);
  }
}

}  // namespace

Window3D::Window3D(const GlSize &gl_size) : gl_size_(gl_size) {
  set_view_preset(ViewSetting::STANDARD);
}

void Window3D::set_view_preset(const ViewSetting &setting) {
  switch (setting) {
    case ViewSetting::STANDARD: {
      set_target_from_world(SE3(SO3::exp(Eigen::Vector3d(-3.1415 * 0.5, 0.0, 0.0)),
                                Eigen::Vector3d::Zero()));
      break;
    }
    case ViewSetting::CAMERA: {
      set_target_from_world(
          SE3(SO3::exp(Eigen::Vector3d::Zero()), Eigen::Vector3d::Zero()));
      break;
    }
  }
}

void Window3D::spin_until_step() {
  while (!should_step_ && !should_continue_ && !should_close()) {
    std::this_thread::sleep_for(std::chrono::milliseconds(10));
  }

  if (should_continue_ && !should_close()) {
    std::this_thread::sleep_for(std::chrono::milliseconds(continue_ms_));
  }

  if (should_step_) {
    should_step_ = false;
  }
}

void Window3D::on_key(int key, int scancode, int action, int mods) {
  const std::lock_guard<std::mutex> lk(behavior_mutex_);

  const char key_char = static_cast<char>(key);

  if (action == GLFW_PRESS) {
    //
    // Toggling
    //
    if (key_mappings_.count(key_char) != 0) {
      const std::string toggle_name = key_mappings_.at(key_char);
      toggles_[toggle_name] = !toggles_[toggle_name];
      const bool new_toggle_state = toggles_[toggle_name];
      for (const auto &toggle_callback : toggle_callbacks_[toggle_name]) {
        toggle_callback(new_toggle_state);
      }
    }

    //
    // Navigation UI management
    //
    if (key_char == 'N') {
      should_step_ = true;
    }

    if (key_char == 'C') {
      should_continue_ = !should_continue_;
    }

    if (key_char == 'O') {
      orthogonal_projection_ = !orthogonal_projection_;
    }
    if (key_char == 'H') {
      hide_axes_ = !hide_axes_;
    }
  }
}
void Window3D::on_mouse_button(int button, int action, int mods) {
  const std::lock_guard<std::mutex> lk(behavior_mutex_);

  const auto current_mouse_pos = mouse_pos();
  // const auto ray = projection_.unproject(current_mouse_pos);

  mouse_pos_last_click_ = current_mouse_pos;
}

void Window3D::on_mouse_move(const WindowPoint &mouse_pos) {
  const std::lock_guard<std::mutex> lk(behavior_mutex_);

  const bool shift = held_keys().count(GLFW_KEY_LEFT_SHIFT) == 1
                         ? held_keys().at(GLFW_KEY_LEFT_SHIFT)
                         : false;

  const bool left = left_mouse_held() && !shift;
  const bool right = right_mouse_held() || (shift && left_mouse_held());

  // if (left || right) {
  // glfwSetInputMode(get_window(), GLFW_CURSOR, GLFW_CURSOR_DISABLED);
  // } else {
  // glfwSetInputMode(get_window(), GLFW_CURSOR, GLFW_CURSOR_NORMAL);
  // }

  view_.apply_mouse(mouse_pos, mouse_pos_last_click_, left, right);

  const auto ray = projection_.unproject(mouse_pos);
  callback_manager_.handle_callbacks(ray);

  if (left || right) {
    mouse_pos_last_click_ = mouse_pos;
  }
}

void Window3D::on_scroll(const double amount) {
  const std::lock_guard<std::mutex> lk(behavior_mutex_);
  view_.apply_scroll(amount);
}

void Window3D::resize(const GlSize &gl_size) {
  const std::lock_guard<std::mutex> lk(behavior_mutex_);

  glViewport(0, 0, gl_size.width, gl_size.height);
  gl_size_ = gl_size;
}

void Window3D::draw_all_primitives() const {
  for (const auto &primitive : primitives_) {
    primitive->draw();
  }
}

void Window3D::render() {
  const std::lock_guard<std::mutex> lk(behavior_mutex_);

  //
  // Render cameras
  //
  for (const auto &camera : cameras_) {
    prepare_to_render();
    camera->prepare_view();
    draw_all_primitives();
    camera->draw();
  }

  {  // Render main scene
    set_perspective(gl_size_, orthogonal_projection_);
    prepare_to_render();
    apply_view(view_, !hide_axes_);
    projection_ = Projection::get_from_current();
    draw_all_primitives();
  }

  const auto strlib = create_text_library();
  write_string("Jagop", strlib);

  const double t_now = glfwGetTime();

  const double dt = std::max(t_now - last_update_time_, 0.02);
  view_.apply_keys(held_keys(), dt);
  view_ = view_.simulate(dt);
  last_update_time_ = t_now;

  glFinish();
}  // namespace viewer

namespace {
struct Window3DGlobalState {
  std::map<std::string, std::shared_ptr<Window3D>> windows;
};

Window3DGlobalState window_3d_state;

Window3DGlobalState &get_global_state() {
  return window_3d_state;
}
}  // namespace

std::shared_ptr<Window3D> get_window3d(const std::string &title) {
  const auto it = get_global_state().windows.find(title);
  if (it != get_global_state().windows.end()) {
    return it->second;
  } else {
    const GlSize gl_size(640, 640);
    auto window = std::make_shared<Window3D>(gl_size);
    get_global_state().windows[title] = window;
    WindowManager::register_window(gl_size, window, title);
    return window;
  }
}
}  // namespace viewer
<commit_msg>More str<commit_after>// inc order weird for these guys
#include <GL/glew.h>
#include <GLFW/glfw3.h>

//%deps(opengl, glfw)

#include "viewer/gl_aliases.hh"
#include "viewer/primitives/simple_geometry_primitives.hh"
#include "viewer/window_3d.hh"
#include "viewer/window_manager.hh"

#include "eigen_helpers.hh"

#include <map>
#include <thread>

//TODO
#include "viewer/text/gl_text.hh"

namespace viewer {
namespace {

void apply_view(const OrbitCamera &view, bool show_axes) {
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  glTransform(view.camera_from_anchor());
  glScaled(view.zoom(), view.zoom(), view.zoom());
  if (show_axes) {
    draw_axes({SE3(), 0.1 / view.zoom(), 3.0});
  }

  glTransform(view.anchor_from_world());
  if (show_axes) {
    draw_axes({SE3(), 0.2 / view.zoom(), 3.0});
  }
}

void prepare_to_render() {
  //
  // Flag soup
  //

  glShadeModel(GL_SMOOTH);

  // Check depth when rendering
  glEnable(GL_DEPTH_TEST);

  // Turn on lighting
  // glEnable(GL_LIGHTING);

  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  glEnable(GL_BLEND);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  glEnable(GL_LINE_SMOOTH);
  glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);

  glEnable(GL_MULTISAMPLE);
}

void set_perspective(const GlSize &gl_size, bool ortho = false) {
  glViewport(0, 0, gl_size.width, gl_size.height);
  glMatrixMode(GL_PROJECTION);

  glLoadIdentity();

  constexpr double NEAR_CLIP = 0.001;
  constexpr double FAR_CLIP = 1000.0;
  const double aspect_ratio =
      (static_cast<double>(gl_size.width) / static_cast<double>(gl_size.height));
  if (ortho) {
    glOrtho(-aspect_ratio, aspect_ratio, -1.0, 1.0, NEAR_CLIP, FAR_CLIP);
  } else {
    constexpr double FOV = 60.0;
    gluPerspective(FOV, aspect_ratio, NEAR_CLIP, FAR_CLIP);
  }
}

}  // namespace

Window3D::Window3D(const GlSize &gl_size) : gl_size_(gl_size) {
  set_view_preset(ViewSetting::STANDARD);
}

void Window3D::set_view_preset(const ViewSetting &setting) {
  switch (setting) {
    case ViewSetting::STANDARD: {
      set_target_from_world(SE3(SO3::exp(Eigen::Vector3d(-3.1415 * 0.5, 0.0, 0.0)),
                                Eigen::Vector3d::Zero()));
      break;
    }
    case ViewSetting::CAMERA: {
      set_target_from_world(
          SE3(SO3::exp(Eigen::Vector3d::Zero()), Eigen::Vector3d::Zero()));
      break;
    }
  }
}

void Window3D::spin_until_step() {
  while (!should_step_ && !should_continue_ && !should_close()) {
    std::this_thread::sleep_for(std::chrono::milliseconds(10));
  }

  if (should_continue_ && !should_close()) {
    std::this_thread::sleep_for(std::chrono::milliseconds(continue_ms_));
  }

  if (should_step_) {
    should_step_ = false;
  }
}

void Window3D::on_key(int key, int scancode, int action, int mods) {
  const std::lock_guard<std::mutex> lk(behavior_mutex_);

  const char key_char = static_cast<char>(key);

  if (action == GLFW_PRESS) {
    //
    // Toggling
    //
    if (key_mappings_.count(key_char) != 0) {
      const std::string toggle_name = key_mappings_.at(key_char);
      toggles_[toggle_name] = !toggles_[toggle_name];
      const bool new_toggle_state = toggles_[toggle_name];
      for (const auto &toggle_callback : toggle_callbacks_[toggle_name]) {
        toggle_callback(new_toggle_state);
      }
    }

    //
    // Navigation UI management
    //
    if (key_char == 'N') {
      should_step_ = true;
    }

    if (key_char == 'C') {
      should_continue_ = !should_continue_;
    }

    if (key_char == 'O') {
      orthogonal_projection_ = !orthogonal_projection_;
    }
    if (key_char == 'H') {
      hide_axes_ = !hide_axes_;
    }
  }
}
void Window3D::on_mouse_button(int button, int action, int mods) {
  const std::lock_guard<std::mutex> lk(behavior_mutex_);

  const auto current_mouse_pos = mouse_pos();
  // const auto ray = projection_.unproject(current_mouse_pos);

  mouse_pos_last_click_ = current_mouse_pos;
}

void Window3D::on_mouse_move(const WindowPoint &mouse_pos) {
  const std::lock_guard<std::mutex> lk(behavior_mutex_);

  const bool shift = held_keys().count(GLFW_KEY_LEFT_SHIFT) == 1
                         ? held_keys().at(GLFW_KEY_LEFT_SHIFT)
                         : false;

  const bool left = left_mouse_held() && !shift;
  const bool right = right_mouse_held() || (shift && left_mouse_held());

  // if (left || right) {
  // glfwSetInputMode(get_window(), GLFW_CURSOR, GLFW_CURSOR_DISABLED);
  // } else {
  // glfwSetInputMode(get_window(), GLFW_CURSOR, GLFW_CURSOR_NORMAL);
  // }

  view_.apply_mouse(mouse_pos, mouse_pos_last_click_, left, right);

  const auto ray = projection_.unproject(mouse_pos);
  callback_manager_.handle_callbacks(ray);

  if (left || right) {
    mouse_pos_last_click_ = mouse_pos;
  }
}

void Window3D::on_scroll(const double amount) {
  const std::lock_guard<std::mutex> lk(behavior_mutex_);
  view_.apply_scroll(amount);
}

void Window3D::resize(const GlSize &gl_size) {
  const std::lock_guard<std::mutex> lk(behavior_mutex_);

  glViewport(0, 0, gl_size.width, gl_size.height);
  gl_size_ = gl_size;
}

void Window3D::draw_all_primitives() const {
  for (const auto &primitive : primitives_) {
    primitive->draw();
  }
}

void Window3D::render() {
  const std::lock_guard<std::mutex> lk(behavior_mutex_);

  //
  // Render cameras
  //
  for (const auto &camera : cameras_) {
    prepare_to_render();
    camera->prepare_view();
    draw_all_primitives();
    camera->draw();
  }

  {  // Render main scene
    set_perspective(gl_size_, orthogonal_projection_);
    prepare_to_render();
    apply_view(view_, !hide_axes_);
    projection_ = Projection::get_from_current();
    draw_all_primitives();
  }

  // const auto strlib = create_text_library();
  // write_string("Jagop: Analytical 240.599", strlib);

  const double t_now = glfwGetTime();

  const double dt = std::max(t_now - last_update_time_, 0.02);
  view_.apply_keys(held_keys(), dt);
  view_ = view_.simulate(dt);
  last_update_time_ = t_now;

  glFinish();
}  // namespace viewer

namespace {
struct Window3DGlobalState {
  std::map<std::string, std::shared_ptr<Window3D>> windows;
};

Window3DGlobalState window_3d_state;

Window3DGlobalState &get_global_state() {
  return window_3d_state;
}
}  // namespace

std::shared_ptr<Window3D> get_window3d(const std::string &title) {
  const auto it = get_global_state().windows.find(title);
  if (it != get_global_state().windows.end()) {
    return it->second;
  } else {
    const GlSize gl_size(640, 640);
    auto window = std::make_shared<Window3D>(gl_size);
    get_global_state().windows[title] = window;
    WindowManager::register_window(gl_size, window, title);
    return window;
  }
}
}  // namespace viewer
<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#ifdef SD_DLLIMPLEMENTATION
#undef SD_DLLIMPLEMENTATION
#endif

#include <svx/svxids.hrc>
#include <svx/dlgutil.hxx>
#ifndef _SFXITEMPOOL_HXX //autogen
#include <svtools/itempool.hxx>
#endif
#ifndef _AEITEM_HXX //autogen
#include <svtools/aeitem.hxx>
#endif

#include "dlgsnap.hrc"
#include "sdattr.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#include "sdresid.hxx"
#include "drawdoc.hxx"
#include "dlgsnap.hxx"

/*************************************************************************
|*
|* Dialog zum Einstellen des Rasters (wohl kaum ESO!)
|*
\************************************************************************/

SdSnapLineDlg::SdSnapLineDlg(
    ::Window* pWindow,
    const SfxItemSet& rInAttrs,
    ::sd::View* pView)
    : ModalDialog (pWindow, SdResId(DLG_SNAPLINE)),
      aFlPos      (this, SdResId(FL_POSITION)),
      aFtX        (this, SdResId(FT_X)),
      aMtrFldX    (this, SdResId(MTR_FLD_X)),
      aFtY        (this, SdResId(FT_Y)),
      aMtrFldY    (this, SdResId(MTR_FLD_Y)),
      aFlDir      (this, SdResId(FL_DIRECTION)),
      aRbPoint    (this, SdResId(RB_POINT)),
      aRbVert     (this, SdResId(RB_VERTICAL)),
      aRbHorz     (this, SdResId(RB_HORIZONTAL)),
      aBtnOK      (this, SdResId(BTN_OK)),
      aBtnCancel  (this, SdResId(BTN_CANCEL)),
      aBtnHelp    (this, SdResId(BTN_HELP)),
      aBtnDelete  (this, SdResId(BTN_DELETE)),
      eUIUnit(pView->GetDoc()->GetUIUnit()),
      aUIScale(pView->GetDoc()->GetUIScale())
{
    aRbPoint.SetModeRadioImage( Image( SdResId( BMP_POINT_H ) ), BMP_COLOR_HIGHCONTRAST );
    aRbVert.SetModeRadioImage( Image( SdResId( BMP_VERTICAL_H ) ), BMP_COLOR_HIGHCONTRAST );
    aRbHorz.SetModeRadioImage( Image( SdResId( BMP_HORIZONTAL_H ) ), BMP_COLOR_HIGHCONTRAST );

    FreeResource();

    aRbHorz.SetClickHdl(LINK(this, SdSnapLineDlg, ClickHdl));
    aRbVert.SetClickHdl(LINK(this, SdSnapLineDlg, ClickHdl));
    aRbPoint.SetClickHdl(LINK(this, SdSnapLineDlg, ClickHdl));

    aBtnDelete.SetClickHdl(LINK(this, SdSnapLineDlg, ClickHdl));

    SetFieldUnit( aMtrFldX, eUIUnit, TRUE );
    SetFieldUnit( aMtrFldY, eUIUnit, TRUE );

    // WorkArea holen
    Rectangle aWorkArea = pView->GetWorkArea();

    // PoolUnit ermitteln
    SfxItemPool* pPool = rInAttrs.GetPool();
    DBG_ASSERT( pPool, "Wo ist der Pool?" );
    SfxMapUnit ePoolUnit = pPool->GetMetric( SID_ATTR_FILL_HATCH );

    // Hier werden die Max- und MinWerte in Ahaengigkeit von der
    // WorkArea, PoolUnit und der FieldUnit:
    SetMetricValue( aMtrFldX, aWorkArea.Left(), ePoolUnit );
    long nValue = static_cast<long>(aMtrFldX.GetValue());
    nValue = Fraction( nValue ) / aUIScale;
    aMtrFldX.SetMin( nValue );
    aMtrFldX.SetFirst( nValue );

    SetMetricValue( aMtrFldX, aWorkArea.Right()+1, ePoolUnit );
    nValue = static_cast<long>(aMtrFldX.GetValue());
    nValue = Fraction( nValue ) / aUIScale;
    aMtrFldX.SetMax( nValue );
    aMtrFldX.SetLast( nValue );

    SetMetricValue( aMtrFldY, aWorkArea.Top(), ePoolUnit );
    nValue = static_cast<long>(aMtrFldY.GetValue());
    nValue = Fraction( nValue ) / aUIScale;
    aMtrFldY.SetMin( nValue );
    aMtrFldY.SetFirst( nValue );

    SetMetricValue( aMtrFldY, aWorkArea.Bottom()+1, ePoolUnit );
    nValue = static_cast<long>(aMtrFldY.GetValue());
    nValue = Fraction( nValue ) / aUIScale;
    aMtrFldY.SetMax( nValue );
    aMtrFldY.SetLast( nValue );

    // Setzen der Werte
    nXValue = ((const SfxUInt32Item&) rInAttrs.Get(ATTR_SNAPLINE_X)).GetValue();
    nYValue = ((const SfxUInt32Item&) rInAttrs.Get(ATTR_SNAPLINE_Y)).GetValue();
    nXValue = Fraction(nXValue) / aUIScale;
    nYValue = Fraction(nYValue) / aUIScale;
    SetMetricValue( aMtrFldX, nXValue, SFX_MAPUNIT_100TH_MM);
    SetMetricValue( aMtrFldY, nYValue, SFX_MAPUNIT_100TH_MM);

    aRbPoint.Check();
}

/*************************************************************************
|*
|* Fuellt uebergebenes Item-Set mit Dialogbox-Attributen
|*
\************************************************************************/

IMPL_LINK( SdSnapLineDlg, ClickHdl, Button *, pBtn )
{
    if ( pBtn == &aRbPoint )        SetInputFields(TRUE, TRUE);
    else if ( pBtn == &aRbHorz )    SetInputFields(FALSE, TRUE);
    else if ( pBtn == &aRbVert )    SetInputFields(TRUE, FALSE);
    else if ( pBtn == &aBtnDelete ) EndDialog(RET_SNAP_DELETE);

    return 0;
}

/*************************************************************************
|*
|* Fuellt uebergebenes Item-Set mit Dialogbox-Attributen
|*
\************************************************************************/

void SdSnapLineDlg::GetAttr(SfxItemSet& rOutAttrs)
{
    SnapKind eKind;

    if ( aRbHorz.IsChecked() )      eKind = SK_HORIZONTAL;
    else if ( aRbVert.IsChecked() ) eKind = SK_VERTICAL;
    else                            eKind = SK_POINT;

    nXValue = Fraction( GetCoreValue( aMtrFldX, SFX_MAPUNIT_100TH_MM) ) * aUIScale;
    nYValue = Fraction( GetCoreValue( aMtrFldY, SFX_MAPUNIT_100TH_MM) ) * aUIScale;

    rOutAttrs.Put(SfxAllEnumItem(ATTR_SNAPLINE_KIND, (USHORT)eKind));
    rOutAttrs.Put(SfxUInt32Item(ATTR_SNAPLINE_X, nXValue));
    rOutAttrs.Put(SfxUInt32Item(ATTR_SNAPLINE_Y, nYValue));
}

/*************************************************************************
|*
|* Gruppe mit Radiobutton verstecken
|*
\************************************************************************/

void SdSnapLineDlg::HideRadioGroup()
{
    aFlDir.Hide();
    aRbHorz.Hide();
    aRbVert.Hide();
    aRbPoint.Hide();
}

/*************************************************************************
|*
|* X- bzw. Y-Inputfeld disablen
|*
\************************************************************************/

void SdSnapLineDlg::SetInputFields(BOOL bEnableX, BOOL bEnableY)
{
    if ( bEnableX )
    {
        if ( !aMtrFldX.IsEnabled() )
            aMtrFldX.SetValue(nXValue);
        aMtrFldX.Enable();
        aFtX.Enable();
    }
    else if ( aMtrFldX.IsEnabled() )
    {
        nXValue = static_cast<long>(aMtrFldX.GetValue());
        aMtrFldX.SetText(String());
        aMtrFldX.Disable();
        aFtX.Disable();
    }
    if ( bEnableY )
    {
        if ( !aMtrFldY.IsEnabled() )
            aMtrFldY.SetValue(nYValue);
        aMtrFldY.Enable();
        aFtY.Enable();
    }
    else if ( aMtrFldY.IsEnabled() )
    {
        nYValue = static_cast<long>(aMtrFldY.GetValue());
        aMtrFldY.SetText(String());
        aMtrFldY.Disable();
        aFtY.Disable();
    }
}

<commit_msg>INTEGRATION: CWS changefileheader (1.10.256); FILE MERGED 2008/04/01 15:34:19 thb 1.10.256.3: #i85898# Stripping all external header guards 2008/04/01 12:38:41 thb 1.10.256.2: #i85898# Stripping all external header guards 2008/03/31 13:57:45 rt 1.10.256.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: dlgsnap.cxx,v $
 * $Revision: 1.11 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#ifdef SD_DLLIMPLEMENTATION
#undef SD_DLLIMPLEMENTATION
#endif

#include <svx/svxids.hrc>
#include <svx/dlgutil.hxx>
#include <svtools/itempool.hxx>
#include <svtools/aeitem.hxx>

#include "dlgsnap.hrc"
#include "sdattr.hxx"
#include "View.hxx"
#include "sdresid.hxx"
#include "drawdoc.hxx"
#include "dlgsnap.hxx"

/*************************************************************************
|*
|* Dialog zum Einstellen des Rasters (wohl kaum ESO!)
|*
\************************************************************************/

SdSnapLineDlg::SdSnapLineDlg(
    ::Window* pWindow,
    const SfxItemSet& rInAttrs,
    ::sd::View* pView)
    : ModalDialog (pWindow, SdResId(DLG_SNAPLINE)),
      aFlPos      (this, SdResId(FL_POSITION)),
      aFtX        (this, SdResId(FT_X)),
      aMtrFldX    (this, SdResId(MTR_FLD_X)),
      aFtY        (this, SdResId(FT_Y)),
      aMtrFldY    (this, SdResId(MTR_FLD_Y)),
      aFlDir      (this, SdResId(FL_DIRECTION)),
      aRbPoint    (this, SdResId(RB_POINT)),
      aRbVert     (this, SdResId(RB_VERTICAL)),
      aRbHorz     (this, SdResId(RB_HORIZONTAL)),
      aBtnOK      (this, SdResId(BTN_OK)),
      aBtnCancel  (this, SdResId(BTN_CANCEL)),
      aBtnHelp    (this, SdResId(BTN_HELP)),
      aBtnDelete  (this, SdResId(BTN_DELETE)),
      eUIUnit(pView->GetDoc()->GetUIUnit()),
      aUIScale(pView->GetDoc()->GetUIScale())
{
    aRbPoint.SetModeRadioImage( Image( SdResId( BMP_POINT_H ) ), BMP_COLOR_HIGHCONTRAST );
    aRbVert.SetModeRadioImage( Image( SdResId( BMP_VERTICAL_H ) ), BMP_COLOR_HIGHCONTRAST );
    aRbHorz.SetModeRadioImage( Image( SdResId( BMP_HORIZONTAL_H ) ), BMP_COLOR_HIGHCONTRAST );

    FreeResource();

    aRbHorz.SetClickHdl(LINK(this, SdSnapLineDlg, ClickHdl));
    aRbVert.SetClickHdl(LINK(this, SdSnapLineDlg, ClickHdl));
    aRbPoint.SetClickHdl(LINK(this, SdSnapLineDlg, ClickHdl));

    aBtnDelete.SetClickHdl(LINK(this, SdSnapLineDlg, ClickHdl));

    SetFieldUnit( aMtrFldX, eUIUnit, TRUE );
    SetFieldUnit( aMtrFldY, eUIUnit, TRUE );

    // WorkArea holen
    Rectangle aWorkArea = pView->GetWorkArea();

    // PoolUnit ermitteln
    SfxItemPool* pPool = rInAttrs.GetPool();
    DBG_ASSERT( pPool, "Wo ist der Pool?" );
    SfxMapUnit ePoolUnit = pPool->GetMetric( SID_ATTR_FILL_HATCH );

    // Hier werden die Max- und MinWerte in Ahaengigkeit von der
    // WorkArea, PoolUnit und der FieldUnit:
    SetMetricValue( aMtrFldX, aWorkArea.Left(), ePoolUnit );
    long nValue = static_cast<long>(aMtrFldX.GetValue());
    nValue = Fraction( nValue ) / aUIScale;
    aMtrFldX.SetMin( nValue );
    aMtrFldX.SetFirst( nValue );

    SetMetricValue( aMtrFldX, aWorkArea.Right()+1, ePoolUnit );
    nValue = static_cast<long>(aMtrFldX.GetValue());
    nValue = Fraction( nValue ) / aUIScale;
    aMtrFldX.SetMax( nValue );
    aMtrFldX.SetLast( nValue );

    SetMetricValue( aMtrFldY, aWorkArea.Top(), ePoolUnit );
    nValue = static_cast<long>(aMtrFldY.GetValue());
    nValue = Fraction( nValue ) / aUIScale;
    aMtrFldY.SetMin( nValue );
    aMtrFldY.SetFirst( nValue );

    SetMetricValue( aMtrFldY, aWorkArea.Bottom()+1, ePoolUnit );
    nValue = static_cast<long>(aMtrFldY.GetValue());
    nValue = Fraction( nValue ) / aUIScale;
    aMtrFldY.SetMax( nValue );
    aMtrFldY.SetLast( nValue );

    // Setzen der Werte
    nXValue = ((const SfxUInt32Item&) rInAttrs.Get(ATTR_SNAPLINE_X)).GetValue();
    nYValue = ((const SfxUInt32Item&) rInAttrs.Get(ATTR_SNAPLINE_Y)).GetValue();
    nXValue = Fraction(nXValue) / aUIScale;
    nYValue = Fraction(nYValue) / aUIScale;
    SetMetricValue( aMtrFldX, nXValue, SFX_MAPUNIT_100TH_MM);
    SetMetricValue( aMtrFldY, nYValue, SFX_MAPUNIT_100TH_MM);

    aRbPoint.Check();
}

/*************************************************************************
|*
|* Fuellt uebergebenes Item-Set mit Dialogbox-Attributen
|*
\************************************************************************/

IMPL_LINK( SdSnapLineDlg, ClickHdl, Button *, pBtn )
{
    if ( pBtn == &aRbPoint )        SetInputFields(TRUE, TRUE);
    else if ( pBtn == &aRbHorz )    SetInputFields(FALSE, TRUE);
    else if ( pBtn == &aRbVert )    SetInputFields(TRUE, FALSE);
    else if ( pBtn == &aBtnDelete ) EndDialog(RET_SNAP_DELETE);

    return 0;
}

/*************************************************************************
|*
|* Fuellt uebergebenes Item-Set mit Dialogbox-Attributen
|*
\************************************************************************/

void SdSnapLineDlg::GetAttr(SfxItemSet& rOutAttrs)
{
    SnapKind eKind;

    if ( aRbHorz.IsChecked() )      eKind = SK_HORIZONTAL;
    else if ( aRbVert.IsChecked() ) eKind = SK_VERTICAL;
    else                            eKind = SK_POINT;

    nXValue = Fraction( GetCoreValue( aMtrFldX, SFX_MAPUNIT_100TH_MM) ) * aUIScale;
    nYValue = Fraction( GetCoreValue( aMtrFldY, SFX_MAPUNIT_100TH_MM) ) * aUIScale;

    rOutAttrs.Put(SfxAllEnumItem(ATTR_SNAPLINE_KIND, (USHORT)eKind));
    rOutAttrs.Put(SfxUInt32Item(ATTR_SNAPLINE_X, nXValue));
    rOutAttrs.Put(SfxUInt32Item(ATTR_SNAPLINE_Y, nYValue));
}

/*************************************************************************
|*
|* Gruppe mit Radiobutton verstecken
|*
\************************************************************************/

void SdSnapLineDlg::HideRadioGroup()
{
    aFlDir.Hide();
    aRbHorz.Hide();
    aRbVert.Hide();
    aRbPoint.Hide();
}

/*************************************************************************
|*
|* X- bzw. Y-Inputfeld disablen
|*
\************************************************************************/

void SdSnapLineDlg::SetInputFields(BOOL bEnableX, BOOL bEnableY)
{
    if ( bEnableX )
    {
        if ( !aMtrFldX.IsEnabled() )
            aMtrFldX.SetValue(nXValue);
        aMtrFldX.Enable();
        aFtX.Enable();
    }
    else if ( aMtrFldX.IsEnabled() )
    {
        nXValue = static_cast<long>(aMtrFldX.GetValue());
        aMtrFldX.SetText(String());
        aMtrFldX.Disable();
        aFtX.Disable();
    }
    if ( bEnableY )
    {
        if ( !aMtrFldY.IsEnabled() )
            aMtrFldY.SetValue(nYValue);
        aMtrFldY.Enable();
        aFtY.Enable();
    }
    else if ( aMtrFldY.IsEnabled() )
    {
        nYValue = static_cast<long>(aMtrFldY.GetValue());
        aMtrFldY.SetText(String());
        aMtrFldY.Disable();
        aFtY.Disable();
    }
}

<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#ifdef SD_DLLIMPLEMENTATION
#undef SD_DLLIMPLEMENTATION
#endif

#include "sddlgfact.hxx"

#ifndef _SAL_TYPES_H_
#include "sal/types.h"
#endif

namespace sdui
{
    static SdAbstractDialogFactory_Impl* pFactory=NULL;
    SdAbstractDialogFactory_Impl* GetFactory()
    {
        if ( !pFactory )
            pFactory = new SdAbstractDialogFactory_Impl;
        return pFactory;
    }
}

extern "C"
{
    SAL_DLLPUBLIC_EXPORT SdAbstractDialogFactory* CreateDialogFactory()
    {
        return ::sdui::GetFactory();
    }
}
<commit_msg>INTEGRATION: CWS changefileheader (1.6.298); FILE MERGED 2008/04/01 15:34:22 thb 1.6.298.2: #i85898# Stripping all external header guards 2008/03/31 13:57:49 rt 1.6.298.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: sduiexp.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#ifdef SD_DLLIMPLEMENTATION
#undef SD_DLLIMPLEMENTATION
#endif

#include "sddlgfact.hxx"
#include "sal/types.h"

namespace sdui
{
    static SdAbstractDialogFactory_Impl* pFactory=NULL;
    SdAbstractDialogFactory_Impl* GetFactory()
    {
        if ( !pFactory )
            pFactory = new SdAbstractDialogFactory_Impl;
        return pFactory;
    }
}

extern "C"
{
    SAL_DLLPUBLIC_EXPORT SdAbstractDialogFactory* CreateDialogFactory()
    {
        return ::sdui::GetFactory();
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: fuarea.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: ka $ $Date: 2000-09-21 16:11:55 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#include <svx/svxids.hrc>
#ifndef _SVX_TAB_AREA_HXX //autogen
#include <svx/tabarea.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SD_VIEWSHEL_HXX
#include "viewshel.hxx"
#endif

#include "drawdoc.hxx"
#include "sdview.hxx"
#include "sdwindow.hxx"
#include "fuarea.hxx"
#include "app.hrc"

TYPEINIT1( FuArea, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuArea::FuArea(SdViewShell* pViewSh, SdWindow* pWin, SdView* pView,
               SdDrawDocument* pDoc, SfxRequest& rReq)
    : FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
    const SfxItemSet* pArgs = rReq.GetArgs();

    if( !pArgs )
    {
        // erst einmal alle eingabeparameter fuer den dialog retten
        SfxItemSet aInputAttr( pDoc->GetPool() );
        pView->GetAttributes( aInputAttr );

        const XFillStyleItem    &rIFillStyleItem    = (const XFillStyleItem &) aInputAttr.Get (XATTR_FILLSTYLE);
        const XFillColorItem    &rIFillColorItem    = (const XFillColorItem &) aInputAttr.Get (XATTR_FILLCOLOR);
        const XFillGradientItem &rIFillGradientItem = (const XFillGradientItem &) aInputAttr.Get (XATTR_FILLGRADIENT);
        const XFillHatchItem    &rIFillHatchItem    = (const XFillHatchItem &) aInputAttr.Get (XATTR_FILLHATCH);
        const XFillBitmapItem   &rIXFillBitmapItem  = (const XFillBitmapItem &) aInputAttr.Get (XATTR_FILLBITMAP);

        SfxItemSet* pNewAttr = new SfxItemSet( pDoc->GetPool() );
        pView->GetAttributes( *pNewAttr );

        SvxAreaTabDialog* pDlg = new SvxAreaTabDialog( NULL, pNewAttr, pDoc, pView );

        if ( pDlg->Execute() == RET_OK )
        {
            pView->SetAttributes (*(pDlg->GetOutputItemSet ()));
        }

        // Attribute wurden geaendert, Listboxes in Objectbars muessen aktualisiert werden
        static USHORT SidArray[] = {
                        SID_ATTR_FILL_STYLE,
                        SID_ATTR_FILL_COLOR,
                        SID_ATTR_FILL_GRADIENT,
                        SID_ATTR_FILL_HATCH,
                        SID_ATTR_FILL_BITMAP,
                        0 };

        pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );

        delete pDlg;
        delete pNewAttr;
    }

    rReq.Ignore ();

}

<commit_msg>INTEGRATION: CWS impress1 (1.2.262); FILE MERGED 2003/09/17 09:02:29 af 1.2.262.1: #111996# Transition to stacked sub-shells. Introduction of namespace sd.<commit_after>/*************************************************************************
 *
 *  $RCSfile: fuarea.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2004-01-20 10:55:56 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#include "fuarea.hxx"

#include <svx/svxids.hrc>
#ifndef _SVX_TAB_AREA_HXX //autogen
#include <svx/tabarea.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif

#include "drawdoc.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#include "app.hrc"

namespace sd {

TYPEINIT1( FuArea, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuArea::FuArea (
    ViewShell* pViewSh,
    ::sd::Window* pWin,
    ::sd::View* pView,
    SdDrawDocument* pDoc,
    SfxRequest& rReq)
    : FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
    const SfxItemSet* pArgs = rReq.GetArgs();

    if( !pArgs )
    {
        // erst einmal alle eingabeparameter fuer den dialog retten
        SfxItemSet aInputAttr( pDoc->GetPool() );
        pView->GetAttributes( aInputAttr );

        const XFillStyleItem    &rIFillStyleItem    = (const XFillStyleItem &) aInputAttr.Get (XATTR_FILLSTYLE);
        const XFillColorItem    &rIFillColorItem    = (const XFillColorItem &) aInputAttr.Get (XATTR_FILLCOLOR);
        const XFillGradientItem &rIFillGradientItem = (const XFillGradientItem &) aInputAttr.Get (XATTR_FILLGRADIENT);
        const XFillHatchItem    &rIFillHatchItem    = (const XFillHatchItem &) aInputAttr.Get (XATTR_FILLHATCH);
        const XFillBitmapItem   &rIXFillBitmapItem  = (const XFillBitmapItem &) aInputAttr.Get (XATTR_FILLBITMAP);

        SfxItemSet* pNewAttr = new SfxItemSet( pDoc->GetPool() );
        pView->GetAttributes( *pNewAttr );

        SvxAreaTabDialog* pDlg = new SvxAreaTabDialog( NULL, pNewAttr, pDoc, pView );

        if ( pDlg->Execute() == RET_OK )
        {
            pView->SetAttributes (*(pDlg->GetOutputItemSet ()));
        }

        // Attribute wurden geaendert, Listboxes in Objectbars muessen aktualisiert werden
        static USHORT SidArray[] = {
                        SID_ATTR_FILL_STYLE,
                        SID_ATTR_FILL_COLOR,
                        SID_ATTR_FILL_GRADIENT,
                        SID_ATTR_FILL_HATCH,
                        SID_ATTR_FILL_BITMAP,
                        0 };

        pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );

        delete pDlg;
        delete pNewAttr;
    }

    rReq.Ignore ();

}

} // end of namespace sd
<|endoftext|>


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

#pragma hdrstop

#include "futhes.hxx"

#include <tools/pstm.hxx>
#include <svx/outliner.hxx>
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
#ifndef _SVDOTEXT_HXX //autogen
#include <svx/svdotext.hxx>
#endif

#ifndef _EEITEM_HXX
#include <svx/eeitem.hxx>
#endif

#define ITEMID_LANGUAGE         SID_ATTR_CHAR_LANGUAGE
#include <svx/dialogs.hrc>
#include <svx/svxerr.hxx>
#include <svx/dialmgr.hxx>

#ifndef _UNO_LINGU_HXX
#include <svx/unolingu.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#include "app.hrc"
#include "strings.hrc"
#include "drawdoc.hxx"
#include "app.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_OUTLINER_HXX
#include "Outliner.hxx"
#endif
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif
#ifndef SD_OUTLINE_VIEW_SHELL_HXX
#include "OutlineViewShell.hxx"
#endif
#ifndef SD_WINDOW_SHELL_HXX
#include "Window.hxx"
#endif
#include "sdresid.hxx"

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::linguistic2;

class SfxRequest;

namespace sd {

TYPEINIT1( FuThesaurus, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuThesaurus::FuThesaurus( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView,
                  SdDrawDocument* pDoc, SfxRequest& rReq )
       : FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
    SfxErrorContext aContext(ERRCTX_SVX_LINGU_THESAURUS, String(),
                             pWin, RID_SVXERRCTX, DIALOG_MGR() );

    if ( pViewShell->ISA(DrawViewShell) )
    {
        SdrTextObj* pTextObj = NULL;

        if ( pView->AreObjectsMarked() )
        {
            const SdrMarkList& rMarkList = pView->GetMarkedObjectList();

            if ( rMarkList.GetMarkCount() == 1 )
            {
                SdrMark* pMark = rMarkList.GetMark(0);
                SdrObject* pObj = pMark->GetObj();

                if ( pObj->ISA(SdrTextObj) )
                {
                    pTextObj = (SdrTextObj*) pObj;
                }
            }
        }

        ::Outliner* pOutliner = pView->GetTextEditOutliner();
        const OutlinerView* pOutlView = pView->GetTextEditOutlinerView();

        if ( pTextObj && pOutliner && pOutlView )
        {
            if ( !pOutliner->GetSpeller().is() )
            {
                Reference< XSpellChecker1 > xSpellChecker( LinguMgr::GetSpellChecker() );
                if ( xSpellChecker.is() )
                    pOutliner->SetSpeller( xSpellChecker );

                Reference< XHyphenator > xHyphenator( LinguMgr::GetHyphenator() );
                if( xHyphenator.is() )
                    pOutliner->SetHyphenator( xHyphenator );

                pOutliner->SetDefaultLanguage( pDoc->GetLanguage( EE_CHAR_LANGUAGE ) );
            }

            EESpellState eState = ( (OutlinerView*) pOutlView)->StartThesaurus();
            DBG_ASSERT(eState != EE_SPELL_NOSPELLER, "No SpellChecker");

            if (eState == EE_SPELL_NOLANGUAGE)
            {
                ErrorBox(pWindow, WB_OK, String(SdResId(STR_NOLANGUAGE))).Execute();
            }
        }
    }
    else if ( pViewShell->ISA(OutlineViewShell) )
    {
        Outliner* pOutliner = pDoc->GetOutliner();
        OutlinerView* pOutlView = pOutliner->GetView(0);

        if ( !pOutliner->GetSpeller().is() )
        {
            Reference< XSpellChecker1 > xSpellChecker( LinguMgr::GetSpellChecker() );
            if ( xSpellChecker.is() )
                pOutliner->SetSpeller( xSpellChecker );

            Reference< XHyphenator > xHyphenator( LinguMgr::GetHyphenator() );
            if( xHyphenator.is() )
                pOutliner->SetHyphenator( xHyphenator );

            pOutliner->SetDefaultLanguage( pDoc->GetLanguage( EE_CHAR_LANGUAGE ) );
        }

        EESpellState eState = pOutlView->StartThesaurus();
        DBG_ASSERT(eState != EE_SPELL_NOSPELLER, "No SpellChecker");

        if (eState == EE_SPELL_NOLANGUAGE)
        {
            ErrorBox(pWindow, WB_OK, String(SdResId(STR_NOLANGUAGE))).Execute();
        }
    }
}

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
FuThesaurus::~FuThesaurus()
{
}

} // end of namespace sd
<commit_msg>INTEGRATION: CWS impressfunctions (1.11.40); FILE MERGED 2005/10/28 12:03:14 cl 1.11.40.2: #125341# fixed unix build problems 2005/10/28 10:57:42 cl 1.11.40.1: #125341# reworked FuPoor classes to use refcounting<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: futhes.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: rt $ $Date: 2005-12-14 17:05:32 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#pragma hdrstop

#include "futhes.hxx"

#include <tools/pstm.hxx>
#include <svx/outliner.hxx>
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
#ifndef _SVDOTEXT_HXX //autogen
#include <svx/svdotext.hxx>
#endif

#ifndef _EEITEM_HXX
#include <svx/eeitem.hxx>
#endif

#define ITEMID_LANGUAGE         SID_ATTR_CHAR_LANGUAGE
#include <svx/dialogs.hrc>
#include <svx/svxerr.hxx>
#include <svx/dialmgr.hxx>

#ifndef _UNO_LINGU_HXX
#include <svx/unolingu.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#include "app.hrc"
#include "strings.hrc"
#include "drawdoc.hxx"
#include "app.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_OUTLINER_HXX
#include "Outliner.hxx"
#endif
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif
#ifndef SD_OUTLINE_VIEW_SHELL_HXX
#include "OutlineViewShell.hxx"
#endif
#ifndef SD_WINDOW_SHELL_HXX
#include "Window.hxx"
#endif
#include "sdresid.hxx"

using ::rtl::OUString;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::linguistic2;

class SfxRequest;

namespace sd {

TYPEINIT1( FuThesaurus, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuThesaurus::FuThesaurus( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView,
                  SdDrawDocument* pDoc, SfxRequest& rReq )
       : FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}

FunctionReference FuThesaurus::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
    FunctionReference xFunc( new FuThesaurus( pViewSh, pWin, pView, pDoc, rReq ) );
    xFunc->DoExecute(rReq);
    return xFunc;
}

void FuThesaurus::DoExecute( SfxRequest& rReq )
{
    SfxErrorContext aContext(ERRCTX_SVX_LINGU_THESAURUS, String(),
                             pWindow, RID_SVXERRCTX, DIALOG_MGR() );

    if( pViewShell && pViewShell->ISA(DrawViewShell) )
    {
        SdrTextObj* pTextObj = NULL;

        if ( pView->AreObjectsMarked() )
        {
            const SdrMarkList& rMarkList = pView->GetMarkedObjectList();

            if ( rMarkList.GetMarkCount() == 1 )
            {
                SdrMark* pMark = rMarkList.GetMark(0);
                SdrObject* pObj = pMark->GetObj();

                if ( pObj->ISA(SdrTextObj) )
                {
                    pTextObj = (SdrTextObj*) pObj;
                }
            }
        }

        ::Outliner* pOutliner = pView->GetTextEditOutliner();
        const OutlinerView* pOutlView = pView->GetTextEditOutlinerView();

        if ( pTextObj && pOutliner && pOutlView )
        {
            if ( !pOutliner->GetSpeller().is() )
            {
                Reference< XSpellChecker1 > xSpellChecker( LinguMgr::GetSpellChecker() );
                if ( xSpellChecker.is() )
                    pOutliner->SetSpeller( xSpellChecker );

                Reference< XHyphenator > xHyphenator( LinguMgr::GetHyphenator() );
                if( xHyphenator.is() )
                    pOutliner->SetHyphenator( xHyphenator );

                pOutliner->SetDefaultLanguage( pDoc->GetLanguage( EE_CHAR_LANGUAGE ) );
            }

            EESpellState eState = ( (OutlinerView*) pOutlView)->StartThesaurus();
            DBG_ASSERT(eState != EE_SPELL_NOSPELLER, "No SpellChecker");

            if (eState == EE_SPELL_NOLANGUAGE)
            {
                ErrorBox(pWindow, WB_OK, String(SdResId(STR_NOLANGUAGE))).Execute();
            }
        }
    }
    else if ( pViewShell->ISA(OutlineViewShell) )
    {
        Outliner* pOutliner = pDoc->GetOutliner();
        OutlinerView* pOutlView = pOutliner->GetView(0);

        if ( !pOutliner->GetSpeller().is() )
        {
            Reference< XSpellChecker1 > xSpellChecker( LinguMgr::GetSpellChecker() );
            if ( xSpellChecker.is() )
                pOutliner->SetSpeller( xSpellChecker );

            Reference< XHyphenator > xHyphenator( LinguMgr::GetHyphenator() );
            if( xHyphenator.is() )
                pOutliner->SetHyphenator( xHyphenator );

            pOutliner->SetDefaultLanguage( pDoc->GetLanguage( EE_CHAR_LANGUAGE ) );
        }

        EESpellState eState = pOutlView->StartThesaurus();
        DBG_ASSERT(eState != EE_SPELL_NOSPELLER, "No SpellChecker");

        if (eState == EE_SPELL_NOLANGUAGE)
        {
            ErrorBox(pWindow, WB_OK, String(SdResId(STR_NOLANGUAGE))).Execute();
        }
    }
}

} // end of namespace sd
<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#include "futhes.hxx"

#include <tools/pstm.hxx>
#include <svx/outliner.hxx>
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
#ifndef _SVDOTEXT_HXX //autogen
#include <svx/svdotext.hxx>
#endif

#ifndef _EEITEM_HXX
#include <svx/eeitem.hxx>
#endif

#define ITEMID_LANGUAGE         SID_ATTR_CHAR_LANGUAGE
#include <svx/dialogs.hrc>
#include <svx/svxerr.hxx>
#include <svx/dialmgr.hxx>

#ifndef _UNO_LINGU_HXX
#include <svx/unolingu.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#include "app.hrc"
#include "strings.hrc"
#include "drawdoc.hxx"
#include "app.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_OUTLINER_HXX
#include "Outliner.hxx"
#endif
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif
#ifndef SD_OUTLINE_VIEW_SHELL_HXX
#include "OutlineViewShell.hxx"
#endif
#ifndef SD_WINDOW_SHELL_HXX
#include "Window.hxx"
#endif
#include "sdresid.hxx"

using ::rtl::OUString;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::linguistic2;

class SfxRequest;

namespace sd {

TYPEINIT1( FuThesaurus, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuThesaurus::FuThesaurus( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView,
                  SdDrawDocument* pDoc, SfxRequest& rReq )
       : FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}

FunctionReference FuThesaurus::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
    FunctionReference xFunc( new FuThesaurus( pViewSh, pWin, pView, pDoc, rReq ) );
    xFunc->DoExecute(rReq);
    return xFunc;
}

void FuThesaurus::DoExecute( SfxRequest& rReq )
{
    SfxErrorContext aContext(ERRCTX_SVX_LINGU_THESAURUS, String(),
                             pWindow, RID_SVXERRCTX, DIALOG_MGR() );

    if( pViewShell && pViewShell->ISA(DrawViewShell) )
    {
        SdrTextObj* pTextObj = NULL;

        if ( pView->AreObjectsMarked() )
        {
            const SdrMarkList& rMarkList = pView->GetMarkedObjectList();

            if ( rMarkList.GetMarkCount() == 1 )
            {
                SdrMark* pMark = rMarkList.GetMark(0);
                SdrObject* pObj = pMark->GetMarkedSdrObj();

                if ( pObj->ISA(SdrTextObj) )
                {
                    pTextObj = (SdrTextObj*) pObj;
                }
            }
        }

        ::Outliner* pOutliner = pView->GetTextEditOutliner();
        const OutlinerView* pOutlView = pView->GetTextEditOutlinerView();

        if ( pTextObj && pOutliner && pOutlView )
        {
            if ( !pOutliner->GetSpeller().is() )
            {
                Reference< XSpellChecker1 > xSpellChecker( LinguMgr::GetSpellChecker() );
                if ( xSpellChecker.is() )
                    pOutliner->SetSpeller( xSpellChecker );

                Reference< XHyphenator > xHyphenator( LinguMgr::GetHyphenator() );
                if( xHyphenator.is() )
                    pOutliner->SetHyphenator( xHyphenator );

                pOutliner->SetDefaultLanguage( pDoc->GetLanguage( EE_CHAR_LANGUAGE ) );
            }

            EESpellState eState = ( (OutlinerView*) pOutlView)->StartThesaurus();
            DBG_ASSERT(eState != EE_SPELL_NOSPELLER, "No SpellChecker");

            if (eState == EE_SPELL_NOLANGUAGE)
            {
                ErrorBox(pWindow, WB_OK, String(SdResId(STR_NOLANGUAGE))).Execute();
            }
        }
    }
    else if ( pViewShell->ISA(OutlineViewShell) )
    {
        Outliner* pOutliner = pDoc->GetOutliner();
        OutlinerView* pOutlView = pOutliner->GetView(0);

        if ( !pOutliner->GetSpeller().is() )
        {
            Reference< XSpellChecker1 > xSpellChecker( LinguMgr::GetSpellChecker() );
            if ( xSpellChecker.is() )
                pOutliner->SetSpeller( xSpellChecker );

            Reference< XHyphenator > xHyphenator( LinguMgr::GetHyphenator() );
            if( xHyphenator.is() )
                pOutliner->SetHyphenator( xHyphenator );

            pOutliner->SetDefaultLanguage( pDoc->GetLanguage( EE_CHAR_LANGUAGE ) );
        }

        EESpellState eState = pOutlView->StartThesaurus();
        DBG_ASSERT(eState != EE_SPELL_NOSPELLER, "No SpellChecker");

        if (eState == EE_SPELL_NOLANGUAGE)
        {
            ErrorBox(pWindow, WB_OK, String(SdResId(STR_NOLANGUAGE))).Execute();
        }
    }
}

} // end of namespace sd
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.14.38); FILE MERGED 2006/11/22 12:41:57 cl 1.14.38.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: futhes.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-12 17:25:52 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#include "futhes.hxx"

#include <tools/pstm.hxx>
#include <svx/outliner.hxx>
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
#ifndef _SVDOTEXT_HXX //autogen
#include <svx/svdotext.hxx>
#endif

#ifndef _EEITEM_HXX
#include <svx/eeitem.hxx>
#endif

#define ITEMID_LANGUAGE         SID_ATTR_CHAR_LANGUAGE
#include <svx/dialogs.hrc>
#include <svx/svxerr.hxx>
#include <svx/dialmgr.hxx>

#ifndef _UNO_LINGU_HXX
#include <svx/unolingu.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#include "app.hrc"
#include "strings.hrc"
#include "drawdoc.hxx"
#include "app.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_OUTLINER_HXX
#include "Outliner.hxx"
#endif
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif
#ifndef SD_OUTLINE_VIEW_SHELL_HXX
#include "OutlineViewShell.hxx"
#endif
#ifndef SD_WINDOW_SHELL_HXX
#include "Window.hxx"
#endif
#include "sdresid.hxx"

using ::rtl::OUString;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::linguistic2;

class SfxRequest;

namespace sd {

TYPEINIT1( FuThesaurus, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuThesaurus::FuThesaurus( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView,
                  SdDrawDocument* pDoc, SfxRequest& rReq )
       : FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}

FunctionReference FuThesaurus::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
    FunctionReference xFunc( new FuThesaurus( pViewSh, pWin, pView, pDoc, rReq ) );
    xFunc->DoExecute(rReq);
    return xFunc;
}

void FuThesaurus::DoExecute( SfxRequest& )
{
    SfxErrorContext aContext(ERRCTX_SVX_LINGU_THESAURUS, String(),
                             mpWindow, RID_SVXERRCTX, DIALOG_MGR() );

    if( mpViewShell && mpViewShell->ISA(DrawViewShell) )
    {
        SdrTextObj* pTextObj = NULL;

        if ( mpView->AreObjectsMarked() )
        {
            const SdrMarkList& rMarkList = mpView->GetMarkedObjectList();

            if ( rMarkList.GetMarkCount() == 1 )
            {
                SdrMark* pMark = rMarkList.GetMark(0);
                SdrObject* pObj = pMark->GetMarkedSdrObj();

                if ( pObj->ISA(SdrTextObj) )
                {
                    pTextObj = (SdrTextObj*) pObj;
                }
            }
        }

        ::Outliner* pOutliner = mpView->GetTextEditOutliner();
        const OutlinerView* pOutlView = mpView->GetTextEditOutlinerView();

        if ( pTextObj && pOutliner && pOutlView )
        {
            if ( !pOutliner->GetSpeller().is() )
            {
                Reference< XSpellChecker1 > xSpellChecker( LinguMgr::GetSpellChecker() );
                if ( xSpellChecker.is() )
                    pOutliner->SetSpeller( xSpellChecker );

                Reference< XHyphenator > xHyphenator( LinguMgr::GetHyphenator() );
                if( xHyphenator.is() )
                    pOutliner->SetHyphenator( xHyphenator );

                pOutliner->SetDefaultLanguage( mpDoc->GetLanguage( EE_CHAR_LANGUAGE ) );
            }

            EESpellState eState = ( (OutlinerView*) pOutlView)->StartThesaurus();
            DBG_ASSERT(eState != EE_SPELL_NOSPELLER, "No SpellChecker");

            if (eState == EE_SPELL_NOLANGUAGE)
            {
                ErrorBox(mpWindow, WB_OK, String(SdResId(STR_NOLANGUAGE))).Execute();
            }
        }
    }
    else if ( mpViewShell->ISA(OutlineViewShell) )
    {
        Outliner* pOutliner = mpDoc->GetOutliner();
        OutlinerView* pOutlView = pOutliner->GetView(0);

        if ( !pOutliner->GetSpeller().is() )
        {
            Reference< XSpellChecker1 > xSpellChecker( LinguMgr::GetSpellChecker() );
            if ( xSpellChecker.is() )
                pOutliner->SetSpeller( xSpellChecker );

            Reference< XHyphenator > xHyphenator( LinguMgr::GetHyphenator() );
            if( xHyphenator.is() )
                pOutliner->SetHyphenator( xHyphenator );

            pOutliner->SetDefaultLanguage( mpDoc->GetLanguage( EE_CHAR_LANGUAGE ) );
        }

        EESpellState eState = pOutlView->StartThesaurus();
        DBG_ASSERT(eState != EE_SPELL_NOSPELLER, "No SpellChecker");

        if (eState == EE_SPELL_NOLANGUAGE)
        {
            ErrorBox(mpWindow, WB_OK, String(SdResId(STR_NOLANGUAGE))).Execute();
        }
    }
}

} // end of namespace sd
<|endoftext|>


<commit_before>#ifndef GROW_CLOUD_HPP_
#define GROW_CLOUD_HPP_

#include <iostream>

#include <lcm/lcm.h>

#include "pcl/io/pcd_io.h"
#include "pcl/point_types.h"

// Find Floor:
#include "pcl/ModelCoefficients.h"
#include "pcl/segmentation/sac_segmentation.h"
#include "pcl/sample_consensus/method_types.h"
#include "pcl/sample_consensus/model_types.h"
// person filtering:
#include <pcl/filters/passthrough.h>
#include "pcl/filters/conditional_removal.h"
#include "pcl/filters/statistical_outlier_removal.h"
#include "pcl/filters/extract_indices.h"
// Plane Extractions:
#include "pcl/filters/voxel_grid.h"
#include "pcl/filters/project_inliers.h"
#include "pcl/surface/convex_hull.h"
#include "pcl/surface/concave_hull.h"
#include "pcl/PolygonMesh.h"
#include "pcl/octree/octree.h"

#include <pronto_utils/pronto_vis.hpp> // visualize pt clds

using namespace std;
typedef pcl::PointXYZRGB PointT;
// removed due to conflict with VS_SLAM
//typedef pcl::PointCloud<pcl::PointXYZRGB>::Ptr PointCloudPtr;

typedef struct _BasicPlane
{
  int64_t utime;
  std::string name; // a unique name eg the file name
  int major; // which major plane
  int minor; // which minor plane
  //Hull of Plane (either convex or concave - depending on algorithm)
  pcl::PointCloud<pcl::PointXYZRGB> cloud ;
   pcl::ModelCoefficients coeffs;
  Eigen::Vector4f centroid;

  // this number of points in the original soure cloud.
  // Used for voting when combining to a final cloud
  int n_source_points;

  // New members added in jun17_2011: mfallon
  EIGEN_ALIGN16 Eigen::Matrix3f covariance_matrix;
  Eigen::Affine3f transform000; // transform to move the plane to 0,0,0 [ie centroid=0,0,0] aligned to the x,y axis (i think)

  EIGEN_MAKE_ALIGNED_OPERATOR_NEW

} BasicPlane;

class GrowCloud {
  public:
    GrowCloud ();

    inline void setInputCloud (const pcl::PointCloud<pcl::PointXYZRGB>::Ptr &input)
    {
      incloud   = input;
    }

    virtual inline void setLCM(lcm_t *publish_lcm_in){
      publish_lcm = publish_lcm_in;
    }

    // function to 'grow' point cloud from a set of points,
    // seperatating disconnected points into different cloud using octrees
    // @input: a point cloud with all points on a plane. points may be from disconnected clouds
    // @output: individual clouds
    void doGrowCloud (vector<BasicPlane> &outstack);

    virtual inline void setMinCloudSize(int min_cloud_size_in){
      min_cloud_size_ = min_cloud_size_in;
    }

    // function to return a plane stack's coeffs in string
    void printPlaneStackCoeffs (vector<BasicPlane> &planeStack,  std::stringstream &ss);
    // ditto for the bounding points
    void printPlaneStackHull (vector<BasicPlane> &planeStack,  std::stringstream &ss);

    void visualizePlanes(vector<BasicPlane> &plane_stack,pronto_vis* pc_vis_ , int null_id );

  protected:
    pcl::PointCloud<pcl::PointXYZRGB>::Ptr incloud;

    // the pose that this cloud is connected to (so as to publish onto a collections pose)
    // if pose_coll_id is negative, don't publish to LCM:
    int pose_coll_id;
    int64_t pose_element_id;

    int verbose_text;
    int verbose_lcm;
    lcm_t *publish_lcm;

    // settings:
    int min_cloud_size_;
};

#endif  //#ifndef _GROW_CLOUD_HPP_
<commit_msg>minor change for ubuntu 16<commit_after>#ifndef GROW_CLOUD_HPP_
#define GROW_CLOUD_HPP_

#include <iostream>

#include <lcm/lcm.h>

#include "pcl/io/pcd_io.h"
#include "pcl/point_types.h"

// Find Floor:
#include "pcl/ModelCoefficients.h"
#include "pcl/segmentation/sac_segmentation.h"
#include "pcl/sample_consensus/method_types.h"
#include "pcl/sample_consensus/model_types.h"
// person filtering:
#include <pcl/filters/passthrough.h>
#include "pcl/filters/conditional_removal.h"
#include "pcl/filters/statistical_outlier_removal.h"
#include "pcl/filters/extract_indices.h"
// Plane Extractions:
#include "pcl/filters/voxel_grid.h"
#include "pcl/filters/project_inliers.h"
#include "pcl/surface/convex_hull.h"
#include "pcl/surface/concave_hull.h"
#include "pcl/PolygonMesh.h"
#include "pcl/octree/octree.h"
#include "pcl/common/centroid.h"

#include <pronto_utils/pronto_vis.hpp> // visualize pt clds

using namespace std;
typedef pcl::PointXYZRGB PointT;
// removed due to conflict with VS_SLAM
//typedef pcl::PointCloud<pcl::PointXYZRGB>::Ptr PointCloudPtr;

typedef struct _BasicPlane
{
  int64_t utime;
  std::string name; // a unique name eg the file name
  int major; // which major plane
  int minor; // which minor plane
  //Hull of Plane (either convex or concave - depending on algorithm)
  pcl::PointCloud<pcl::PointXYZRGB> cloud ;
   pcl::ModelCoefficients coeffs;
  Eigen::Vector4f centroid;

  // this number of points in the original soure cloud.
  // Used for voting when combining to a final cloud
  int n_source_points;

  // New members added in jun17_2011: mfallon
  EIGEN_ALIGN16 Eigen::Matrix3f covariance_matrix;
  Eigen::Affine3f transform000; // transform to move the plane to 0,0,0 [ie centroid=0,0,0] aligned to the x,y axis (i think)

  EIGEN_MAKE_ALIGNED_OPERATOR_NEW

} BasicPlane;

class GrowCloud {
  public:
    GrowCloud ();

    inline void setInputCloud (const pcl::PointCloud<pcl::PointXYZRGB>::Ptr &input)
    {
      incloud   = input;
    }

    virtual inline void setLCM(lcm_t *publish_lcm_in){
      publish_lcm = publish_lcm_in;
    }

    // function to 'grow' point cloud from a set of points,
    // seperatating disconnected points into different cloud using octrees
    // @input: a point cloud with all points on a plane. points may be from disconnected clouds
    // @output: individual clouds
    void doGrowCloud (vector<BasicPlane> &outstack);

    virtual inline void setMinCloudSize(int min_cloud_size_in){
      min_cloud_size_ = min_cloud_size_in;
    }

    // function to return a plane stack's coeffs in string
    void printPlaneStackCoeffs (vector<BasicPlane> &planeStack,  std::stringstream &ss);
    // ditto for the bounding points
    void printPlaneStackHull (vector<BasicPlane> &planeStack,  std::stringstream &ss);

    void visualizePlanes(vector<BasicPlane> &plane_stack,pronto_vis* pc_vis_ , int null_id );

  protected:
    pcl::PointCloud<pcl::PointXYZRGB>::Ptr incloud;

    // the pose that this cloud is connected to (so as to publish onto a collections pose)
    // if pose_coll_id is negative, don't publish to LCM:
    int pose_coll_id;
    int64_t pose_element_id;

    int verbose_text;
    int verbose_lcm;
    lcm_t *publish_lcm;

    // settings:
    int min_cloud_size_;
};

#endif  //#ifndef _GROW_CLOUD_HPP_
<|endoftext|>


<commit_before>
static void (*real_one) ();
static void stub(){}

/* in CheatSheetTest.cpp */
#include "CppUTest/TestHarness.h"

/* Declare TestGroup with name CheatSheet */
TEST_GROUP(CheatSheet)
{
/* declare a setup method for the test group. Optional. */
    void setup ()
    {
/* Set method real_one to stub. Automatically restore in teardown */
        UT_PTR_SET(real_one, stub);
    }

/* Declare a teardown method for the test group. Optional */
    void teardown()
    {
    }
}; /* Do not forget semicolumn */

/* Declare one test within the test group */
TEST(CheatSheet, TestName)
{
    /* Check two longs are equal */
    LONGS_EQUAL(1, 2);

    /* Check a condition */
    CHECK(true == true);

    /* Check a string */
    STRCMP_EQUAL("HelloWorld", "HelloWorld");
}

<commit_msg>Remove intentional failure again, so build can pass<commit_after>
static void (*real_one) ();
static void stub(){}

/* in CheatSheetTest.cpp */
#include "CppUTest/TestHarness.h"

/* Declare TestGroup with name CheatSheet */
TEST_GROUP(CheatSheet)
{
/* declare a setup method for the test group. Optional. */
    void setup ()
    {
/* Set method real_one to stub. Automatically restore in teardown */
        UT_PTR_SET(real_one, stub);
    }

/* Declare a teardown method for the test group. Optional */
    void teardown()
    {
    }
}; /* Do not forget semicolumn */

/* Declare one test within the test group */
TEST(CheatSheet, TestName)
{
    /* Check two longs are equal */
    LONGS_EQUAL(1, 1);

    /* Check a condition */
    CHECK(true == true);

    /* Check a string */
    STRCMP_EQUAL("HelloWorld", "HelloWorld");
}

<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/prediction/prediction.h"

#include <algorithm>
#include <cmath>
#include <vector>

#include "boost/filesystem.hpp"
#include "boost/range/iterator_range.hpp"
#include "rosbag/bag.h"
#include "rosbag/view.h"

#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/math/vec2d.h"
#include "modules/common/time/time.h"
#include "modules/common/util/file.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/validation_checker.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/container/pose/pose_container.h"
#include "modules/prediction/evaluator/evaluator_manager.h"
#include "modules/prediction/predictor/predictor_manager.h"
#include "modules/prediction/proto/prediction_obstacle.pb.h"

namespace apollo {
namespace prediction {

using ::apollo::common::ErrorCode;
using ::apollo::common::Status;
using ::apollo::common::TrajectoryPoint;
using ::apollo::common::adapter::AdapterConfig;
using ::apollo::common::adapter::AdapterManager;
using ::apollo::common::math::Vec2d;
using ::apollo::common::time::Clock;
using ::apollo::common::util::DirectoryExists;
using ::apollo::common::util::Glob;
using ::apollo::localization::LocalizationEstimate;
using ::apollo::perception::PerceptionObstacle;
using ::apollo::perception::PerceptionObstacles;

std::string Prediction::Name() const { return FLAGS_prediction_module_name; }

void GetBagFiles(const boost::filesystem::path& p,
                 std::vector<std::string>* bag_files) {
  CHECK(bag_files);
  if (!boost::filesystem::exists(p)) {
    return;
  }
  if (boost::filesystem::is_regular_file(p)) {
    const auto ext = p.extension();
    if (ext == ".bag" || ext == ".BAG") {
      AINFO << "Found bag file: " << p.c_str();
      bag_files->push_back(p.c_str());
    }
    return;
  }
  if (boost::filesystem::is_directory(p)) {
    for (auto& entry : boost::make_iterator_range(
             boost::filesystem::directory_iterator(p), {})) {
      GetBagFiles(entry.path(), bag_files);
    }
  }
}
void Prediction::ProcessRosbag(const std::string& filename) {
  const std::vector<std::string> topics{FLAGS_perception_obstacle_topic,
                                        FLAGS_localization_topic};
  rosbag::Bag bag;
  try {
    bag.open(filename, rosbag::bagmode::Read);
  } catch (const rosbag::BagIOException& e) {
    AERROR << "BagIOException when open bag: " << filename
           << " Exception: " << e.what();
    bag.close();
    return;
  } catch (...) {
    AERROR << "Failed to open bag: " << filename;
    bag.close();
    return;
  }
  rosbag::View view(bag, rosbag::TopicQuery(topics));
  for (auto it = view.begin(); it != view.end(); ++it) {
    if (it->getTopic() == FLAGS_localization_topic) {
      OnLocalization(*(it->instantiate<LocalizationEstimate>()));
    } else if (it->getTopic() == FLAGS_perception_obstacle_topic) {
      RunOnce(*(it->instantiate<PerceptionObstacles>()));
    }
  }
  bag.close();
}

Status Prediction::Init() {
  start_time_ = Clock::NowInSeconds();

  // Load prediction conf
  prediction_conf_.Clear();
  if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file,
                                      &prediction_conf_)) {
    return OnError("Unable to load prediction conf file: " +
                   FLAGS_prediction_conf_file);
  } else {
    ADEBUG << "Prediction config file is loaded into: "
           << prediction_conf_.ShortDebugString();
  }

  adapter_conf_.Clear();
  if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename,
                                      &adapter_conf_)) {
    return OnError("Unable to load adapter conf file: " +
                   FLAGS_prediction_adapter_config_filename);
  } else {
    ADEBUG << "Adapter config file is loaded into: "
           << adapter_conf_.ShortDebugString();
  }

  // Initialization of all managers
  AdapterManager::Init(adapter_conf_);
  ContainerManager::instance()->Init(adapter_conf_);
  EvaluatorManager::instance()->Init(prediction_conf_);
  PredictorManager::instance()->Init(prediction_conf_);

  CHECK(AdapterManager::GetLocalization()) << "Localization is not registered.";
  CHECK(AdapterManager::GetPerceptionObstacles())
      << "Perception is not registered.";

  // Set localization callback function
  AdapterManager::AddLocalizationCallback(&Prediction::OnLocalization, this);
  // Set planning callback function
  AdapterManager::AddPlanningCallback(&Prediction::OnPlanning, this);
  // Set perception obstacle callback function
  AdapterManager::AddPerceptionObstaclesCallback(&Prediction::RunOnce, this);

  if (!FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
    return OnError("Map cannot be loaded.");
  }

  if (FLAGS_prediction_offline_mode) {
    if (!FeatureOutput::Ready()) {
      return OnError("Feature output is not ready.");
    }
    if (FLAGS_prediction_offline_bags.empty()) {
      return Status::OK();  // use listen to ROS topic mode
    }
    std::vector<std::string> inputs;
    apollo::common::util::split(FLAGS_prediction_offline_bags, ':', &inputs);
    for (const auto& input : inputs) {
      std::vector<std::string> offline_bags;
      GetBagFiles(boost::filesystem::path(input), &offline_bags);
      std::sort(offline_bags.begin(), offline_bags.end());
      AINFO << "For input " << input << ", found " << offline_bags.size()
            << "  rosbags to process";
      for (std::size_t i = 0; i < offline_bags.size(); ++i) {
        AINFO << "\tProcessing: [ " << i << " / " << offline_bags.size()
              << " ]: " << offline_bags[i];
        ProcessRosbag(offline_bags[i]);
      }
    }
    Stop();
    ros::shutdown();
  }
  return Status::OK();
}

Status Prediction::Start() { return Status::OK(); }

void Prediction::Stop() {
  if (FLAGS_prediction_offline_mode) {
    FeatureOutput::Close();
  }
}

void Prediction::OnLocalization(const LocalizationEstimate& localization) {
  PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
      ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION));
  CHECK_NOTNULL(pose_container);
  pose_container->Insert(localization);

  ADEBUG << "Received a localization message ["
         << localization.ShortDebugString() << "].";
}

void Prediction::OnPlanning(const planning::ADCTrajectory& adc_trajectory) {
  ADCTrajectoryContainer* adc_trajectory_container =
      dynamic_cast<ADCTrajectoryContainer*>(
          ContainerManager::instance()->GetContainer(
              AdapterConfig::PLANNING_TRAJECTORY));
  CHECK_NOTNULL(adc_trajectory_container);
  adc_trajectory_container->Insert(adc_trajectory);

  ADEBUG << "Received a planning message [" << adc_trajectory.ShortDebugString()
         << "].";
}

void Prediction::RunOnce(const PerceptionObstacles& perception_obstacles) {
  if (FLAGS_prediction_test_mode && FLAGS_prediction_test_duration > 0 &&
      (Clock::NowInSeconds() - start_time_ > FLAGS_prediction_test_duration)) {
    AINFO << "Prediction finished running in test mode";
    ros::shutdown();
  }

  // Update relative map if needed
  AdapterManager::Observe();
  if (FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
    AERROR << "Relative map is empty.";
    return;
  }

  double start_timestamp = Clock::NowInSeconds();

  // Insert obstacle
  ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>(
      ContainerManager::instance()->GetContainer(
          AdapterConfig::PERCEPTION_OBSTACLES));
  CHECK_NOTNULL(obstacles_container);
  obstacles_container->Insert(perception_obstacles);

  ADEBUG << "Received a perception message ["
         << perception_obstacles.ShortDebugString() << "].";

  // Update ADC status
  PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
      ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION));
  ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>(
      ContainerManager::instance()->GetContainer(
          AdapterConfig::PLANNING_TRAJECTORY));
  CHECK_NOTNULL(pose_container);
  CHECK_NOTNULL(adc_container);

  PerceptionObstacle* adc = pose_container->ToPerceptionObstacle();
  if (adc != nullptr) {
    obstacles_container->InsertPerceptionObstacle(*adc, adc->timestamp());
    double x = adc->position().x();
    double y = adc->position().y();
    ADEBUG << "Get ADC position [" << std::fixed << std::setprecision(6) << x
           << ", " << std::fixed << std::setprecision(6) << y << "].";
    Vec2d adc_position(x, y);
    adc_container->SetPosition(adc_position);
  }

  // Make evaluations
  EvaluatorManager::instance()->Run(perception_obstacles);

  // No prediction for offline mode
  if (FLAGS_prediction_offline_mode) {
    return;
  }

  // Make predictions
  PredictorManager::instance()->Run(perception_obstacles);

  auto prediction_obstacles =
      PredictorManager::instance()->prediction_obstacles();
  prediction_obstacles.set_start_timestamp(start_timestamp);
  prediction_obstacles.set_end_timestamp(Clock::NowInSeconds());

  if (FLAGS_prediction_test_mode) {
    for (auto const& prediction_obstacle :
         prediction_obstacles.prediction_obstacle()) {
      for (auto const& trajectory : prediction_obstacle.trajectory()) {
        for (auto const& trajectory_point : trajectory.trajectory_point()) {
          if (!ValidationChecker::ValidTrajectoryPoint(trajectory_point)) {
            AERROR << "Invalid trajectory point ["
                   << trajectory_point.ShortDebugString() << "]";
            return;
          }
        }
      }
    }
  }

  Publish(&prediction_obstacles);
}

Status Prediction::OnError(const std::string& error_msg) {
  return Status(ErrorCode::PREDICTION_ERROR, error_msg);
}

}  // namespace prediction
}  // namespace apollo
<commit_msg>prediction: added sensors time for end to end performance evaluation.<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/prediction/prediction.h"

#include <algorithm>
#include <cmath>
#include <vector>

#include "boost/filesystem.hpp"
#include "boost/range/iterator_range.hpp"
#include "rosbag/bag.h"
#include "rosbag/view.h"

#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/math/vec2d.h"
#include "modules/common/time/time.h"
#include "modules/common/util/file.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/validation_checker.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/container/pose/pose_container.h"
#include "modules/prediction/evaluator/evaluator_manager.h"
#include "modules/prediction/predictor/predictor_manager.h"
#include "modules/prediction/proto/prediction_obstacle.pb.h"

namespace apollo {
namespace prediction {

using ::apollo::common::ErrorCode;
using ::apollo::common::Status;
using ::apollo::common::TrajectoryPoint;
using ::apollo::common::adapter::AdapterConfig;
using ::apollo::common::adapter::AdapterManager;
using ::apollo::common::math::Vec2d;
using ::apollo::common::time::Clock;
using ::apollo::common::util::DirectoryExists;
using ::apollo::common::util::Glob;
using ::apollo::localization::LocalizationEstimate;
using ::apollo::perception::PerceptionObstacle;
using ::apollo::perception::PerceptionObstacles;

std::string Prediction::Name() const { return FLAGS_prediction_module_name; }

void GetBagFiles(const boost::filesystem::path& p,
                 std::vector<std::string>* bag_files) {
  CHECK(bag_files);
  if (!boost::filesystem::exists(p)) {
    return;
  }
  if (boost::filesystem::is_regular_file(p)) {
    const auto ext = p.extension();
    if (ext == ".bag" || ext == ".BAG") {
      AINFO << "Found bag file: " << p.c_str();
      bag_files->push_back(p.c_str());
    }
    return;
  }
  if (boost::filesystem::is_directory(p)) {
    for (auto& entry : boost::make_iterator_range(
             boost::filesystem::directory_iterator(p), {})) {
      GetBagFiles(entry.path(), bag_files);
    }
  }
}
void Prediction::ProcessRosbag(const std::string& filename) {
  const std::vector<std::string> topics{FLAGS_perception_obstacle_topic,
                                        FLAGS_localization_topic};
  rosbag::Bag bag;
  try {
    bag.open(filename, rosbag::bagmode::Read);
  } catch (const rosbag::BagIOException& e) {
    AERROR << "BagIOException when open bag: " << filename
           << " Exception: " << e.what();
    bag.close();
    return;
  } catch (...) {
    AERROR << "Failed to open bag: " << filename;
    bag.close();
    return;
  }
  rosbag::View view(bag, rosbag::TopicQuery(topics));
  for (auto it = view.begin(); it != view.end(); ++it) {
    if (it->getTopic() == FLAGS_localization_topic) {
      OnLocalization(*(it->instantiate<LocalizationEstimate>()));
    } else if (it->getTopic() == FLAGS_perception_obstacle_topic) {
      RunOnce(*(it->instantiate<PerceptionObstacles>()));
    }
  }
  bag.close();
}

Status Prediction::Init() {
  start_time_ = Clock::NowInSeconds();

  // Load prediction conf
  prediction_conf_.Clear();
  if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file,
                                      &prediction_conf_)) {
    return OnError("Unable to load prediction conf file: " +
                   FLAGS_prediction_conf_file);
  } else {
    ADEBUG << "Prediction config file is loaded into: "
           << prediction_conf_.ShortDebugString();
  }

  adapter_conf_.Clear();
  if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename,
                                      &adapter_conf_)) {
    return OnError("Unable to load adapter conf file: " +
                   FLAGS_prediction_adapter_config_filename);
  } else {
    ADEBUG << "Adapter config file is loaded into: "
           << adapter_conf_.ShortDebugString();
  }

  // Initialization of all managers
  AdapterManager::Init(adapter_conf_);
  ContainerManager::instance()->Init(adapter_conf_);
  EvaluatorManager::instance()->Init(prediction_conf_);
  PredictorManager::instance()->Init(prediction_conf_);

  CHECK(AdapterManager::GetLocalization()) << "Localization is not registered.";
  CHECK(AdapterManager::GetPerceptionObstacles())
      << "Perception is not registered.";

  // Set localization callback function
  AdapterManager::AddLocalizationCallback(&Prediction::OnLocalization, this);
  // Set planning callback function
  AdapterManager::AddPlanningCallback(&Prediction::OnPlanning, this);
  // Set perception obstacle callback function
  AdapterManager::AddPerceptionObstaclesCallback(&Prediction::RunOnce, this);

  if (!FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
    return OnError("Map cannot be loaded.");
  }

  if (FLAGS_prediction_offline_mode) {
    if (!FeatureOutput::Ready()) {
      return OnError("Feature output is not ready.");
    }
    if (FLAGS_prediction_offline_bags.empty()) {
      return Status::OK();  // use listen to ROS topic mode
    }
    std::vector<std::string> inputs;
    apollo::common::util::split(FLAGS_prediction_offline_bags, ':', &inputs);
    for (const auto& input : inputs) {
      std::vector<std::string> offline_bags;
      GetBagFiles(boost::filesystem::path(input), &offline_bags);
      std::sort(offline_bags.begin(), offline_bags.end());
      AINFO << "For input " << input << ", found " << offline_bags.size()
            << "  rosbags to process";
      for (std::size_t i = 0; i < offline_bags.size(); ++i) {
        AINFO << "\tProcessing: [ " << i << " / " << offline_bags.size()
              << " ]: " << offline_bags[i];
        ProcessRosbag(offline_bags[i]);
      }
    }
    Stop();
    ros::shutdown();
  }
  return Status::OK();
}

Status Prediction::Start() { return Status::OK(); }

void Prediction::Stop() {
  if (FLAGS_prediction_offline_mode) {
    FeatureOutput::Close();
  }
}

void Prediction::OnLocalization(const LocalizationEstimate& localization) {
  PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
      ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION));
  CHECK_NOTNULL(pose_container);
  pose_container->Insert(localization);

  ADEBUG << "Received a localization message ["
         << localization.ShortDebugString() << "].";
}

void Prediction::OnPlanning(const planning::ADCTrajectory& adc_trajectory) {
  ADCTrajectoryContainer* adc_trajectory_container =
      dynamic_cast<ADCTrajectoryContainer*>(
          ContainerManager::instance()->GetContainer(
              AdapterConfig::PLANNING_TRAJECTORY));
  CHECK_NOTNULL(adc_trajectory_container);
  adc_trajectory_container->Insert(adc_trajectory);

  ADEBUG << "Received a planning message [" << adc_trajectory.ShortDebugString()
         << "].";
}

void Prediction::RunOnce(const PerceptionObstacles& perception_obstacles) {
  if (FLAGS_prediction_test_mode && FLAGS_prediction_test_duration > 0 &&
      (Clock::NowInSeconds() - start_time_ > FLAGS_prediction_test_duration)) {
    AINFO << "Prediction finished running in test mode";
    ros::shutdown();
  }

  // Update relative map if needed
  AdapterManager::Observe();
  if (FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
    AERROR << "Relative map is empty.";
    return;
  }

  double start_timestamp = Clock::NowInSeconds();

  // Insert obstacle
  ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>(
      ContainerManager::instance()->GetContainer(
          AdapterConfig::PERCEPTION_OBSTACLES));
  CHECK_NOTNULL(obstacles_container);
  obstacles_container->Insert(perception_obstacles);

  ADEBUG << "Received a perception message ["
         << perception_obstacles.ShortDebugString() << "].";

  // Update ADC status
  PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
      ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION));
  ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>(
      ContainerManager::instance()->GetContainer(
          AdapterConfig::PLANNING_TRAJECTORY));
  CHECK_NOTNULL(pose_container);
  CHECK_NOTNULL(adc_container);

  PerceptionObstacle* adc = pose_container->ToPerceptionObstacle();
  if (adc != nullptr) {
    obstacles_container->InsertPerceptionObstacle(*adc, adc->timestamp());
    double x = adc->position().x();
    double y = adc->position().y();
    ADEBUG << "Get ADC position [" << std::fixed << std::setprecision(6) << x
           << ", " << std::fixed << std::setprecision(6) << y << "].";
    Vec2d adc_position(x, y);
    adc_container->SetPosition(adc_position);
  }

  // Make evaluations
  EvaluatorManager::instance()->Run(perception_obstacles);

  // No prediction for offline mode
  if (FLAGS_prediction_offline_mode) {
    return;
  }

  // Make predictions
  PredictorManager::instance()->Run(perception_obstacles);

  auto prediction_obstacles =
      PredictorManager::instance()->prediction_obstacles();
  prediction_obstacles.set_start_timestamp(start_timestamp);
  prediction_obstacles.set_end_timestamp(Clock::NowInSeconds());
  prediction_obstacles.mutable_header()->set_lidar_timestamp(
      perception_obstacles.header().lidar_timestamp());
  prediction_obstacles.mutable_header()->set_camera_timestamp(
      perception_obstacles.header().camera_timestamp());
  prediction_obstacles.mutable_header()->set_radar_timestamp(
      perception_obstacles.header().radar_timestamp());

  if (FLAGS_prediction_test_mode) {
    for (auto const& prediction_obstacle :
         prediction_obstacles.prediction_obstacle()) {
      for (auto const& trajectory : prediction_obstacle.trajectory()) {
        for (auto const& trajectory_point : trajectory.trajectory_point()) {
          if (!ValidationChecker::ValidTrajectoryPoint(trajectory_point)) {
            AERROR << "Invalid trajectory point ["
                   << trajectory_point.ShortDebugString() << "]";
            return;
          }
        }
      }
    }
  }

  Publish(&prediction_obstacles);
}

Status Prediction::OnError(const std::string& error_msg) {
  return Status(ErrorCode::PREDICTION_ERROR, error_msg);
}

}  // namespace prediction
}  // namespace apollo
<|endoftext|>