ctkVTKMagnifyView.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. /*=========================================================================
  2. Library: CTK
  3. Copyright (c) Kitware Inc.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0.txt
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. =========================================================================*/
  14. // Qt includes
  15. #include <QEvent>
  16. #include <QMouseEvent>
  17. #include <QPointF>
  18. #include <QTimerEvent>
  19. // CTK includes
  20. #include "ctkVTKMagnifyView.h"
  21. #include "ctkVTKMagnifyView_p.h"
  22. #include "ctkLogger.h"
  23. // VTK includes
  24. #include <QVTKWidget.h>
  25. #include <vtkMath.h>
  26. #include <vtkRenderWindow.h>
  27. #include <vtkUnsignedCharArray.h>
  28. // STD includes
  29. #include <cmath>
  30. // Convenient macro
  31. #define VTK_CREATE(type, name) \
  32. vtkSmartPointer<type> name = vtkSmartPointer<type>::New()
  33. //--------------------------------------------------------------------------
  34. static ctkLogger logger("org.commontk.visualization.vtk.widgets.ctkVTKMagnifyView");
  35. //--------------------------------------------------------------------------
  36. // --------------------------------------------------------------------------
  37. // ctkVTKMagnifyViewPrivate methods
  38. // --------------------------------------------------------------------------
  39. ctkVTKMagnifyViewPrivate::ctkVTKMagnifyViewPrivate(ctkVTKMagnifyView& object)
  40. : QObject(&object), q_ptr(&object)
  41. {
  42. this->ObservedQVTKWidgets = QList<QVTKWidget *>();
  43. this->Magnification = 1.0;
  44. this->ObserveRenderWindowEvents = true;
  45. this->EventHandler.EventType = NoEvent;
  46. this->EventHandler.Position = QPointF(0,0);
  47. this->EventHandler.UpdateInterval = 20;
  48. this->EventHandler.TimerId = 0;
  49. }
  50. // --------------------------------------------------------------------------
  51. ctkVTKMagnifyViewPrivate::~ctkVTKMagnifyViewPrivate()
  52. {
  53. if (this->EventHandler.TimerId != 0)
  54. {
  55. this->killTimer(this->EventHandler.TimerId);
  56. }
  57. }
  58. // --------------------------------------------------------------------------
  59. void ctkVTKMagnifyViewPrivate::init()
  60. {
  61. // Start by removing the pixmap
  62. this->EventHandler.EventType = RemovePixmapEvent;
  63. this->removePixmap();
  64. // Start the timer
  65. this->restartTimer();
  66. }
  67. // --------------------------------------------------------------------------
  68. void ctkVTKMagnifyViewPrivate::restartTimer()
  69. {
  70. // Kill any old timers
  71. if (this->EventHandler.TimerId != 0)
  72. {
  73. this->killTimer(this->EventHandler.TimerId);
  74. this->EventHandler.TimerId = 0;
  75. }
  76. // Start timer if appropriate
  77. if (this->EventHandler.UpdateInterval != 0)
  78. {
  79. this->EventHandler.TimerId = this->startTimer(this->EventHandler.UpdateInterval);
  80. Q_ASSERT(this->EventHandler.TimerId);
  81. }
  82. // Not using any timers, process events as they come
  83. else
  84. {
  85. this->EventHandler.TimerId = 0;
  86. }
  87. }
  88. // --------------------------------------------------------------------------
  89. void ctkVTKMagnifyViewPrivate::resetEventHandler()
  90. {
  91. this->EventHandler.EventType = NoEvent;
  92. }
  93. // --------------------------------------------------------------------------
  94. void ctkVTKMagnifyViewPrivate::timerEvent(QTimerEvent * event)
  95. {
  96. Q_ASSERT(event->timerId() == this->EventHandler.TimerId);
  97. if (this->EventHandler.EventType == UpdatePixmapEvent)
  98. {
  99. this->updatePixmap();
  100. }
  101. else if (this->EventHandler.EventType == RemovePixmapEvent)
  102. {
  103. this->removePixmap();
  104. }
  105. }
  106. // --------------------------------------------------------------------------
  107. void ctkVTKMagnifyViewPrivate::pushUpdatePixmapEvent()
  108. {
  109. if (this->EventHandler.Widget.isNull())
  110. {
  111. return;
  112. }
  113. this->pushUpdatePixmapEvent(
  114. this->EventHandler.Widget.data()->mapFromGlobal(QCursor::pos()));
  115. }
  116. // --------------------------------------------------------------------------
  117. void ctkVTKMagnifyViewPrivate::pushUpdatePixmapEvent(QPointF pos)
  118. {
  119. if (this->EventHandler.Widget.isNull())
  120. {
  121. return;
  122. }
  123. // Add this event to the queue
  124. this->EventHandler.EventType = UpdatePixmapEvent;
  125. this->EventHandler.Position = pos;
  126. // Process the event if we handle all events
  127. if (this->EventHandler.UpdateInterval == 0)
  128. {
  129. this->updatePixmap();
  130. }
  131. }
  132. // --------------------------------------------------------------------------
  133. void ctkVTKMagnifyViewPrivate::pushRemovePixmapEvent()
  134. {
  135. // Add this event to the queue
  136. this->EventHandler.EventType = RemovePixmapEvent;
  137. // Process the event if we handle all events
  138. if (this->EventHandler.UpdateInterval == 0)
  139. {
  140. this->removePixmap();
  141. }
  142. }
  143. // --------------------------------------------------------------------------
  144. void ctkVTKMagnifyViewPrivate::connectRenderWindow(QVTKWidget * widget)
  145. {
  146. Q_ASSERT(widget);
  147. Q_ASSERT(this->ObserveRenderWindowEvents);
  148. vtkRenderWindow * renderWindow = widget->GetRenderWindow();
  149. if (renderWindow)
  150. {
  151. this->qvtkConnect(renderWindow, vtkCommand::EndEvent,
  152. this, SLOT(pushUpdatePixmapEvent()));
  153. }
  154. }
  155. // --------------------------------------------------------------------------
  156. void ctkVTKMagnifyViewPrivate::disconnectRenderWindow(QVTKWidget * widget)
  157. {
  158. Q_ASSERT(widget);
  159. vtkRenderWindow * renderWindow = widget->GetRenderWindow();
  160. if (renderWindow)
  161. {
  162. this->qvtkDisconnect(renderWindow, vtkCommand::EndEvent,
  163. this, SLOT(pushUpdatePixmapEvent()));
  164. }
  165. }
  166. // --------------------------------------------------------------------------
  167. void ctkVTKMagnifyViewPrivate::observe(QVTKWidget * widget)
  168. {
  169. Q_ASSERT(widget);
  170. // If we are not already observing the widget, add it to the list and install
  171. // the public implementation as the event filter to handle mousing
  172. if (!this->ObservedQVTKWidgets.contains(widget))
  173. {
  174. this->ObservedQVTKWidgets.append(widget);
  175. Q_Q(ctkVTKMagnifyView);
  176. widget->installEventFilter(q);
  177. if (this->ObserveRenderWindowEvents)
  178. {
  179. this->connectRenderWindow(widget);
  180. }
  181. }
  182. }
  183. // --------------------------------------------------------------------------
  184. void ctkVTKMagnifyViewPrivate::remove(QVTKWidget * widget)
  185. {
  186. Q_ASSERT(widget);
  187. // If we are observing the widget, remove it from the list and remove the
  188. // public implementations event filtering
  189. if (this->ObservedQVTKWidgets.contains(widget))
  190. {
  191. Q_ASSERT(this->ObservedQVTKWidgets.count(widget) == 1);
  192. this->ObservedQVTKWidgets.removeOne(widget);
  193. Q_Q(ctkVTKMagnifyView);
  194. widget->removeEventFilter(q);
  195. if (this->ObserveRenderWindowEvents)
  196. {
  197. this->disconnectRenderWindow(widget);
  198. }
  199. }
  200. }
  201. // --------------------------------------------------------------------------
  202. void ctkVTKMagnifyViewPrivate::removePixmap()
  203. {
  204. Q_ASSERT(this->EventHandler.EventType == RemovePixmapEvent);
  205. Q_Q(ctkVTKMagnifyView);
  206. QPixmap nullPixmap;
  207. q->setPixmap(nullPixmap);
  208. q->update();
  209. this->resetEventHandler();
  210. }
  211. // -------------------------------------------------------------------------
  212. void ctkVTKMagnifyViewPrivate::updatePixmap()
  213. {
  214. Q_ASSERT(this->EventHandler.EventType == UpdatePixmapEvent);
  215. Q_ASSERT(!this->EventHandler.Widget.isNull());
  216. Q_Q(ctkVTKMagnifyView);
  217. // Retrieve buffer of given QVTKWidget from its render window
  218. vtkRenderWindow * renderWindow = this->EventHandler.Widget.data()->GetRenderWindow();
  219. if (!renderWindow)
  220. {
  221. return;
  222. }
  223. // Get the window size and mouse position, and do error checking
  224. QPointF pos = this->EventHandler.Position;
  225. int * windowSize = renderWindow->GetSize();
  226. QPointF mouseWindowPos(pos.x(), static_cast<double>(windowSize[1]-1)-pos.y());
  227. if (mouseWindowPos.x() < 0 || mouseWindowPos.x() >= windowSize[0] ||
  228. mouseWindowPos.y() < 0 || mouseWindowPos.y() >= windowSize[1])
  229. {
  230. return;
  231. }
  232. // Compute indices into the render window's data array
  233. // Given a magnification and the label's widget size, compute the number of
  234. // pixels we can show. We should round to get a larger integer extent, since
  235. // we will later adjust the pixmap's location in paintEvent().
  236. // Left-right and up-down are in the render window coordinate frame.
  237. // (which is different in the y-direction compared to Qt coordinates).
  238. QSizeF sizeToMagnify = QSizeF(q->size()) / this->Magnification;
  239. double posLeft = (mouseWindowPos.x() - ((sizeToMagnify.width()-1.0) / 2.0));
  240. double posRight = (mouseWindowPos.x() + ((sizeToMagnify.width()-1.0) / 2.0));
  241. double posBottom = (mouseWindowPos.y() - ((sizeToMagnify.height()-1.0) / 2.0));
  242. double posTop = (mouseWindowPos.y() + ((sizeToMagnify.height()-1.0) / 2.0));
  243. // Round to ints, for indexing into the pixel array
  244. int indexLeft = std::floor(posLeft);
  245. int indexRight = std::ceil(posRight);
  246. int indexBottom = std::floor(posBottom);
  247. int indexTop = std::ceil(posTop);
  248. // Handle when mouse is near the border
  249. int minLeft = 0;
  250. int maxRight = windowSize[0]-1;
  251. int minBottom = 0;
  252. int maxTop = windowSize[1]-1;
  253. bool overLeft = indexLeft < minLeft;
  254. bool overRight = indexRight > maxRight;
  255. bool overBottom = indexBottom < minBottom;
  256. bool overTop = indexTop > maxTop;
  257. // Ensure we don't access nonexistant indices
  258. if (overLeft)
  259. {
  260. indexLeft = minLeft;
  261. posLeft = minLeft;
  262. }
  263. if (overRight)
  264. {
  265. indexRight = maxRight;
  266. posRight = maxRight;
  267. }
  268. if (overBottom)
  269. {
  270. indexBottom = minBottom;
  271. posBottom = minBottom;
  272. }
  273. if (overTop)
  274. {
  275. indexTop = maxTop;
  276. posTop = maxTop;
  277. }
  278. // Error case
  279. if (indexLeft > indexRight || indexBottom > indexTop)
  280. {
  281. return;
  282. }
  283. // Setup the pixelmap's position in the label
  284. Qt::Alignment alignment;
  285. if (overLeft && !overRight)
  286. {
  287. alignment = Qt::AlignRight;
  288. }
  289. else if (overRight && !overLeft)
  290. {
  291. alignment = Qt::AlignLeft;
  292. }
  293. else
  294. {
  295. alignment = Qt::AlignLeft;
  296. }
  297. if (overBottom && !overTop)
  298. {
  299. alignment = alignment | Qt::AlignTop;
  300. }
  301. else if (overTop && !overBottom)
  302. {
  303. alignment = alignment | Qt::AlignBottom;
  304. }
  305. else
  306. {
  307. alignment = alignment | Qt::AlignTop;
  308. }
  309. q->setAlignment(alignment);
  310. // Retrieve the pixel data into a QImage (flip vertically to move from render
  311. // window coordinates to Qt coordinates)
  312. QSize actualSize(indexRight-indexLeft+1, indexTop-indexBottom+1);
  313. QImage image(actualSize.width(), actualSize.height(), QImage::Format_RGB32);
  314. vtkUnsignedCharArray * pixelData = vtkUnsignedCharArray::New();
  315. pixelData->SetArray(image.bits(), actualSize.width() * actualSize.height() * 4, 1);
  316. int front = renderWindow->GetDoubleBuffer();
  317. int success = renderWindow->GetRGBACharPixelData(
  318. indexLeft, indexBottom, indexRight, indexTop, front, pixelData);
  319. if (!success)
  320. {
  321. return;
  322. }
  323. pixelData->Delete();
  324. image = image.rgbSwapped();
  325. image = image.mirrored();
  326. // Scale the image to zoom, using FastTransformation to prevent smoothing
  327. QSize imageSize = actualSize * this->Magnification;
  328. image = image.scaled(imageSize, Qt::KeepAspectRatioByExpanding,
  329. Qt::FastTransformation);
  330. // Crop the magnified image to solve the problem of magnified partial pixels
  331. double errorLeft
  332. = (posLeft - static_cast<double>(indexLeft)) * this->Magnification;
  333. double errorRight
  334. = (static_cast<double>(indexRight) - posRight) * this->Magnification;
  335. double errorBottom
  336. = (posBottom - static_cast<double>(indexBottom)) * this->Magnification;
  337. double errorTop
  338. = (static_cast<double>(indexTop) - posTop) * this->Magnification;
  339. // When cropping the Qt image, the 'adjust' variables are in Qt coordinates,
  340. // not render window coordinates (bottom and top switch).
  341. int cropIndexLeft = vtkMath::Round(errorLeft);
  342. int cropIndexRight = imageSize.width() - vtkMath::Round(errorRight) - 1;
  343. int cropIndexTop = vtkMath::Round(errorTop);
  344. int cropIndexBottom = imageSize.height() - vtkMath::Round(errorBottom) - 1;
  345. // Handle case when label size and magnification are not both even or odd
  346. // (errorLeft/errorRight/errorBottom/errorTop will have fractional component,
  347. // so cropped image wouldn't be the correct size unless we adjust further).
  348. int requiredWidth = vtkMath::Round((posRight - posLeft + 1) * this->Magnification);
  349. int requiredHeight = vtkMath::Round((posTop - posBottom + 1) * this->Magnification);
  350. int actualWidth = cropIndexRight - cropIndexLeft + 1;
  351. int actualHeight = cropIndexBottom - cropIndexTop + 1;
  352. int diffWidth = requiredWidth - actualWidth;
  353. int diffHeight = requiredHeight - actualHeight;
  354. // Too wide
  355. if (diffWidth < 0 && cropIndexRight != imageSize.width()-1)
  356. {
  357. Q_ASSERT(actualWidth - requiredWidth <= 1);
  358. cropIndexRight += diffWidth;
  359. }
  360. // Too narrow
  361. else if (diffWidth > 0 && cropIndexLeft != 0)
  362. {
  363. Q_ASSERT(requiredWidth - actualWidth <= 1);
  364. cropIndexLeft -= diffWidth;
  365. }
  366. // Too tall
  367. if (diffHeight < 0 && cropIndexBottom != imageSize.height()-1)
  368. {
  369. Q_ASSERT(actualHeight - requiredHeight <= 1);
  370. cropIndexBottom += diffHeight;
  371. }
  372. // Too short
  373. else if (diffHeight > 0 && cropIndexTop != 0)
  374. {
  375. Q_ASSERT(requiredHeight - actualHeight <= 1);
  376. cropIndexTop -= diffHeight;
  377. }
  378. // Finally crop the QImage for display
  379. QRect cropRect(QPoint(cropIndexLeft, cropIndexTop),
  380. QPoint(cropIndexRight, cropIndexBottom));
  381. image = image.copy(cropRect);
  382. // Finally, set the pixelmap to the new one we have created and update
  383. q->setPixmap(QPixmap::fromImage(image));
  384. q->update();
  385. this->resetEventHandler();
  386. }
  387. //---------------------------------------------------------------------------
  388. // ctkVTKMagnifyView methods
  389. // --------------------------------------------------------------------------
  390. ctkVTKMagnifyView::ctkVTKMagnifyView(QWidget* parentWidget)
  391. : Superclass(parentWidget)
  392. , d_ptr(new ctkVTKMagnifyViewPrivate(*this))
  393. {
  394. Q_D(ctkVTKMagnifyView);
  395. d->init();
  396. }
  397. // --------------------------------------------------------------------------
  398. ctkVTKMagnifyView::~ctkVTKMagnifyView()
  399. {
  400. }
  401. // --------------------------------------------------------------------------
  402. CTK_GET_CPP(ctkVTKMagnifyView, double, magnification, Magnification)
  403. // --------------------------------------------------------------------------
  404. void ctkVTKMagnifyView::setMagnification(double newMagnification)
  405. {
  406. Q_D(ctkVTKMagnifyView);
  407. if (newMagnification == d->Magnification || newMagnification <= 0)
  408. {
  409. return;
  410. }
  411. d->Magnification = newMagnification;
  412. this->update();
  413. }
  414. // --------------------------------------------------------------------------
  415. CTK_GET_CPP(ctkVTKMagnifyView, bool,
  416. observeRenderWindowEvents, ObserveRenderWindowEvents)
  417. // --------------------------------------------------------------------------
  418. void ctkVTKMagnifyView::setObserveRenderWindowEvents(bool newObserve)
  419. {
  420. Q_D(ctkVTKMagnifyView);
  421. if (newObserve == d->ObserveRenderWindowEvents)
  422. {
  423. return;
  424. }
  425. d->ObserveRenderWindowEvents = newObserve;
  426. // Connect/disconnect observations on vtkRenderWindow EndEvents, depending
  427. // on whether we are switching from not-observing to observing or from
  428. // observing to not-observing
  429. QList<QVTKWidget *>::iterator it = d->ObservedQVTKWidgets.begin();
  430. while (it != d->ObservedQVTKWidgets.end())
  431. {
  432. if (newObserve)
  433. {
  434. d->connectRenderWindow(*it);
  435. }
  436. else
  437. {
  438. d->disconnectRenderWindow(*it);
  439. }
  440. ++it;
  441. }
  442. }
  443. // --------------------------------------------------------------------------
  444. int ctkVTKMagnifyView::updateInterval() const
  445. {
  446. Q_D(const ctkVTKMagnifyView);
  447. return d->EventHandler.UpdateInterval;
  448. }
  449. // --------------------------------------------------------------------------
  450. void ctkVTKMagnifyView::setUpdateInterval(int newInterval)
  451. {
  452. Q_D(ctkVTKMagnifyView);
  453. if (newInterval == d->EventHandler.UpdateInterval || newInterval < 0)
  454. {
  455. return;
  456. }
  457. d->EventHandler.UpdateInterval = newInterval;
  458. d->restartTimer();
  459. }
  460. // --------------------------------------------------------------------------
  461. void ctkVTKMagnifyView::observe(QVTKWidget * widget)
  462. {
  463. Q_D(ctkVTKMagnifyView);
  464. if (widget)
  465. {
  466. d->observe(widget);
  467. }
  468. }
  469. // --------------------------------------------------------------------------
  470. void ctkVTKMagnifyView::observe(QList<QVTKWidget *> widgets)
  471. {
  472. foreach(QVTKWidget * widget, widgets)
  473. {
  474. this->observe(widget);
  475. }
  476. }
  477. // --------------------------------------------------------------------------
  478. bool ctkVTKMagnifyView::isObserved(QVTKWidget * widget) const
  479. {
  480. if (!widget)
  481. {
  482. return false;
  483. }
  484. Q_D(const ctkVTKMagnifyView);
  485. return d->ObservedQVTKWidgets.contains(widget);
  486. }
  487. // --------------------------------------------------------------------------
  488. int ctkVTKMagnifyView::numberObserved() const
  489. {
  490. Q_D(const ctkVTKMagnifyView);
  491. return d->ObservedQVTKWidgets.length();
  492. }
  493. // --------------------------------------------------------------------------
  494. void ctkVTKMagnifyView::remove(QVTKWidget * widget)
  495. {
  496. Q_D(ctkVTKMagnifyView);
  497. if (widget)
  498. {
  499. d->remove(widget);
  500. }
  501. }
  502. // --------------------------------------------------------------------------
  503. void ctkVTKMagnifyView::remove(QList<QVTKWidget *> widgets)
  504. {
  505. foreach(QVTKWidget * widget, widgets)
  506. {
  507. this->remove(widget);
  508. }
  509. }
  510. // --------------------------------------------------------------------------
  511. bool ctkVTKMagnifyView::eventFilter(QObject * obj, QEvent * event)
  512. {
  513. // The given object should be a QVTKWidget in our list
  514. QVTKWidget * widget = static_cast<QVTKWidget *>(obj);
  515. Q_ASSERT(widget);
  516. Q_D(ctkVTKMagnifyView);
  517. Q_ASSERT(d->ObservedQVTKWidgets.contains(widget));
  518. d->EventHandler.Widget = QWeakPointer<QVTKWidget>(widget);
  519. QEvent::Type eventType = event->type();
  520. // On mouse move, update the pixmap with the zoomed image
  521. if (eventType == QEvent::MouseMove)
  522. {
  523. QMouseEvent * mouseEvent = static_cast<QMouseEvent *>(event);
  524. Q_ASSERT(mouseEvent);
  525. d->pushUpdatePixmapEvent(mouseEvent->posF());
  526. }
  527. // On enter, update the pixmap with the zoomed image (required for zooming when
  528. // widget is created with mouse already within it), and emit signal of enter event
  529. else if (eventType == QEvent::Enter)
  530. {
  531. d->pushUpdatePixmapEvent();
  532. emit enteredObservedWidget(widget);
  533. }
  534. // On leave, fill the pixmap with a solid color and emit signal of leave event
  535. else if (eventType == QEvent::Leave)
  536. {
  537. d->pushRemovePixmapEvent();
  538. emit leftObservedWidget(widget);
  539. }
  540. // For other event types, use standard event processing
  541. else
  542. {
  543. return QObject::eventFilter(obj, event);
  544. }
  545. return false;
  546. }