forked from mxcube/HardwareObjects
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Qt4_GraphicsManager.py
1570 lines (1351 loc) · 61.4 KB
/
Qt4_GraphicsManager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Project: MXCuBE
# https://github.com/mxcube.
#
# This file is part of MXCuBE software.
#
# MXCuBE is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# MXCuBE 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with MXCuBE. If not, see <http://www.gnu.org/licenses/>.
"""
Qt4_GraphicsManager keeps track of the current shapes the user has created.
All shapes (graphics items) are based on Qt native QGraphicsLib.GraphicsItem objects.
QGraphicsScene and QGraphicsView are used to display objects
example xml:
<object class="Qt4_GraphicsManager">
<object href="/Qt4_mini-diff-mockup" role="diffractometer"/>
<object href="/beam-info" role="beam_info"/>
</object>
"""
import os
import atexit
import tempfile
import logging
import numpy as np
from copy import deepcopy
from scipy import ndimage
from scipy.interpolate import splrep, sproot
from PyQt4 import QtGui
from PyQt4 import QtCore
import Qt4_GraphicsLib as GraphicsLib
import queue_model_objects_v1 as queue_model_objects
from HardwareRepository.BaseHardwareObjects import HardwareObject
class Qt4_GraphicsManager(HardwareObject):
"""
Descript. : Keeps track of the current shapes the user has created. The
Diffractometer and BeamInfo hardware objects are mandotary
"""
def __init__(self, name):
"""
:param name: name
:type name: str
"""
HardwareObject.__init__(self, name)
self.diffractometer_hwobj = None
self.camera_hwobj = None
self.beam_info_hwobj = None
self.pixels_per_mm = [0, 0]
self.beam_position = [0, 0]
self.beam_info_dict = {}
self.graphics_scene_size = [0, 0]
self.mouse_position = [0, 0]
self.image_scale = None
self.image_scale_list = []
self.auto_grid = None
self.auto_grid_size_mm = (0, 0)
self.omega_axis_info_dict = {}
self.in_centring_state = None
self.in_grid_drawing_state = None
self.in_measure_distance_state = None
self.in_measure_angle_state = None
self.in_measure_area_state = None
self.in_move_beam_mark_state = None
self.in_select_items_state = None
self.in_beam_define_state = None
self.wait_grid_drawing_click = None
self.wait_measure_distance_click = None
self.wait_measure_angle_click = None
self.wait_measure_area_click = None
self.wait_beam_define_click = None
self.current_centring_method = None
self.point_count = 0
self.line_count = 0
self.grid_count = 0
self.shape_dict = {}
self.graphics_view = None
self.graphics_camera_frame = None
self.graphics_beam_item = None
self.graphics_scale_item = None
self.graphics_omega_reference_item = None
self.graphics_centring_lines_item = None
self.graphics_grid_draw_item = None
self.graphics_measure_distance_item = None
self.graphics_measure_angle_item = None
self.graphics_measure_area_item = None
self.graphics_move_beam_mark_item = None
self.graphics_select_tool_item = None
self.graphics_beam_define_item = None
def init(self):
"""Main init function. Initiates all graphics items, hwobjs and
connects all qt signals to slots.
"""
self.graphics_view = GraphicsLib.GraphicsView()
self.graphics_camera_frame = GraphicsLib.GraphicsCameraFrame()
self.graphics_scale_item = GraphicsLib.GraphicsItemScale(self)
self.graphics_omega_reference_item = \
GraphicsLib.GraphicsItemOmegaReference(self)
self.graphics_beam_item = GraphicsLib.GraphicsItemBeam(self)
self.graphics_info_item = GraphicsLib.GraphicsItemInfo(self)
self.graphics_info_item.hide()
self.graphics_move_beam_mark_item = \
GraphicsLib.GraphicsItemMoveBeamMark(self)
self.graphics_move_beam_mark_item.hide()
self.graphics_centring_lines_item = \
GraphicsLib.GraphicsItemCentringLines(self)
self.graphics_centring_lines_item.hide()
self.graphics_measure_distance_item = \
GraphicsLib.GraphicsItemMeasureDistance(self)
self.graphics_measure_distance_item.hide()
self.graphics_measure_angle_item = \
GraphicsLib.GraphicsItemMeasureAngle(self)
self.graphics_measure_angle_item.hide()
self.graphics_measure_area_item = \
GraphicsLib.GraphicsItemMeasureArea(self)
self.graphics_measure_area_item.hide()
self.graphics_select_tool_item = GraphicsLib.GraphicsSelectTool(self)
self.graphics_select_tool_item.hide()
self.graphics_beam_define_item = GraphicsLib.GraphicsItemBeamDefine(self)
self.graphics_beam_define_item.hide()
self.graphics_view.graphics_scene.addItem(self.graphics_camera_frame)
self.graphics_view.graphics_scene.addItem(self.graphics_omega_reference_item)
self.graphics_view.graphics_scene.addItem(self.graphics_beam_item)
self.graphics_view.graphics_scene.addItem(self.graphics_info_item)
self.graphics_view.graphics_scene.addItem(self.graphics_move_beam_mark_item)
self.graphics_view.graphics_scene.addItem(self.graphics_centring_lines_item)
self.graphics_view.graphics_scene.addItem(self.graphics_scale_item)
self.graphics_view.graphics_scene.addItem(self.graphics_measure_distance_item)
self.graphics_view.graphics_scene.addItem(self.graphics_measure_angle_item)
self.graphics_view.graphics_scene.addItem(self.graphics_measure_area_item)
self.graphics_view.graphics_scene.addItem(self.graphics_select_tool_item)
self.graphics_view.graphics_scene.addItem(self.graphics_beam_define_item)
self.graphics_view.scene().mouseClickedSignal.connect(\
self.mouse_clicked)
self.graphics_view.scene().mouseDoubleClickedSignal.connect(\
self.mouse_double_clicked)
self.graphics_view.scene().mouseReleasedSignal.connect(\
self.mouse_released)
self.graphics_view.scene().itemClickedSignal.connect(\
self.item_clicked)
self.graphics_view.scene().itemDoubleClickedSignal.connect(\
self.item_double_clicked)
self.graphics_view.mouseMovedSignal.connect(self.mouse_moved)
self.graphics_view.keyPressedSignal.connect(self.key_pressed)
self.graphics_view.wheelSignal.connect(self.mouse_wheel_scrolled)
self.diffractometer_hwobj = self.getObjectByRole("diffractometer")
pixels_per_mm = self.diffractometer_hwobj.get_pixels_per_mm()
self.diffractometer_pixels_per_mm_changed(pixels_per_mm)
GraphicsLib.GraphicsItemGrid.set_grid_direction(\
self.diffractometer_hwobj.get_grid_direction())
self.connect(self.diffractometer_hwobj, "minidiffStateChanged",
self.diffractometer_state_changed)
self.connect(self.diffractometer_hwobj, "centringStarted",
self.diffractometer_centring_started)
self.connect(self.diffractometer_hwobj, "centringAccepted",
self.create_centring_point)
self.connect(self.diffractometer_hwobj, "centringSuccessful",
self.diffractometer_centring_successful)
self.connect(self.diffractometer_hwobj, "centringFailed",
self.diffractometer_centring_failed)
self.connect(self.diffractometer_hwobj, "pixelsPerMmChanged",
self.diffractometer_pixels_per_mm_changed)
self.connect(self.diffractometer_hwobj, "omegaReferenceChanged",
self.diffractometer_omega_reference_changed)
self.connect(self.diffractometer_hwobj, "phiMotorMoved",
self.diffractometer_phi_motor_moved)
self.connect(self.diffractometer_hwobj, "minidiffPhaseChanged",
self.diffractometer_phase_changed)
self.beam_info_hwobj = self.getObjectByRole("beam_info")
if self.beam_info_hwobj is not None:
self.beam_info_dict = self.beam_info_hwobj.get_beam_info()
self.beam_position = self.beam_info_hwobj.get_beam_position()
self.connect(self.beam_info_hwobj,
"beamPosChanged",
self.beam_position_changed)
self.connect(self.beam_info_hwobj,
"beamInfoChanged",
self.beam_info_changed)
self.beam_info_changed(self.beam_info_dict)
self.beam_position_changed(self.beam_info_hwobj.get_beam_position())
else:
logging.getLogger("HWR").error("GraphicsManager: BeamInfo hwobj not defined")
self.camera_hwobj = self.getObjectByRole("camera")
if self.camera_hwobj is not None:
self.graphics_scene_size = self.camera_hwobj.get_image_dimensions()
self.set_graphics_scene_size(self.graphics_scene_size, False)
self.camera_hwobj.start_camera()
self.connect(self.camera_hwobj,
"imageReceived",
self.camera_image_received)
else:
logging.getLogger("HWR").error("GraphicsManager: Camera hwobj not defined")
try:
self.image_scale_list = eval(self.getProperty("imageScaleList"))
if len(self.image_scale_list) > 0:
self.image_scale = self.getProperty("defaultImageScale")
self.set_image_scale(self.image_scale, self.image_scale is not None)
except:
pass
if self.getProperty("store_graphics_config") == True:
atexit.register(self.save_graphics_config)
self.graphics_config_filename = self.getProperty("graphics_config_filename")
if self.graphics_config_filename is None:
self.graphics_config_filename = os.path.join(\
tempfile.gettempdir(), "mxcube", "graphics_config.dat")
self.load_graphics_config()
try:
self.auto_grid_size_mm = eval(self.getProperty("auto_grid_size_mm"))
except:
self.auto_grid_size_mm = (0.2, 0.2)
#self.init_auto_grid()
def save_graphics_config(self):
"""Saves graphical objects in the file
"""
logging.getLogger("HWR").debug("GraphicsManager: Saving graphics " + \
"in configuration file %s" % self.graphics_config_filename)
try:
if not os.path.exists(os.path.dirname(self.graphics_config_filename)):
os.makedirs(os.path.dirname(self.graphics_config_filename))
graphics_config_file = open(self.graphics_config_filename, "w")
graphics_config = []
for shape in self.get_shapes():
if isinstance(shape, GraphicsLib.GraphicsItemPoint):
cpos = shape.get_centred_position()
graphics_config.append({"type" : "point",
"index": shape.index,
"pos_x": shape.start_coord,
"pos_y": shape.end_coord,
"cpos": cpos.as_dict(),
"cpos_index": cpos.get_index()})
elif isinstance(shape, GraphicsLib.GraphicsItemLine):
(start_point_index, end_point_index) = shape.get_points_index()
graphics_config.append({"type" : "line",
"index": shape.index,
"start_point_index": start_point_index,
"end_point_index": end_point_index,})
graphics_config_file.write(repr(graphics_config))
graphics_config_file.close()
except:
logging.getLogger("HWR").error("GraphicsManager: Error saving graphics " + \
"in configuration file %s" % self.graphics_config_filename)
def load_graphics_config(self):
"""Loads graphics from file
"""
if os.path.exists(self.graphics_config_filename):
try:
logging.getLogger("HWR").debug("GraphicsManager: Loading graphics " + \
"from configuration file %s" % self.graphics_config_filename)
graphics_config_file = open(self.graphics_config_filename)
graphics_config = eval(graphics_config_file.read())
for graphics_item in graphics_config:
if graphics_item["type"] == "point":
point = self.create_centring_point(\
None, {"motors": graphics_item["cpos"]})
point.index = graphics_item["index"]
cpos = point.get_centred_position()
cpos.set_index(graphics_item["cpos_index"])
for graphics_item in graphics_config:
if graphics_item["type"] == "line":
start_point = self.get_point_by_index(\
graphics_item["start_point_index"])
end_point = self.get_point_by_index(\
graphics_item["end_point_index"])
self.create_line(start_point, end_point)
self.de_select_all()
graphics_config_file.close()
except:
logging.getLogger("HWR").error("GraphicsManager: Unable to load " + \
"graphics from configuration file %s" % self.graphics_config_filename)
def camera_image_received(self, pixmap_image):
"""Method called when a frame from camera arrives.
Slot to signal 'imageReceived'
:param pixmap_image: frame from camera
:type pixmap_image: QtGui.QPixmapImage
"""
if self.image_scale:
pixmap_image = pixmap_image.scaled(QtCore.QSize(\
pixmap_image.width() * self.image_scale,
pixmap_image.height() * self.image_scale))
self.graphics_camera_frame.setPixmap(pixmap_image)
def beam_position_changed(self, position):
"""Method called when beam position on the screen changed.
:param position: beam position on a screen
:type position: list of two int
"""
if position:
self.beam_position = position
for graphics_item in self.graphics_view.graphics_scene.items():
if isinstance(graphics_item, GraphicsLib.GraphicsItem):
graphics_item.set_beam_position(position)
def beam_info_changed(self, beam_info):
"""Method called when beam info changed
:param beam_info: information about the beam shape
:type beam_info: dict with beam info parameters
"""
if beam_info:
self.beam_info_dict = beam_info
for graphics_item in self.graphics_view.graphics_scene.items():
if isinstance(graphics_item, GraphicsLib.GraphicsItem):
graphics_item.set_beam_info(beam_info)
def diffractometer_state_changed(self, *args):
"""Method called when diffractometer state changed.
Updates point screen coordinates and grid coorner coordinates.
If diffractometer not ready then hides all shapes.
"""
if self.diffractometer_hwobj.is_ready():
for shape in self.get_shapes():
if isinstance(shape, GraphicsLib.GraphicsItemPoint):
cpos = shape.get_centred_position()
new_x, new_y = self.diffractometer_hwobj.\
motor_positions_to_screen(cpos.as_dict())
shape.set_start_position(new_x, new_y)
elif isinstance(shape, GraphicsLib.GraphicsItemGrid):
grid_cpos = shape.get_centred_position()
if grid_cpos is not None:
current_cpos = queue_model_objects.CentredPosition(\
self.diffractometer_hwobj.get_positions())
current_cpos.set_motor_pos_delta(0.1)
grid_cpos.set_motor_pos_delta(0.1)
if hasattr(grid_cpos, "zoom"):
current_cpos.zoom = grid_cpos.zoom
center_coord = self.diffractometer_hwobj.\
motor_positions_to_screen(grid_cpos.as_dict())
if center_coord:
shape.set_center_coord(center_coord)
corner_coord = []
for motor_pos in shape.get_motor_pos_corner():
corner_coord.append((self.diffractometer_hwobj.\
motor_positions_to_screen(motor_pos)))
shape.set_corner_coord(corner_coord)
if current_cpos == grid_cpos:
shape.set_projection_mode(False)
else:
shape.set_projection_mode(True)
self.show_all_items()
self.graphics_view.graphics_scene.update()
self.emit("diffractometerReady", True)
else:
self.hide_all_items()
self.emit("diffractometerReady", False)
def diffractometer_phase_changed(self, phase):
"""Phase changed event.
If PHASE_BEAM then displays a grid on the screen
"""
self.graphics_scale_item.set_display_grid(\
phase == self.diffractometer_hwobj.PHASE_BEAM)
self.emit("diffractometerPhaseChanged", phase)
def diffractometer_centring_started(self, centring_method, flexible):
"""Method called when centring started as a reply from diffractometer
:param centring_method: centring method
:type centring_method: str
:param flexible: flexible bit
:type flexible: bool
:emits: centringStarted
"""
self.current_centring_method = centring_method
self.emit("centringStarted")
def create_centring_point(self, centring_state, centring_status):
"""Creates a new centring position and adds it to graphics point.
:param centring_state:
:type centring_state: str
:param centring_status: dictionary with motor pos and etc
:type centring_status: dict
:emits: centringInProgress
"""
p_dict = {}
if 'motors' in centring_status and \
'extraMotors' in centring_status:
p_dict = dict(centring_status['motors'],
**centring_status['extraMotors'])
elif 'motors' in centring_status:
p_dict = dict(centring_status['motors'])
self.emit("centringInProgress", False)
if p_dict:
cpos = queue_model_objects.CentredPosition(p_dict)
screen_pos = self.diffractometer_hwobj.\
motor_positions_to_screen(cpos.as_dict())
point = GraphicsLib.GraphicsItemPoint(cpos, True,
screen_pos[0], screen_pos[1])
self.add_shape(point)
cpos.set_index(point.index)
return point
def diffractometer_centring_successful(self, method, centring_status):
"""Last stage in centring procedure
:param method: method name
:type method: str
:param centring_status: centring status
:type centring_status: dict
:emits: - centringSuccessful
- infoMsg
"""
self.set_centring_state(False)
self.emit("centringSuccessful", method, centring_status)
self.emit("infoMsg", "Click Save to store the centred point "+\
"or start a new centring")
def diffractometer_centring_failed(self, method, centring_status):
"""CleanUp method after centring failed
:param method: method name
:type method: str
:param centring_status: centring status
:type centring_status: dict
:emits: - centringFailed
- infoMsg
"""
self.set_centring_state(False)
self.emit("centringFailed", method, centring_status)
self.emit("infoMsg", "")
def diffractometer_pixels_per_mm_changed(self, pixels_per_mm):
"""Updates graphics scale when zoom changed
:param pixels_per_mm: two floats for scaling
:type pixels_per_mm: list with two floats
"""
if type(pixels_per_mm) in (list, tuple):
if pixels_per_mm != self.pixels_per_mm:
self.pixels_per_mm = pixels_per_mm
for item in self.graphics_view.graphics_scene.items():
if isinstance(item, GraphicsLib.GraphicsItem):
item.set_pixels_per_mm(self.pixels_per_mm)
self.graphics_view.graphics_scene.update()
def diffractometer_omega_reference_changed(self, omega_reference):
"""Method called when omega reference changed
:param omega_reference: omega reference values
:type omega_reference: list of two coordinated
"""
self.graphics_omega_reference_item.set_reference(omega_reference)
def diffractometer_phi_motor_moved(self, position):
"""Method when phi motor changed. Updates omega reference by
redrawing phi angle
:param position: phi rotation value
:type position: float
"""
self.graphics_omega_reference_item.set_phi_position(position)
def mouse_clicked(self, pos_x, pos_y, left_click=True):
"""Method when mouse clicked on GraphicsScene
:param pos_x: screen coordinate X
:type pos_x: int
:param pos_y: screen coordinate Y
:type pos_y: int
:param left_click: left button clicked
:type left_click: bool
:emits: - shapeSelected
- pointSelected
- infoMsg
"""
if self.in_centring_state:
self.graphics_centring_lines_item.set_start_position(pos_x, pos_y)
self.diffractometer_hwobj.image_clicked(pos_x, pos_y)
elif self.wait_grid_drawing_click:
self.in_grid_drawing_state = True
self.graphics_grid_draw_item.set_draw_mode(True)
self.graphics_grid_draw_item.set_draw_start_position(pos_x, pos_y)
self.graphics_grid_draw_item.show()
elif self.wait_measure_distance_click:
self.start_graphics_item(self.graphics_measure_distance_item)
self.in_measure_distance_state = True
self.wait_measure_distance_click = False
elif self.wait_measure_angle_click:
self.start_graphics_item(self.graphics_measure_angle_item)
self.in_measure_angle_state = True
self.wait_measure_angle_click = False
elif self.wait_measure_area_click:
self.start_graphics_item(self.graphics_measure_area_item)
self.in_measure_area_state = True
self.wait_measure_area_click = False
elif self.wait_beam_define_click:
self.start_graphics_item(self.graphics_beam_define_item)
self.in_beam_define_state = True
self.wait_beam_define_click = False
elif self.in_measure_distance_state:
self.graphics_measure_distance_item.store_coord(pos_x, pos_y)
elif self.in_measure_angle_state:
self.graphics_measure_angle_item.store_coord(pos_x, pos_y)
elif self.in_measure_area_state:
self.graphics_measure_area_item.store_coord()
elif self.in_move_beam_mark_state:
self.stop_move_beam_mark()
elif self.in_beam_define_state:
self.stop_beam_define()
#self.graphics_beam_define_item.store_coord(pos_x, pos_y)
else:
self.emit("pointSelected", None)
self.emit("infoMsg", "")
if left_click:
self.graphics_select_tool_item.set_start_position(pos_x, pos_y)
self.graphics_select_tool_item.set_end_position(pos_x, pos_y)
self.graphics_select_tool_item.show()
self.in_select_items_state = True
for graphics_item in self.graphics_view.scene().items():
graphics_item.setSelected(False)
if type(graphics_item) in [GraphicsLib.GraphicsItemPoint,
GraphicsLib.GraphicsItemLine,
GraphicsLib.GraphicsItemGrid]:
self.emit("shapeSelected", graphics_item, False)
#if isinstance(graphics_item, GraphicsLib.GraphicsItemPoint):
# self.emit("pointSelected", graphics_item)
def mouse_double_clicked(self, pos_x, pos_y):
"""If in one of the measuring states, then stops measuring.
Otherwise moves to screen coordinate
:param pos_x: screen coordinate X
:type pos_x: int
:param pos_y: screen coordinate Y
:type pos_y: int
"""
if self.in_measure_distance_state:
self.stop_measure_distance()
elif self.in_measure_angle_state:
self.stop_measure_angle()
elif self.in_measure_area_state:
self.stop_measure_area()
elif self.in_beam_define_state:
self.stop_beam_define()
else:
self.diffractometer_hwobj.move_to_beam(pos_x, pos_y)
def mouse_released(self, pos_x, pos_y):
"""Mouse release method. Used to finish grid drawing and item
selection with selection rectangle
:param pos_x: screen coordinate X
:type pos_x: int
:param pos_y: screen coordinate Y
:type pos_y: int
:emits: shapeCreated
"""
if self.in_grid_drawing_state:
QtGui.QApplication.restoreOverrideCursor()
self.update_grid_motor_positions(self.graphics_grid_draw_item)
self.graphics_grid_draw_item.set_draw_mode(False)
self.wait_grid_drawing_click = False
self.in_grid_drawing_state = False
self.de_select_all()
self.emit("shapeCreated", self.graphics_grid_draw_item, "Grid")
self.graphics_grid_draw_item.setSelected(True)
self.shape_dict[self.graphics_grid_draw_item.get_display_name()] = \
self.graphics_grid_draw_item
elif self.in_beam_define_state:
self.stop_beam_define()
elif self.in_select_items_state:
self.graphics_select_tool_item.hide()
self.in_select_items_state = False
"""
for point in self.get_points():
if point.isSelected():
self.emit("pointSelected", point)
"""
self.select_lines_and_grids()
def mouse_moved(self, pos_x, pos_y):
"""Executed when mouse moved. Used in all measure methods, centring
procedure and item selection procedure.
:param pos_x: screen coordinate X
:type pos_x: int
:param pos_y: screen coordinate Y
:type pos_y: int
:emits: mouseMoved
"""
self.emit("mouseMoved", pos_x, pos_y)
self.mouse_position[0] = pos_x
self.mouse_position[1] = pos_y
if self.in_centring_state:
self.graphics_centring_lines_item.set_start_position(pos_x, pos_y)
elif self.in_grid_drawing_state:
if self.graphics_grid_draw_item.is_draw_mode():
self.graphics_grid_draw_item.set_draw_end_position(pos_x, pos_y)
elif self.in_measure_distance_state:
self.graphics_measure_distance_item.set_coord(self.mouse_position)
elif self.in_measure_angle_state:
self.graphics_measure_angle_item.set_coord(self.mouse_position)
elif self.in_measure_area_state:
self.graphics_measure_area_item.set_coord(self.mouse_position)
elif self.in_move_beam_mark_state:
self.graphics_move_beam_mark_item.set_end_position(\
self.mouse_position[0], self.mouse_position[1])
elif self.in_beam_define_state:
self.graphics_beam_define_item.set_end_position(\
self.mouse_position[0], self.mouse_position[1])
elif self.in_select_items_state:
self.graphics_select_tool_item.set_end_position(pos_x, pos_y)
select_start_x = self.graphics_select_tool_item.start_coord[0]
select_start_y = self.graphics_select_tool_item.start_coord[1]
if abs(select_start_x - pos_x) > 5 and \
abs(select_start_y - pos_y) > 5:
painter_path = QtGui.QPainterPath()
painter_path.addRect(min(select_start_x, pos_x),
min(select_start_y, pos_y),
abs(select_start_x - pos_x),
abs(select_start_y - pos_y))
self.graphics_view.graphics_scene.setSelectionArea(painter_path)
"""
for point in self.get_points():
if point.isSelected():
self.emit("pointSelected", point)
self.select_lines_and_grids()
"""
def key_pressed(self, key_event):
"""Method when key on GraphicsView pressed.
- Deletes selected shapes if Delete pressed
- Cancels measurement action if Escape pressed
:param key_event: key event type
:type key_event: str
"""
if key_event == "Delete":
for item in self.graphics_view.graphics_scene.items():
if item.isSelected():
self.delete_shape(item)
elif key_event == "Escape":
self.stop_measure_distance()
self.stop_measure_angle()
self.stop_measure_area()
if self.in_beam_define_state:
self.stop_beam_define()
#elif key_event == "Up":
# self.diffractometer_hwobj.move_to_beam(self.beam_position[0],
# self.beam_position[1] - 50)
#elif key_event == "Down":
# self.diffractometer_hwobj.move_to_beam(self.beam_position[0],
# self.beam_position[1] + 50)
elif key_event == "Plus":
self.diffractometer_hwobj.zoom_in()
elif key_event == "Minus":
self.diffractometer_hwobj.zoom_out()
def mouse_wheel_scrolled(self, delta):
"""Method called when mouse wheel is scrolled.
Rotates omega axis up or down
"""
if delta > 0:
self.diffractometer_hwobj.move_omega_relative(20)
else:
self.diffractometer_hwobj.move_omega_relative(-20)
def item_clicked(self, item, state):
"""Item clicked event
:param item: clicked item
:type item: QGraphicsLib.GraphicsItem
:param state: selection state
:type state: bool
:emits: - pointsSelected
- infoMsg
"""
if type(item) in [GraphicsLib.GraphicsItemPoint,
GraphicsLib.GraphicsItemLine,
GraphicsLib.GraphicsItemGrid]:
self.emit("shapeSelected", item, state)
if isinstance(item, GraphicsLib.GraphicsItemPoint):
self.emit("pointSelected", item)
self.emit("infoMsg", item.get_full_name() + " selected")
def item_double_clicked(self, item):
"""Item double clicked method.
If centring point double clicked then moves motors to the
centring position
:param item: double clicked item
:type item: QGraphicsLib.GraphicsItem
"""
if isinstance(item, GraphicsLib.GraphicsItemPoint):
self.diffractometer_hwobj.move_to_centred_position(\
item.get_centred_position())
def get_graphics_view(self):
"""Rturns current GraphicsView
:returns: QGraphicsView
"""
return self.graphics_view
def get_graphics_camera_frame(self):
"""Rturns current CameraFrame
:returns: GraphicsCameraFrame
"""
return self.graphics_camera_frame
def set_graphics_scene_size(self, size, fixed):
"""Sets fixed size of scene
:param size: scene size
:type size: list
:param fixed: fixed bit
:type fixed: bool
"""
if not self.graphics_scene_size or fixed:
self.graphics_scene_size = size
self.graphics_scale_item.set_start_position(size[0], size[1])
self.graphics_view.scene().setSceneRect(0, 0, size[0], size[1])
#self.graphics_view.setFixedSize(size[0] + 2, size[1] + 2)
def set_centring_state(self, state):
"""Sets centrin state
:param state: centring state
:type state: bool
"""
self.in_centring_state = state
self.graphics_centring_lines_item.setVisible(state)
def get_shapes(self):
"""Returns currently handled shapes.
:returns: list with shapes
"""
shapes_list = []
for shape in self.graphics_view.graphics_scene.items():
if type(shape) in (GraphicsLib.GraphicsItemPoint,
GraphicsLib.GraphicsItemLine,
GraphicsLib.GraphicsItemGrid):
shapes_list.append(shape)
return shapes_list
def get_points(self):
"""Returns all points
:returns: list with GraphicsLib.GraphicsItemPoint
"""
current_points = []
for shape in self.get_shapes():
if isinstance(shape, GraphicsLib.GraphicsItemPoint):
current_points.append(shape)
return current_points
def get_point_by_index(self, index):
"""Returns centring point by its index
:param index: point index
:type inde: int
:returns: Qt4_GraphicsLib.GraphicsPoint
"""
for point in self.get_points():
if point.index == index:
return point
def add_shape(self, shape):
"""Adds the shape <shape> to the list of handled objects.
:param shape: Shape to add.
:type shape: Shape object.
:emits: shapeSelected
"""
self.de_select_all()
if isinstance(shape, GraphicsLib.GraphicsItemPoint):
self.point_count += 1
shape.index = self.point_count
self.emit("shapeCreated", shape, "Point")
self.emit("pointSelected", shape)
self.emit("infoMsg", "Centring %s created" % shape.get_full_name())
elif isinstance(shape, GraphicsLib.GraphicsItemLine):
self.line_count += 1
shape.index = self.line_count
self.emit("shapeCreated", shape, "Line")
self.emit("infoMsg", "%s created" % shape.get_full_name())
self.shape_dict[shape.get_display_name()] = shape
self.graphics_view.graphics_scene.addItem(shape)
shape.setSelected(True)
self.emit("shapeSelected", shape, True)
def delete_shape(self, shape):
"""Removes the shape <shape> from the list of handled shapes.
:param shape: The shape to remove
:type shape: GraphicsLib.GraphicsItem object
:emits: shapeDeleted
"""
if isinstance(shape, GraphicsLib.GraphicsItemPoint):
for s in self.get_shapes():
if isinstance(s, GraphicsLib.GraphicsItemLine):
if shape in s.get_graphics_points():
self.delete_shape(s)
break
shape_type = ""
if isinstance(shape, GraphicsLib.GraphicsItemPoint):
shape_type = "Point"
elif isinstance(shape, GraphicsLib.GraphicsItemLine):
shape_type = "Line"
elif isinstance(shape, GraphicsLib.GraphicsItemGrid):
shape_type = "Grid"
self.emit("shapeDeleted", shape, shape_type)
self.graphics_view.graphics_scene.removeItem(shape)
self.graphics_view.graphics_scene.update()
def get_shape_by_name(self, shape_name):
"""Returns shape by name
:param shape_name: name of the shape
:type shape_name: str
:returns: GraphicsLib.GraphicsItem
"""
return self.shape_dict.get(shape_name)
def clear_all(self):
"""Clear the shape history, remove all contents.
"""
self.point_count = 0
self.line_count = 0
self.grid_count = 0
for shape in self.get_shapes():
#if shape == self.auto_grid:
# shape.hide()
#else:
self.delete_shape(shape)
self.graphics_view.graphics_scene.update()
def de_select_all(self):
"""Deselects all shapes
"""
self.graphics_view.graphics_scene.clearSelection()
def select_shape(self, shape, state=True):
"""Selects shape
:param shape: shape to be selected or unselected
:type shape: Qtg4_GraphicsLib.GraphicsItem
:param state: selection state
:type state: bool
"""
shape.setSelected(state)
self.graphics_view.graphics_scene.update()
def select_all_points(self):
"""Selects all points
"""
self.de_select_all()
for shape in self.get_points():
shape.setSelected(True)
self.graphics_view.graphics_scene.update()
def select_shape_with_cpos(self, cpos):
"""Selects point with centred position
:param cpos: centring point
:type cpos: queue_model_objects.CentredPosition
"""
self.de_select_all()
for shape in self.get_points():
if shape.get_centred_position() == cpos:
shape.setSelected(True)
#self.graphics_view.graphics_scene.update()
def get_selected_shapes(self):
"""Returns selected shapes
:returns: list with GraphicsLib.GraphicsItem
"""
selected_shapes = []
for item in self.graphics_view.graphics_scene.items():
if (type(item) in (GraphicsLib.GraphicsItemPoint,
GraphicsLib.GraphicsItemLine,
GraphicsLib.GraphicsItemGrid) and
item.isSelected()):
selected_shapes.append(item)
return selected_shapes
def get_selected_points(self):
"""Returns selected points
:returns: list with GraphicsLib.GraphicsItemPoint
"""
selected_points = []
selected_shapes = self.get_selected_shapes()
for shape in selected_shapes:
if isinstance(shape, GraphicsLib.GraphicsItemPoint):
selected_points.append(shape)
return sorted(selected_points, key = lambda x : x.index, reverse = False)
def hide_all_items(self):
"""Hides all items
"""
for shape in self.get_shapes():
if shape != self.auto_grid:
shape.hide()
def show_all_items(self):
"""Shows all items
"""
for shape in self.get_shapes():
if shape != self.auto_grid:
shape.show()
def get_scene_snapshot(self, shape=None, bw=None, return_as_array=None):
"""Takes a snapshot of the scene
:param shape: shape that needs to be selected
:type shape: GraphicsLib.GraphicsItem
:returns: QImage
"""
if shape:
self.hide_all_items()
#self.de_select_all()
shape.show()
#shape.setSelected(True)
#self.select_shape_with_cpos(shape.get_centred_position())
self.graphics_omega_reference_item.hide()
image = QtGui.QImage(self.graphics_view.graphics_scene.sceneRect().\
size().toSize(), QtGui.QImage.Format_ARGB32)
image.fill(QtCore.Qt.transparent)
image_painter = QtGui.QPainter(image)
self.graphics_view.render(image_painter)
image_painter.end()
self.show_all_items()
self.graphics_omega_reference_item.show()
if return_as_array:
pass
else:
return image
def save_scene_snapshot(self, filename):
"""Method to save snapshot
:param file_name: file name
:type file_name: str
"""
logging.getLogger("user_level_log").debug("Saving scene snapshot: %s" % filename)
snapshot = self.get_scene_snapshot()
snapshot.save(filename)
def get_raw_snapshot(self, bw=False, return_as_array=False):