프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

hytos / DTI_PID / DTI_PID / Commands / DefaultCommand.py @ 38657e1b

이력 | 보기 | 이력해설 | 다운로드 (12 KB)

1
import sys
2
import os.path
3
import AbstractCommand
4
try:
5
    from PyQt5.QtCore import *
6
    from PyQt5.QtGui import *
7
    from PyQt5.QtWidgets import *
8
except ImportError:
9
    try:
10
        from PyQt4.QtCore import Qt, QRectF, pyqtSignal, QT_VERSION_STR, QEvent
11
        from PyQt4.QtGui import QGraphicsView, QGraphicsScene, QImge, QPixmap, QPainterPath, QFileDialog, QCursor, QMouseEvent
12
    except ImportError:
13
        raise ImportError("ImageViewerQt: Requires PyQt5 or PyQt4.")
14

    
15
'''
16
    @brief      QtImageViewer Default Command
17
    @author     Jeongwoo
18
    @date       18.04.10
19
    @history    2018.05.02  Jeongwoo    Change mouse cursor
20
'''
21
class DefaultCommand(AbstractCommand.AbstractCommand):
22
    onSuccess = pyqtSignal(float, float, float, float)
23

    
24
    def __init__(self, imageViewer):
25
        super(DefaultCommand, self).__init__(imageViewer)
26
        self.name = 'Default'
27
        self.imageViewer.setCursor(QCursor(Qt.ArrowCursor))
28
        
29
        self._vertices = []
30
        self.startX = 0
31
        self.startY = 0
32
        self.isClicked = False
33

    
34
        self.symbol = None
35
        self.isCopy = False
36
        self.isSpecBreak = False
37
        self.specBreak_startPoint = []
38
        self.tempAngle = 0
39
    
40
    '''
41
        @brief      Scroll / Pan / Zoom with Wheel Button
42
        @author     Jeongwoo
43
        @date       18.04.10
44
        @history    kyouho  2018.07.31  add copy symbol logic
45
                    humkyung 2018.08.11 cancel paste when user press escape key
46
    '''
47
    def execute(self, param):
48
        from SymbolSvgItem import SymbolSvgItem
49
        from EngineeringLineNoTextItem import QEngineeringLineNoTextItem
50
        from EngineeringTextItem import QEngineeringTextItem
51

    
52
        event = param[1]
53
        scenePos = param[2]
54
        
55
        self.isTreated = False
56

    
57
        try:
58
            if not self.isCopy:
59
                if 'mousePressEvent' == param[0] and (event.button() == Qt.MiddleButton or
60
                                                      event.button() == Qt.RightButton):
61
                    self.imageViewer.setDragMode(QGraphicsView.ScrollHandDrag)
62
                    QGraphicsView.mousePressEvent(self.imageViewer, QMouseEvent(QEvent.MouseButtonPress, event.pos(), Qt.LeftButton, event.buttons(), Qt.NoModifier))
63
                elif 'mouseReleaseEvent' == param[0] and (event.button() == Qt.MiddleButton or
64
                                                          event.button() == Qt.RightButton):
65
                    try:
66
                        self.imageViewer.setDragMode(QGraphicsView.NoDrag)
67
                    finally:
68
                        QGraphicsView.mouseReleaseEvent(self.imageViewer, QMouseEvent(QEvent.MouseButtonRelease, event.pos(), Qt.LeftButton, event.buttons(), Qt.NoModifier))
69
                        pass
70
                elif 'mousePressEvent' == param[0] and event.button() == Qt.LeftButton:
71
                    self.imageViewer.setDragMode(QGraphicsView.RubberBandDrag)
72
                    self.startX = scenePos.x()
73
                    self.startY = scenePos.y()
74
                    self._vertices.clear()
75
                    self._vertices.append(param[2])
76
                    self.isClicked = True
77
                elif 'mouseReleaseEvent' == param[0] and event.button() == Qt.LeftButton:
78
                    try:
79
                        QGraphicsView.mouseReleaseEvent(self.imageViewer, event)
80
                        self._vertices.append(param[2])
81
                    finally:
82
                        self.imageViewer.setDragMode(QGraphicsView.NoDrag)
83
                        if len(self._vertices) == 2:
84
                            x = min(self._vertices[0].x(), self._vertices[1].x())
