프로젝트

일반

사용자정보

개정판 aff7c828

IDaff7c82877c8b2164bdf2a7e3467bf1de4a69b48
상위 e9b4417a
하위 887ce06c, 63ef9dd0

백흠경이(가) 약 5년 전에 추가함

issue #1061: 심볼 형상을 데이타베이스에 저장하는 기능 추가

Change-Id: I1cd8a90af3adfc158db39900153e50d8d3a54a75

차이점 보기:

HYTOS/HYTOS/AppDocData.py
348 348
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
349 349
        return os.path.join(path, 'svg')
350 350

  
351
    def update_symbol_shape(self, drawing, symbol, svg_file):
352
        """update symbol shape"""
353

  
354
        conn = sqlite3.connect(drawing)
355
        conn.execute('PRAGMA foreign_keys = ON')
356
        with conn:
357
            try:
358
                conn.row_factory = sqlite3.Row
359
                # Get a cursor object
360
                cursor = conn.cursor()
361

  
362
                sql = f"update Symbols set Shape = ? where UID='{symbol}'"
363

  
364
                blob_data = None
365
                with open(svg_file, 'rb') as file:
366
                    blob_data = file.read()
367

  
368
                # Convert data into tuple format
369
                params = (blob_data,)
370
                cursor.execute(sql, params)
371
                conn.commit()
372

  
373
            # Catch the exception
374
            except Exception as ex:
375
                from App import App
376
                # Roll back any change if something goes wrong
377
                conn.rollback()
378

  
379
                message = 'error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename,
380
                                                               sys.exc_info()[-1].tb_lineno)
381
                App.mainWnd().addMessage.emit(MessageType.Error, message)
382

  
383
    def read_symbol_shape(self, drawing, symbol):
384
        """read symbol shape"""
385

  
386
        res = None
387

  
388
        conn = sqlite3.connect(drawing)
389
        conn.execute('PRAGMA foreign_keys = ON')
390
        with conn:
391
            try:
392
                conn.row_factory = sqlite3.Row
393
                # Get a cursor object
394
                cursor = conn.cursor()
395

  
396
                sql = f"select Shape from Symbols where UID='{symbol}'"
397
                cursor.execute(sql)
398
                records = cursor.fetchall()
399
                for record in records:
400
                    res = record[0]
401
                    break
402

  
403
            # Catch the exception
404
            except Exception as ex:
405
                from App import App
406
                # Roll back any change if something goes wrong
407
                conn.rollback()
408

  
409
                message = 'error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename,
410
                                                               sys.exc_info()[-1].tb_lineno)
411
                App.mainWnd().addMessage.emit(MessageType.Error, message)
412

  
413
        return res
414

  
351 415
    def getRoughness(self, phase_type):
352 416
        res = []
353 417

  
HYTOS/HYTOS/QtImageViewer.py
554 554
        svgScale = 1
555 555
        svgOrigin = symbol.originalPoint
556 556
        svgFilePath = os.path.join(app_doc_data.symbol_file_path, symbol.getCategory(), symbol.getType(), svgFileName + '.svg')
557
        svg = SymbolSvgItem.createItem(symbol.getType(), svgFilePath)
557
        svg = SymbolSvgItem.createItem(symbol.getType(), svgFilePath, None, owner=None, flip=0, symbol=uid)
558 558
        connPts = None
559 559
        strConnPts = symbol.connectionPoint
560 560
        if strConnPts is not None and strConnPts != '':
HYTOS/HYTOS/Shapes/SymbolSvgItem.py
32 32
                    18.05.30    Jeongwoo    Add self variables (parentSymbol, childSymbol)
