프로젝트

일반

사용자정보

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

hytos / HYTOS / HYTOS / SymbolTreeWidget.py @ d9478fca

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

1
try:
2
    from PyQt5.QtCore import *
3
    from PyQt5.QtGui import *
4
    from PyQt5.QtWidgets import *
5
except ImportError:
6
    try:
7
        from PyQt4.QtCore import *
8
        from PyQt4.QtGui import *
9
    except ImportError:
10
        raise ImportError("ImageViewerQt: Requires PyQt5 or PyQt4.")
11
from AppDocData import *
12
import os
13
import sys
14
import SymbolBase
15
import symbol
16
import SymbolEditorDialog
17
import QSymbolDisplayDialog
18

    
19
class QSymbolTreeWidget(QTreeWidget):
20
    #Add signal
21
    singleClicked = pyqtSignal(SymbolBase.SymbolBase)
22
    TREE_DATA_ROLE = Qt.UserRole
23

    
24
    def __init__(self):
25
        QTreeWidget.__init__(self)
26
        self.setDragEnabled(True)   # enable drag
27
        self.initDirTreeWidget()
28
        self.isDoubleClicked = False
29
        self.itemDoubleClicked.connect(self.itemDoubleClickEvent)
30
        self.setContextMenuPolicy(Qt.CustomContextMenu)
31
        self.customContextMenuRequested.connect(self.openContextMenu)
32
        self.currentItemChanged.connect(self.onCurrentItemChanged)
33
            
34
    '''
35
        @brief      Show Context Menu
36
        @author     Jeongwoo
37
        @date       18.04.??
38
        @history    Jeongwoo 2018.04.23 Symbol object Null Check when show context menu
39
                    humkyung 2018.08.14 add menu for symbol type
40
    '''
41
    def openContextMenu(self, position):
42
        indexes = self.selectedIndexes()
43
        itemPosition = self.mapTo(self, position)
44
        item = self.itemAt(itemPosition)
45
        data = item.data(0, self.TREE_DATA_ROLE)
46
        if data is not None and type(data) is symbol.SymbolBase:
47
            sym = self.getSymbolByItemName(item, 0)
48
            text = item.text(0)
49
            if len(indexes) > 0:
50
                level = 0
51
                index = indexes[0]
52
                while index.parent().isValid():
53
                    index = index.parent()
54
                    level += 1
55
            if sym is not None:
56
                menu = QMenu()
57
                editSymbolAction = QAction(self.tr("Edit Symbol"))
58
                editSymbolAction.triggered.connect(lambda: self.editSymbolActionClickEvent(item, 0))
59
                menu.addAction(editSymbolAction)
60
                displaySymbolAction = QAction(self.tr("Display Symbol"))
61
                displaySymbolAction.triggered.connect(lambda: self.displaySymbolActionClickEvent(sym.getType(), text))
62
                menu.addAction(displaySymbolAction)
63
                deleteSymbolAction = QAction(self.tr("Delete Symbol"))
64
                deleteSymbolAction.triggered.connect(lambda: self.deleteSymbolActionClickEvent(sym.getType(), text))
65
                menu.addAction(deleteSymbolAction)
66
                menu.exec_(self.viewport().mapToGlobal(position))
67
        else:
68
            menu = QMenu()
69
            editAttrAction = QAction(self.tr("Edit Attribute"))
70
            editAttrAction.triggered.connect(lambda: self.onEditAttrClicked(item, 0))
71
            menu.addAction(editAttrAction)
72
            menu.exec_(self.viewport().mapToGlobal(position))
73

    
74
    def editSymbolActionClickEvent(self, item, columNo):
75
        self.showSymbolEditorDialog(item, columNo)
76

    
77
    '''
78
        @brief      popup attribute editor dialog
79
        @author     humkyung
80
        @date       2018.08.13
81
    '''
82
    def onEditAttrClicked(self, item, columnNo):
83
        from SymbolAttrEditorDialog import QSymbolAttrEditorDialog
84

    
85
        try:
86
                data = item.data(0, self.TREE_DATA_ROLE)
87

    
88
                dlg = QSymbolAttrEditorDialog(self, data)
89
                dlg.exec_()
90
        except Exception as ex:
91
            from App import App
92

    
93
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
94
            App.mainWnd().addMessage.emit(MessageType.Error, message)
