view Framework/Viewport/WebAssemblyViewport.cpp @ 1331:ab81ee8fce1f broker

- Viewport is not passed and stored as a shared_ptr instead of raw reference. - ViewportController can now be injected with an undo stack (not a ctor param anymore, as a preparation for the move of the undo stack to an interactor) - Added (temp) flag to disable emscripten events registration in the WebAssemblyViewport (because legacy client code deals with them directly) - Added emscripten_clear_timeout in ~WebGLViewportsRegistry - Removed GenericToolbox::HoldingRef whose responsibility is better served with proper callback un-registration.
author Benjamin Golinvaux <bgo@osimis.io>
date Mon, 30 Mar 2020 14:23:46 +0200
parents fd616c4a5904
children df8bf351c23f
line wrap: on
line source

/**
 * Stone of Orthanc
 * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
 * Department, University Hospital of Liege, Belgium
 * Copyright (C) 2017-2020 Osimis S.A., Belgium
 *
 * This program is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 *
 * This program 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
 * Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 **/


#include "WebAssemblyViewport.h"

#include "../Toolbox/GenericToolbox.h"

#include <Core/OrthancException.h>

#include <boost/make_shared.hpp>
#include <boost/enable_shared_from_this.hpp>

namespace OrthancStone
{
  static void ConvertMouseEvent(PointerEvent& target,
                                const EmscriptenMouseEvent& source,
                                const ICompositor& compositor)
  {
    int x = static_cast<int>(source.targetX);
    int y = static_cast<int>(source.targetY);

    switch (source.button)
    {
      case 0:
        target.SetMouseButton(MouseButton_Left);
        break;

      case 1:
        target.SetMouseButton(MouseButton_Middle);
        break;

      case 2:
        target.SetMouseButton(MouseButton_Right);
        break;

      default:
        target.SetMouseButton(MouseButton_None);
        break;
    }
      
    target.AddPosition(compositor.GetPixelCenterCoordinates(x, y));
    target.SetAltModifier(source.altKey);
    target.SetControlModifier(source.ctrlKey);
    target.SetShiftModifier(source.shiftKey);
  }


  class WebAssemblyViewport::WasmLock : public ILock
  {
  private:
    WebAssemblyViewport& that_;

  public:
    WasmLock(WebAssemblyViewport& that) :
      that_(that)
    {
    }

    virtual bool HasCompositor() const ORTHANC_OVERRIDE
    {
      return that_.compositor_.get() != NULL;
    }

    virtual ICompositor& GetCompositor() ORTHANC_OVERRIDE
    {
      if (that_.compositor_.get() == NULL)
      {
        throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls);
      }
      else
      {
        return *that_.compositor_;
      }
    }

    virtual ViewportController& GetController() ORTHANC_OVERRIDE
    {
      assert(that_.controller_);
      return *that_.controller_;
    }