33 33
    '''
34 34

  
35
    def __init__(self, path, uid=None, flip=0):
35
    def __init__(self, path, uid=None, flip=0, symbol=None):
36 36
        import uuid
37 37
        from SymbolAttr import SymbolProp
38 38

  
......
70 70
        self.transfer = Transfer()
71 71

  
72 72
        try:
73
            f = QFile(path)
74
            f.open(QIODevice.ReadOnly)
75
            array = f.readAll()
73
            app_doc_data = AppDocData.instance()
74
            shape = None
75
            if symbol:
76
                shape = app_doc_data.read_symbol_shape(app_doc_data.activeDrawing.path, symbol)
77

  
78
            if not shape:
79
                f = QFile(path)
80
                if f.open(QIODevice.ReadOnly):
81
                    shape = f.readAll()
82
                    f.close()
83

  
76 84
            self._document = QDomDocument()
77
            self._document.setContent(array)
85
            self._document.setContent(shape)
78 86
            self._renderer = QSvgRenderer(self._document.toByteArray())
79 87
            self.setSharedRenderer(self._renderer)
80 88

  
......
86 94
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
87 95
                                                          sys.exc_info()[-1].tb_lineno)
88 96
            App.mainWnd().addMessage.emit(MessageType.Error, message)
89
        finally:
90
            f.close()
91 97

  
92 98
        self.setZValue(SymbolSvgItem.ZVALUE)
93 99
        self._desc_label = QEngineeringEqpDescTextItem('eqp name<br>pressure drop<br>elevation', self)
......
1021 1027
            svgFilePath = os.path.join(app_doc_data.symbol_file_path, category, _type, name + '.svg')
1022 1028

  
1023 1029
            if os.path.isfile(svgFilePath):
1024
                item = SymbolSvgItem.createItem(_type, svgFilePath, uid)
1030
                item = SymbolSvgItem.createItem(_type, svgFilePath, uid, None, 0, dbUid)
1025 1031
                item.setVisible(False)
1026 1032
                item.buildItem(name, _type, float(angle), float(scale), pt, origin, connPts, dbUid, pointsUids)
1027 1033
                item.tag_no = tag_no
......
1043 1049
    '''
1044 1050

  
1045 1051
    @staticmethod
1046
    def createItem(type, path, uid=None, owner=None, flip=0):
1052
    def createItem(type, path, uid=None, owner=None, flip=0, symbol=None):
1047 1053
        import uuid
1048 1054

  
1049
        item = SymbolSvgItem(path, uid, flip=flip)
1055
        item = SymbolSvgItem(path, uid, flip=flip, symbol=symbol)
1050 1056

  
1051 1057
        if owner is not None:
1052
            item.owner = uuid.UUID(owner, version=4)
1058
            item.owner = uuid.UUID(owner)
1053 1059

  
1054 1060
        return item
1055 1061

  
HYTOS/HYTOS/SymbolEditorDialog.py
36 36
            self.setWindowFlag(Qt.WindowMinMaxButtonsHint)
37 37
            self.ui = SymbolEditor_UI.Ui_Dialog()
38 38
            self.ui.setupUi(self)
39
            self.ui.pushButtonSvgFilePath.clicked.connect(self.select_svg_file)
39 40
            
40 41
            self.ui.tableWidgetConnList.setColumnCount(3)
41 42
            self.ui.tableWidgetConnList.horizontalHeader().setStretchLastSection(True)
......
61 62
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
62 63
            print(message)
63 64

  
65
    def select_svg_file(self):
66
        """select svg file"""
64 67

  
68
        options = QFileDialog.Options()
69
        options |= QFileDialog.DontUseNativeDialog
70
        name, _ = QFileDialog.getOpenFileName(self, self.tr('Open svg file'), os.getcwd(), 'Svf File(*.svg)',
71
                                              options=options)
72
        if name:
73
            self.ui.lineEditSvgFilePath.setText(name)
74

  
75
            image = QImage(name)
76
            width, height = image.width(), image.height()
77

  
78
            image = image.scaled(int(width), int(height))
79
            self.ui.imageView.setImage(image)
80
            self.ui.imageView.showGuideline(None, True)
