ctkVTKMagnifyView.cpp 18 KB

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