85
                            y = min(self._vertices[0].y(), self._vertices[1].y())
86
                            width = abs(self._vertices[0].x() - self._vertices[1].x())
87
                            height = abs(self._vertices[0].y() - self._vertices[1].y())
88
                            self.onSuccess.emit(x, y, width, height)
89
                        self.isClicked = False
90
                elif self.isClicked and 'mouseMoveEvent' == param[0]:
91
                    endX = scenePos.x()
92
                    endY = scenePos.y()
93

    
94
                    if self.startX > endX and self.startY > endY:
95
                        self.imageViewer.setRubberBandSelectionMode(Qt.ContainsItemShape)
96
                    else:
97
                        self.imageViewer.setRubberBandSelectionMode(Qt.IntersectsItemShape)
98
                elif 'keyPressEvent' == param[0] and (event.modifiers() == Qt.ControlModifier and event.key() == Qt.Key_C):
99
                    selectedItems = self.imageViewer.scene().selectedItems()
100
                    if len(selectedItems) == 1 and issubclass(type(selectedItems[0]), SymbolSvgItem):
101
                        from xml.etree.ElementTree import tostring
102
                        xmlStr = str(tostring(selectedItems[0].toXml()))
103
                        xmlStr = xmlStr[xmlStr.find('<SYMBOL>'):xmlStr.find('</SYMBOL>') + 9]
104
                        QApplication.clipboard().setText(xmlStr)
105
                    elif len(selectedItems) > 0:
106
                        import io, csv
107
                        
108
                        text_items = [item for item in selectedItems if issubclass(type(item), QEngineeringTextItem)]
109
                        text_items = sorted(text_items, key=lambda param:param.loc[0])
110
                        table = [[text.text() for text in text_items]]
111
                        stream = io.StringIO()
112
                        csv.writer(stream, delimiter='\t').writerows(table)
113
                        QApplication.clipboard().setText(stream.getvalue())
114

    
115
                elif 'keyPressEvent' == param[0] and (event.modifiers() == Qt.ControlModifier and event.key() == Qt.Key_V):
116
                    xmlStr = QApplication.clipboard().text()
117
                    if xmlStr.find('<SYMBOL>') > -1 and xmlStr.find('</SYMBOL>') > -1:
118
                        self.copySymbol(QApplication.clipboard().text())
119
                self.isTreated = False
120
            elif self.isCopy and self.isSpecBreak:
121
                if 'mouseReleaseEvent' == param[0] and event.button() == Qt.LeftButton:
122
                    from EngineeringConnectorItem import QEngineeringConnectorItem
123

    
124
                    offsetX = 0
125
                    offsetY = 0
126
                    transform = QTransform()
127
                    currentPt = self.symbol.getCurrentPoint()
128
                    if 0 == self.symbol.angle or 3.14 == self.symbol.angle:
129
                        transform.translate(self.specBreak_startPoint[0], scenePos.y())
130
                        offsetY = self.specBreak_startPoint[1] - scenePos.y()
131
                        
132
                    else:
133
                        transform.translate(scenePos.x(), self.specBreak_startPoint[1])
134
                        offsetX = self.specBreak_startPoint[0] - scenePos.x()
135

    
136
                    transform.rotateRadians(-self.symbol.angle)
137
                    transform.translate(-currentPt[0], -currentPt[1])
138
                    self.symbol.setTransform(transform)
139

    
140
                    self.symbol.specBreak_offsetX = offsetX
141
                    self.symbol.specBreak_offsetY = offsetY
142

    
143
                    self.symbol.connectors[0].connectPoint = (self.symbol.connectors[0].connectPoint[0] + offsetX, self.symbol.connectors[0].connectPoint[1] + offsetY)
144
                    self.symbol.connectors[0].setPos((self.symbol.connectors[0].connectPoint[0], self.symbol.connectors[0].connectPoint[1]))
145

    
146
                    self.symbol = None
147
                    self.isCopy = False
148
                    self.isSpecBreak = False
149

    
150
                    QApplication.instance().setOverrideCursor(QCursor(Qt.ArrowCursor))
151
                elif 'mouseMoveEvent' == param[0]:
152
                    from EngineeringConnectorItem import QEngineeringConnectorItem