65 81

  
66 82
    ''' 
67 83
        @brief      hilight pressed connector item
......
133 149
        self.ui.typeComboBox.currentIndexChanged.connect(self.onTypeChanged)
134 150
        self.ui.nameComboBox.currentIndexChanged.connect(self.onNameChanged)
135 151

  
136

  
137
        
138

  
139 152
        self.initDBPath()
140 153
        self.initSymbolCategoryComboBoxItems() 
141 154

  
142 155
    def initDBPath(self):
143
        self.ui.lineEdit_DBPath.setText( AppDocData.instance().getTemplateDbPath())
156
        app_doc_data = AppDocData.instance()
144 157

  
158
        if app_doc_data.activeDrawing:
159
            self.ui.lineEdit_DBPath.setText(app_doc_data.activeDrawing.path)
160
        else:
161
            self.ui.lineEdit_DBPath.setText(app_doc_data.getTemplateDbPath())
145 162

  
146 163
    def onCategoryChanged(self, index):
147 164
        category = self.ui.categoryComboBox.itemText(index)
......
164 181
        self.initContents()
165 182

  
166 183
    def setImage(self):
167
        from PIL import Image
168

  
169 184
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
170 185
        category = self.ui.categoryComboBox.currentText()
171 186
        type = self.ui.typeComboBox.currentText()
172 187
        name = self.ui.nameComboBox.currentText()
173 188

  
174
        filePath = os.path.join(path, 'svg', category, type, '{}.svg'.format(name))
189
        app_doc_data = AppDocData.instance()
190
        uid = self.selectedSymbol[0][0]
191
        shape = app_doc_data.read_symbol_shape(app_doc_data.activeDrawing.path, uid)
175 192

  
176
        if os.path.isfile(filePath) and os.path.exists(filePath):
177
            
178
            image = QImage(filePath)
193
        image = None
194
        if shape:
195
            image = QImage.fromData(shape)
196
        else:
197
            filePath = os.path.join(path, 'svg', category, type, '{}.svg'.format(name))
198

  
199
            if os.path.isfile(filePath) and os.path.exists(filePath):
200
                image = QImage(filePath)
201

  
202
        if image:
179 203
            self.imgW = image.width()
180 204
            self.imgH = image.height()
181 205

  
......
439 463
                                            Change self.dbHelper to AppDocData
440 464
                    2019.07.11 yenjin       
441 465
    '''
442
    def accept(self):      
443
        if len(self.selectedSymbol) > 0:            
444
            uid = self.selectedSymbol[0][0]
466
    def accept(self):
467
        try:
468
            if len(self.selectedSymbol) > 0:
469
                uid = self.selectedSymbol[0][0]
445 470

  
446
            originalPoint = self.ui.originalPointLineEdit.text()
447
            connectionPoint = self.makeConnectionPointListString()
471
                originalPoint = self.ui.originalPointLineEdit.text()
472
                connectionPoint = self.makeConnectionPointListString()
448 473

  
449
            isSuccess = AppDocData.instance().updateTemplateSymbol(uid, originalPoint, connectionPoint)
450
            if isSuccess:
451
                QMessageBox.information(self, self.tr("Notice"), self.tr("Save completed successfully."))
452
            
474
                app_doc_data = AppDocData.instance()
475
                if self.ui.lineEditSvgFilePath.text():
476
                    app_doc_data.update_symbol_shape(app_doc_data.activeDrawing.path, uid, self.ui.lineEditSvgFilePath.text())
477

  
478
                isSuccess = app_doc_data.updateTemplateSymbol(uid, originalPoint, connectionPoint)
479
                if isSuccess:
480
                    QMessageBox.information(self, self.tr("Notice"), self.tr("Save completed successfully."))
481
        except Exception as ex:
482
            message = 'error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename,
483
                                                           sys.exc_info()[-1].tb_lineno)
484
            QMessageBox.information(self, message)
453 485

  
454
        #QDialog.accept(self)
455
            
456 486
    '''
457 487
        @brief  Called When Close Button Clicked
458 488
    '''
HYTOS/HYTOS/SymbolEditor_UI.py
13 13
class Ui_Dialog(object):
14 14
    def setupUi(self, Dialog):
15 15
        Dialog.setObjectName("Dialog")
16
        Dialog.resize(1002, 563)
16
        Dialog.resize(977, 563)
17 17
        Dialog.setMinimumSize(QtCore.QSize(0, 0))
18 18
        Dialog.setMaximumSize(QtCore.QSize(16777215, 16777215))
19 19
        font = QtGui.QFont()
......
24 24
        Dialog.setWindowIcon(icon)
25 25
        self.gridLayout_3 = QtWidgets.QGridLayout(Dialog)
26 26
        self.gridLayout_3.setObjectName("gridLayout_3")
27
        self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
28
        self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Close|QtWidgets.QDialogButtonBox.Save)
29
        self.buttonBox.setObjectName("buttonBox")
30
        self.gridLayout_3.addWidget(self.buttonBox, 2, 0, 1, 1)
27 31
        self.splitter = QtWidgets.QSplitter(Dialog)