95

    
96
    def displaySymbolActionClickEvent(self, itemType, itemName):
97
        project = AppDocData.instance().getCurrentProject()
98
        image = QImage(os.path.join(project.getImageFilePath(), itemType, itemName, "PNG")) #itemName includes ".png"
99
        dialog = QSymbolDisplayDialog.QSymbolDisplayDialog(image)
100
        dialog.showDialog()
101

    
102
    def deleteSymbolActionClickEvent(self, itemType, itemName):
103
        msg = QMessageBox()
104
        msg.setIcon(QMessageBox.Critical)
105
        msg.setText(self.tr('Are you sure you want to delete selected symbol?\nData can not be restored!'))
106
        msg.setWindowTitle(self.tr('Delete symbol'))
107
        msg.setStandardButtons(QMessageBox.Ok|QMessageBox.Cancel)
108
        result = msg.exec_()
109
        self.handleDeleteSymbolAction(result, itemType, itemName)
110

    
111
    '''
112
        @history    2018.05.03  Jeongwoo    Modify file path with ".png" and ".svg"
113
                                            Use project object when making svgPath
114
    '''
115
    def handleDeleteSymbolAction(self, result, itemType, itemName):
116
        if result == QMessageBox.Ok:
117
            project = AppDocData.instance().getCurrentProject()
118
            imagePath = os.path.join(project.getImageFilePath(), itemType, itemName  + '.png') # itemName DOESN'T includes ".png"
119
            if os.path.exists(imagePath):
120
                os.remove(imagePath)
121

    
122
            svgPath = os.path.join(project.getSvgFilePath(), itemType, itemName + '.svg')
123
            if os.path.exists(svgPath):
124
                os.remove(svgPath)
125

    
126
            AppDocData.instance().deleteSymbol(itemName)
127
            self.initDirTreeWidget()
128
        else:
129
            pass
130

    
131
    '''
132
        @history    2018.05.02  Jeongwoo    Change return value of QSymbolEditorDialog (Single variable → Tuple)
133
    '''
134
    def initDirTreeWidget(self):
135
        project = AppDocData.instance().getCurrentProject()
136
        if project is not None:
137
            self.clear()
138
            projectPath = project.getPath().replace("\\", "/")
139
            self.makeChildDir()
140
            self.loadSymbolInfo()
141
            self.expandAll()
142

    
143
    '''
144
        @brief      Load Symbol Info and add TreeItem with DB
145
        @author     Jeongwoo
146
        @date       18.04.20
147
        @history    Jeongwoo 2018.05.03 Get Svg File Path by SymbolBase.getSvgFileFullPath()
148
                    humkyung 2018.07.30 sort child items
149
    '''
150
    def loadSymbolInfo(self):
151
        
152
        try:
153
            symbolCategoryList = AppDocData.instance().getSymbolCategoryList()
154
            for symbolCategory in symbolCategoryList:
155
                parent = QTreeWidgetItem(self, [symbolCategory])
156
                parent.setData(0, self.TREE_DATA_ROLE, symbolCategory)
157

    
158

    
159

    
160
                symbolTypeList = AppDocData.instance().getSymbolTypeListByCategory(symbolCategory)
161
                for symbolType in symbolTypeList:
162
                    category = QTreeWidgetItem(parent, [symbolType[1]])
163
                    category.setData(0, self.TREE_DATA_ROLE, symbolType)
164
                    symbolList = AppDocData.instance().getSymbolListByType('type', symbolType[1])
165
                    for symbol in symbolList:
166
                        symbolItem = QTreeWidgetItem(category, [symbol.getName()])
167
                        symbolItem.setData(0, self.TREE_DATA_ROLE, symbol)
168
                        svgPath = symbol.getSvgFileFullPath()
169
                        icon = QIcon(svgPath)
170
                        symbolItem.setIcon(0, icon)
171
                        symbolItem.svgFilePath = svgPath # save svg file path
172

    
173
                    parent.sortChildren(0, Qt.AscendingOrder)
174
        except Exception as ex:
175
            from App import App
176

    
177
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
178
            App.mainWnd().addMessage.emit(MessageType.Error, message)
179

    
180
    '''
181
        @brief      Make Directory
182
        @author     Jeongwoo
183
        @date       18.04.??
184
        @history    18.04.12    Jeongwoo    Add output, temp Directory
185
    '''