153

    
154
                    transform = QTransform()
155
                    currentPt = self.symbol.getCurrentPoint()
156
                    if 0 == self.symbol.angle or 3.14 == self.symbol.angle:
157
                        transform.translate(self.specBreak_startPoint[0], scenePos.y())
158
                    else:
159
                        transform.translate(scenePos.x(), self.specBreak_startPoint[1])
160
                    transform.rotateRadians(-self.symbol.angle)
161
                    transform.translate(-currentPt[0], -currentPt[1])
162
                    self.symbol.setTransform(transform)
163
                elif 'keyPressEvent' == param[0] and event.key() == Qt.Key_Escape:
164
                    self.imageViewer.scene().removeItem(self.symbol)
165
                    self.symbol = None
166
                    self.isCopy = False
167
                    self.isSpecBreak = False
168

    
169
            else:
170
                if 'mouseReleaseEvent' == param[0] and event.button() == Qt.LeftButton:
171
                    from EngineeringConnectorItem import QEngineeringConnectorItem
172

    
173
                    item = self.imageViewer.scene().itemAt(scenePos, QTransform())
174
                    if item is not None and type(item) is QEngineeringConnectorItem:
175
                        scenePos = QPointF(item.center()[0], item.center()[1])
176

    
177
                    transform = QTransform()
178
                    currentPt = self.symbol.getCurrentPoint()
179
                    transform.translate(scenePos.x() - currentPt[0], scenePos.y() - currentPt[1])
180
                    self.symbol.setTransform(transform)
181

    
182
                    self.imageViewer.scene().removeItem(self.symbol)
183
                    self.imageViewer.matchSymbolToLine(self.symbol, scenePos)
184
                    self.symbol = None
185
                    self.isCopy = False
186

    
187
                    QApplication.instance().setOverrideCursor(QCursor(Qt.ArrowCursor))
188
                elif 'mouseMoveEvent' == param[0]:
189
                    from EngineeringConnectorItem import QEngineeringConnectorItem
190

    
191
                    item = self.imageViewer.scene().itemAt(scenePos, QTransform())
192
                    if item is not None and type(item) is QEngineeringConnectorItem:
193
                        scenePos = QPointF(item.center()[0], item.center()[1])
194

    
195
                    transform = QTransform()
196
                    currentPt = self.symbol.getCurrentPoint()
197
                    transform.translate(scenePos.x() - currentPt[0], scenePos.y() - currentPt[1])
198
                    self.symbol.setTransform(transform)
199
                elif 'keyPressEvent' == param[0] and event.key() == Qt.Key_Escape:
200
                    self.imageViewer.scene().removeItem(self.symbol)
201
                    self.symbol = None
202
                    self.isCopy = False
203
        except Exception as ex:
204
            from App import App 
205
            from AppDocData import MessageType
206

    
207
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
208
            App.mainWnd().addMessage.emit(MessageType.Error, message)
209

    
210
    def undo(self):
211
        pass
212

    
213
    def redo(self):
214
        pass
215
    
216
    '''
217
        @brief      xml to ElementTree and ElementTree to Symbol
218
        @author     kyouho
219
        @date       18.07.31
220
    '''
221
    def copySymbol(self, xmlStr):
222
        from xml.etree.ElementTree import Element, SubElement, dump, ElementTree, parse, fromstring
223
        sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\Shapes')
224
        from SymbolSvgItem import SymbolSvgItem
225
        import uuid
226

    
227
        try:   
228
            # string to ElementTree
229
            et = fromstring(xmlStr)
230
            item = SymbolSvgItem.fromXml(et)
231
            self.symbol = item
232
            for connector in self.symbol.connectors:
233
                connector.connectedItem = None
234
            # uid 새로 할당
235
            self.symbol.uid = uuid.uuid4()
236
            self.imageViewer.scene().addItem(self.symbol)
237
            self.imageViewer.scene().clearFocus()
238
            self.imageViewer.scene().setFocusItem(self.symbol)
239
            self.symbol.setSelected(True)
240
            self.isCopy = True
241

    
242
            QApplication.instance().setOverrideCursor(QCursor(Qt.DragCopyCursor))
243
        except Exception as ex:
244
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
245
        
클립보드 이미지 추가 (최대 크기: 500 MB)