28 32
        self.splitter.setMinimumSize(QtCore.QSize(0, 0))
29 33
        self.splitter.setOrientation(QtCore.Qt.Horizontal)
......
39 43
        self.imageViewContainer.setObjectName("imageViewContainer")
40 44
        self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.imageViewContainer)
41 45
        self.verticalLayout_3.setObjectName("verticalLayout_3")
46
        self.horizontalLayout = QtWidgets.QHBoxLayout()
47
        self.horizontalLayout.setObjectName("horizontalLayout")
48
        self.label_3 = QtWidgets.QLabel(self.imageViewContainer)
49
        self.label_3.setObjectName("label_3")
50
        self.horizontalLayout.addWidget(self.label_3)
51
        self.lineEditSvgFilePath = QtWidgets.QLineEdit(self.imageViewContainer)
52
        self.lineEditSvgFilePath.setDragEnabled(True)
53
        self.lineEditSvgFilePath.setReadOnly(True)
54
        self.lineEditSvgFilePath.setObjectName("lineEditSvgFilePath")
55
        self.horizontalLayout.addWidget(self.lineEditSvgFilePath)
56
        self.pushButtonSvgFilePath = QtWidgets.QPushButton(self.imageViewContainer)
57
        self.pushButtonSvgFilePath.setMinimumSize(QtCore.QSize(24, 0))
58
        self.pushButtonSvgFilePath.setMaximumSize(QtCore.QSize(24, 16777215))
59
        self.pushButtonSvgFilePath.setObjectName("pushButtonSvgFilePath")
60
        self.horizontalLayout.addWidget(self.pushButtonSvgFilePath)
61
        self.verticalLayout_3.addLayout(self.horizontalLayout)
42 62
        self.imageViewerContainerLayout = QtWidgets.QVBoxLayout()
43 63
        self.imageViewerContainerLayout.setObjectName("imageViewerContainerLayout")
44 64
        self.verticalLayout_3.addLayout(self.imageViewerContainerLayout)
......
166 186
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
167 187
        self.verticalLayout.addWidget(self.scrollArea)
168 188
        self.gridLayout_2.addLayout(self.verticalLayout, 0, 0, 1, 1)
169
        self.gridLayout_3.addWidget(self.splitter, 0, 0, 1, 1)
170
        self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
171
        self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Close|QtWidgets.QDialogButtonBox.Save)
172
        self.buttonBox.setObjectName("buttonBox")
173
        self.gridLayout_3.addWidget(self.buttonBox, 1, 0, 1, 1)
189
        self.gridLayout_3.addWidget(self.splitter, 1, 0, 1, 1)
174 190

  
175 191
        self.retranslateUi(Dialog)
176 192
        self.buttonBox.accepted.connect(Dialog.accept)
......
180 196
    def retranslateUi(self, Dialog):
181 197
        _translate = QtCore.QCoreApplication.translate
182 198
        Dialog.setWindowTitle(_translate("Dialog", "Symbol Editor"))
199
        self.label_3.setText(_translate("Dialog", "Svg File Path : "))
200
        self.pushButtonSvgFilePath.setText(_translate("Dialog", "..."))
183 201
        self.addConnectionPointButton.setText(_translate("Dialog", "Add"))
184 202
        self.pushButtonDelConnPt.setText(_translate("Dialog", "Del"))
185 203
        self.nameLabel.setText(_translate("Dialog", "Name :"))
HYTOS/HYTOS/SymbolTreeWidget.py
17 17
import QSymbolDisplayDialog
18 18

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

  
24 24
    def __init__(self):
25 25
        QTreeWidget.__init__(self)
26 26
        self.setDragEnabled(True)   # enable drag
27
        #self.initSymbolTreeWidget()
28

  
27
        self.setIconSize(QSize(32, 32))