    virtual void Invalidate() ORTHANC_OVERRIDE
    {
      that_.Invalidate();
    }
  };


  EM_BOOL WebAssemblyViewport::OnRequestAnimationFrame(double time, void *userData)
  {
    LOG(TRACE) << __func__;
    WebAssemblyViewport* that = reinterpret_cast<WebAssemblyViewport*>(userData);

    if (that->compositor_.get() != NULL &&
        that->controller_ /* should always be true */)
    {
      that->Paint(*that->compositor_, *that->controller_);
    }
      
    LOG(TRACE) << "Exiting: " << __func__;
    return true;
  }

  EM_BOOL WebAssemblyViewport::OnResize(int eventType, const EmscriptenUiEvent *uiEvent, void *userData)
  {
    LOG(TRACE) << __func__;
    WebAssemblyViewport* that = reinterpret_cast<WebAssemblyViewport*>(userData);

    if (that->compositor_.get() != NULL)
    {
      that->UpdateSize(*that->compositor_);
      that->Invalidate();
    }
      
    LOG(TRACE) << "Exiting: " << __func__;
    return true;
  }


  EM_BOOL WebAssemblyViewport::OnMouseDown(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData)
  {
    WebAssemblyViewport* that = reinterpret_cast<WebAssemblyViewport*>(userData);

    LOG(TRACE) << "mouse down: " << that->GetFullCanvasId();      

    if (that->compositor_.get() != NULL &&
        that->interactor_.get() != NULL)
    {
      PointerEvent pointer;
      ConvertMouseEvent(pointer, *mouseEvent, *that->compositor_);

      that->controller_->HandleMousePress(*that->interactor_, pointer,
                                         that->compositor_->GetCanvasWidth(),
                                         that->compositor_->GetCanvasHeight());        
      that->Invalidate();
    }

    LOG(TRACE) << "Exiting: " << __func__;
    return true;
  }

    
  EM_BOOL WebAssemblyViewport::OnMouseMove(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData)
  {
    LOG(TRACE) << "WebAssemblyViewport::OnMouseMove CP1. userData = " << userData;
    
    WebAssemblyViewport* that = reinterpret_cast<WebAssemblyViewport*>(userData);
    LOG(TRACE) << "WebAssemblyViewport::OnMouseMove CP2";

    if (that->compositor_.get() != NULL &&
        that->controller_->HasActiveTracker())
    {
      LOG(TRACE) << "WebAssemblyViewport::OnMouseMove CP3";
      PointerEvent pointer;
      ConvertMouseEvent(pointer, *mouseEvent, *that->compositor_);
      LOG(TRACE) << "WebAssemblyViewport::OnMouseMove CP4";
      if (that->controller_->HandleMouseMove(pointer))
      {
        LOG(TRACE) << "WebAssemblyViewport::OnMouseMove CP5";
        that->Invalidate();
        LOG(TRACE) << "WebAssemblyViewport::OnMouseMove CP6";
      }
    }

    LOG(TRACE) << "Exiting: " << __func__;
    return true;
  }
    
  EM_BOOL WebAssemblyViewport::OnMouseUp(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData)
  {
    LOG(TRACE) << __func__;
    WebAssemblyViewport* that = reinterpret_cast<WebAssemblyViewport*>(userData);

    if (that->compositor_.get() != NULL)
    {
      PointerEvent pointer;
      ConvertMouseEvent(pointer, *mouseEvent, *that->compositor_);
      that->controller_->HandleMouseRelease(pointer);
      that->Invalidate();
    }

    LOG(TRACE) << "Exiting: " << __func__;
    return true;
  }

  void WebAssemblyViewport::Invalidate()
  {
    emscripten_request_animation_frame(OnRequestAnimationFrame, reinterpret_cast<void*>(this));
  }

  void WebAssemblyViewport::AcquireCompositor(ICompositor* compositor /* takes ownership */)
  {
    if (compositor == NULL)
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_NullPointer);
    }
    else
    {
      compositor_.reset(compositor);
    }
  }

  WebAssemblyViewport::WebAssemblyViewport(
    const std::string& canvasId, bool enableEmscriptenEvents) :
    shortCanvasId_(canvasId),
    fullCanvasId_(canvasId),
    interactor_(new DefaultViewportInteractor),
    enableEmscriptenEvents_(enableEmscriptenEvents)
  {
  }

  void WebAssemblyViewport::PostConstructor()
  {
    boost::shared_ptr<IViewport> viewport = shared_from_this();
    controller_.reset(new ViewportController(viewport));

    LOG(INFO) << "Initializing Stone viewport on HTML canvas: " 
      << shortCanvasId_;

    if (shortCanvasId_.empty() ||
        shortCanvasId_[0] == '#')
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_ParameterOutOfRange,
        "The canvas identifier must not start with '#'");
    }

    // Disable right-click on the canvas (i.e. context menu)
    EM_ASM({
        document.getElementById(UTF8ToString($0)).oncontextmenu = 
        function(event)
        {
          event.preventDefault();
        }
      },
      shortCanvasId_.c_str()   // $0
      );

    if (enableEmscriptenEvents_)
    {
      // It is not possible to monitor the resizing of individual
      // canvas, so we track the full window of the browser
      emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW,
                                     reinterpret_cast<void*>(this),
                                     false,
                                     OnResize);

      emscripten_set_mousedown_callback(fullCanvasId_.c_str(),
                                        reinterpret_cast<void*>(this),
                                        false,
                                        OnMouseDown);

      emscripten_set_mousemove_callback(fullCanvasId_.c_str(),
                                        reinterpret_cast<void*>(this),
                                        false,
                                        OnMouseMove);

      emscripten_set_mouseup_callback(fullCanvasId_.c_str(),
                                      reinterpret_cast<void*>(this),
                                      false,
                                      OnMouseUp);
    }
  }

  WebAssemblyViewport::~WebAssemblyViewport()
  {
    if (enableEmscriptenEvents_)
    {
      emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW,
                                     reinterpret_cast<void*>(this),
                                     false,
                                     NULL);

      emscripten_set_mousedown_callback(fullCanvasId_.c_str(),
                                        reinterpret_cast<void*>(this),
                                        false,
                                        OnMouseDown);

      emscripten_set_mousemove_callback(fullCanvasId_.c_str(),
                                        reinterpret_cast<void*>(this),
                                        false,
                                        OnMouseMove);

      emscripten_set_mouseup_callback(fullCanvasId_.c_str(),
                                      reinterpret_cast<void*>(this),
                                      false,
                                      OnMouseUp);
    }
  }
  
  IViewport::ILock* WebAssemblyViewport::Lock()
  {
    return new WasmLock(*this);
  }
  
  void WebAssemblyViewport::AcquireInteractor(IViewportInteractor* interactor)
  {
    if (interactor == NULL)
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_NullPointer);
    }
    else
    {
      interactor_.reset(interactor);
    }
  }
}