186
    def makeChildDir(self):
187
        project = AppDocData.instance().getCurrentProject()
188
        dbDir = project.getDbFilePath()
189
        if not os.path.exists(dbDir):
190
            os.makedirs(dbDir)
191
        imgDir = project.getImageFilePath()
192
        if not os.path.exists(imgDir):
193
            os.makedirs(imgDir)
194
        svgDir = project.getSvgFilePath()
195
        if not os.path.exists(svgDir):
196
            os.makedirs(svgDir)
197
        outputDir = project.getOutputPath()
198
        if not os.path.exists(outputDir):
199
            os.makedirs(outputDir)
200
        tempDir = project.getTempPath()
201
        if not os.path.exists(tempDir):
202
            os.makedirs(tempDir)
203

    
204
    '''
205
        @history    2019.07.11  yeonjin    심벌 편집 시 png 파일이 아닌 svg 파일을 불러 오도록 수정
206
                                            
207
    '''
208
    def showSymbolEditorDialog(self, item, columnNo):
209
        try:
210
            sym = self.getSymbolByItemName(item, columnNo)
211
            if sym is not None:
212
                #path = sym.getPath()
213
                #image = QImage(path, "PNG")
214
                path = sym.getSvgFileFullPath()
215
                image = QImage(path, "SVG")
216
                symbolEditorDialog = SymbolEditorDialog.QSymbolEditorDialog(self, image, AppDocData.instance().getCurrentProject(), sym)
217
                (isAccepted, isImmediateInsert, offsetX, offsetY, newSym) = symbolEditorDialog.showDialog()
218
                self.initDirTreeWidget()
219
            else:
220
                QMessageBox.about(self, self.tr('Error'), self.tr('Error occurs during loading symbol data.'))
221
        except Exception as ex:
222
            from App import App
223

    
224
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
225
            App.mainWnd().addMessage.emit(MessageType.Error, message)
226

    
227
    def itemDoubleClickEvent(self, item, columnNo):
228
        self.isDoubleClicked = True
229
        sym = self.getSymbolByItemName(item, columnNo)
230
        itemName = item.text(columnNo)
231
        if sym is not None:
232
            self.showSymbolEditorDialog(item, columnNo)
233
        self.isDoubleClicked = False
234

    
235
    '''
236
        @brief      Get Symbol data by symbol name
237
        @author     Jeongwoo
238
        @date       18.04.20
239
    '''
240
    def getSymbolByItemName(self, item, columnNo):
241
        itemName = item.text(columnNo)
242

    
243
        name = itemName
244
        sym = AppDocData.instance().getSymbolByQuery("name", name)
245
        return sym
246

    
247
    '''
248
        @breif      show symbol's property when selection changed
249
        @author     humkyung
250
        @date       2018.07.30
251
    '''
252
    def onCurrentItemChanged(self, current, previous):
253
        item = self.currentItem()
254
        if item is not None:
255
            data = item.data(0, self.TREE_DATA_ROLE)
256
            if data is not None and type(data) is symbol.SymbolBase:
257
                self.singleClicked.emit(data)
258

    
259
    '''
260
        @brief  start drag
261
        @author humkyung
262
        @date   2018.04.17
263
        @history    18.04.20    Jeongwoo    Change Path in QPixmap
264
                    18.06.21    Jeongwoo    Casting string to float and int
265
    '''
266
    def startDrag(self, dropAction):
267
        try:
268
            items = self.selectedItems()
269
            if items and hasattr(items[0], 'svgFilePath'):
270
                symData = items[0].data(0, self.TREE_DATA_ROLE)
271
                pixmap = QPixmap(items[0].svgFilePath)
272

    
273
                mime = QMimeData()
274
                mime.setText(symData.getName())
275

    
276
                drag = QDrag(self)
277
                drag.setMimeData(mime) 
278
                originalPoint = symData.getOriginalPoint()
279
                drag.setHotSpot(QPoint(int(float(originalPoint.split(",")[0])), int(float(originalPoint.split(",")[1]))))
280
                drag.setPixmap(pixmap)        
281
                drag.exec(Qt.CopyAction)
282
        except Exception as ex:
283
            from App import App
284

    
285
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
286
            App.mainWnd().addMessage.emit(MessageType.Error, message)
클립보드 이미지 추가 (최대 크기: 500 MB)