29 28

  
30 29
    '''
31 30
        @history    2019.07.11  yeonjin    심벌 편집 시 png 파일이 아닌 svg 파일을 불러 오도록 수정
......
93 92
                    for symbol in symbolList:
94 93
                        symbolItem = QTreeWidgetItem(category, [symbol.sName, symbol.uid])
95 94
                        symbolItem.setData(0, self.TREE_DATA_ROLE, symbol)
96
                        svgPath = symbol.getSvgFileFullPath()
97
                        icon = QIcon(svgPath)
98
                        symbolItem.setIcon(0, icon)
99
                        symbolItem.svgFilePath = svgPath # save svg file path
100

  
101
                        # show symbol tree item tooltip with image(size*3)
102
                        renderer = QSvgRenderer(svgPath)
103
                        image = QImage(renderer.defaultSize()*3, QImage.Format_ARGB32)
104
                        painter = QPainter(image)
105
                        with painter:
106
                            renderer.render(painter)
107
                            buffer = QBuffer()
108
                            buffer.open(QIODevice.WriteOnly)
109
                            image.save(buffer, "PNG", quality=100)
110
                            pixmap = bytes(buffer.data().toBase64()).decode()
111
                            html = '<img src="data:image/png;base64,{}>"'.format(pixmap)
112
                            symbolItem.setToolTip(0, html)
95

  
96
                        shape = app_doc_data.read_symbol_shape(app_doc_data.activeDrawing.path, symbol.uid)
97
                        if shape:
98
                            pixmap = QPixmap(QSize(32, 32))
99
                            pixmap.loadFromData(shape)
100
                            icon = QIcon(pixmap)
101
                            symbolItem.setIcon(0, icon)
102
                            symbolItem.svgFilePath = None  # reset svg file path
103
                        else:
104
                            svgPath = symbol.getSvgFileFullPath()
105
                            icon = QIcon(svgPath)
106
                            symbolItem.setIcon(0, icon)
107
                            symbolItem.svgFilePath = svgPath # save svg file path
113 108

  
114 109
                    parent.sortChildren(0, Qt.AscendingOrder)
115 110
        except Exception as ex:
......
130 125
            items = self.selectedItems()
131 126
            if items and hasattr(items[0], 'svgFilePath'):
132 127
                symData = items[0].data(0, self.TREE_DATA_ROLE)
133
                pixmap = QPixmap(items[0].svgFilePath)
128
                if items[0].svgFilePath:
129
                    pixmap = QPixmap(items[0].svgFilePath)
130
                else:
131
                    app_doc_data = AppDocData.instance()
132
                    shape = app_doc_data.read_symbol_shape(app_doc_data.activeDrawing.path, symData.uid)
133
                    if shape:
134
                        pixmap = QPixmap()
135
                        pixmap.loadFromData(shape)
134 136

  
135 137
                mime = QMimeData()
136
                #mime.setText(symData.getName())
137 138
                mime.setText(symData.getUid())
138 139

  
139 140
                drag = QDrag(self)
......
145 146
        except Exception as ex:
146 147
            from App import App
147 148

  
148
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
149
            message = 'error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
149 150
            App.mainWnd().addMessage.emit(MessageType.Error, message)
HYTOS/HYTOS/UI/SymbolEditor.ui
61 61
          <widget class="QWidget" name="imageViewContainer" native="true">
62 62
           <layout class="QVBoxLayout" name="verticalLayout_3">
63 63
            <item>
64
             <layout class="QHBoxLayout" name="horizontalLayout">
65
              <item>
66
               <widget class="QLabel" name="label_3">
67
                <property name="text">
68
                 <string>Svg File Path : </string>
69
                </property>
70
               </widget>
71
              </item>
72
              <item>
73
               <widget class="QLineEdit" name="lineEditSvgFilePath">
74
                <property name="dragEnabled">
75
                 <bool>true</bool>
76
                </property>
77
                <property name="readOnly">
78
                 <bool>true</bool>
79
                </property>
80
               </widget>
81
              </item>
82
              <item>
83
               <widget class="QPushButton" name="pushButtonSvgFilePath">
84
                <property name="minimumSize">
85
                 <size>
86
                  <width>24</width>
87
                  <height>0</height>
88
                 </size>
89
                </property>
90
                <property name="maximumSize">
91
                 <size>
92
                  <width>24</width>
93
                  <height>16777215</height>
94
                 </size>
95
                </property>
96
                <property name="text">
97
                 <string>...</string>
98
                </property>
99
               </widget>
100
              </item>
101
             </layout>
102
            </item>
103
            <item>
64 104
             <layout class="QVBoxLayout" name="imageViewerContainerLayout"/>
65 105
            </item>
66 106
           </layout>

내보내기 Unified diff

클립보드 이미지 추가 (최대 크기: 500 MB)