프로젝트

일반

사용자정보

개정판 2796938f

ID2796938f1d4c49ce00f1a96fdf5ff640a8e62dc7
상위 2ea965f2
하위 43619a9b, 99fec6e2

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

issue #622: 저장 - 아이템들을 데이타베이스에 저장한다

Change-Id: Icc9ef95e9347ea18c63e25158a0d3163d2f1a262

차이점 보기:

DTI_PID/DTI_PID/AppDocData.py
2197 2197
                # Get a cursor object
2198 2198
                cursor = conn.cursor()
2199 2199

  
2200
                sql = "select a.*,b.Name,b.SymbolType_UID,b.[Type],b.OriginalPoint,b.ConnectionPoint,b.BaseSymbol,b.Flip from Components a \
2200
                sql = "select a.*,b.Name,b.SymbolType_UID,b.[Type],b.OriginalPoint,b.ConnectionPoint,b.BaseSymbol,b.AdditionalSymbol,b.HasInstrumentLabel,b.Flip from Components a \
2201 2201
                join Symbol b on a.Symbol_UID=b.UID \
2202
                where a.Drawings_UID=(select UID from Drawings where Name='{}')".format(drawing)
2202
                where a.Drawings_UID='{}'".format(drawing)
2203 2203
                cursor.execute(sql)
2204 2204
                return cursor.fetchall()
2205 2205
            # Catch the exception
......
2223 2223
                # Get a cursor object
2224 2224
                cursor = conn.cursor()
2225 2225

  
2226
                sql = "select * from Points Components_UID='{}' order by [Index]".format(component)
2226
                sql = "select * from Points where Components_UID='{}' order by [Index]".format(component)
2227 2227
                cursor.execute(sql)
2228 2228
                return cursor.fetchall()
2229 2229
            # Catch the exception
......
2247 2247
                # Get a cursor object
2248 2248
                cursor = conn.cursor()
2249 2249

  
2250
                sql = "select * from Associations Components_UID='{}'".format(component)
2250
                sql = "select * from Associations where Components_UID='{}'".format(component)
2251 2251
                cursor.execute(sql)
2252 2252
                return cursor.fetchall()
2253 2253
            # Catch the exception
......
3077 3077
                sql = "delete from Components where Drawings_UID='{}'".format(drawing_uid)
3078 3078
                cursor.execute(sql)
3079 3079

  
3080
                conn.commit()
3081
            # Catch the exception
3082
        except Exception as ex:
3083
            from App import App
3084
            # Roll back any change if something goes wrong
3085
            conn.rollback()
3086

  
3087
            print(sql)
3088
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3089
            App.mainWnd().addMessage.emit(MessageType.Error, message)
3090
            return
3091

  
3092
        try:
3093
            from EngineeringUnknownItem import QEngineeringUnknownItem
3094

  
3095
            # Creates or opens a file called mydb with a SQLite3 DB
3096
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3097
            conn = sqlite3.connect(dbPath, isolation_level=None)
3098
            with conn:
3099
                cursor = conn.cursor()
3100 3080
                for item in items:
3101 3081
                    sql = item.toSql()
3102 3082
                    if type(sql) is list:
......
3216 3196
        @author     humkyung
3217 3197
        @date       2018.11.03
3218 3198
        """
3219

  
3220 3199
        res = []
3221
        try:
3222
            xmlList = [xml.replace('.xml', '') for xml in os.listdir(AppDocData.instance().getCurrentProject().getTempPath()) if xml.find('.xml') is not -1]
3223 3200

  
3201
        try:
3224 3202
            # Creates or opens a file called mydb with a SQLite3 DB
3225 3203
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3226 3204
            conn = sqlite3.connect(dbPath)
3227
            # Get a cursor object
3228
            cursor = conn.cursor()
3229

  
3230
            sql = 'select UID,[NAME],[DATETIME] from Drawings'
3231
            cursor.execute(sql)
3232
            rows = cursor.fetchall()
3233
            for row in rows:
3234
                for xml in xmlList:
3235
                    if row[1].replace('.png', '') == xml:
3236
                        res.append([row[0], row[1], row[2]])
3237
                        break
3205
            with conn:
3206
                conn.row_factory = sqlite3.Row
3207
                # Get a cursor object
3208
                cursor = conn.cursor()
3238 3209

  
3210
                sql = 'select UID,[NAME],[DATETIME] from Drawings'
3211
                cursor.execute(sql)
3212
                for row in cursor.fetchall():
3213
                    res.append([row['UID'], row['NAME'], row['DATETIME']])
3239 3214
        # Catch the exception
3240 3215
        except Exception as ex:
3241 3216
            # Roll back any change if something goes wrong
......
3244 3219

  
3245 3220
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3246 3221
            App.mainWnd().addMessage.emit(MessageType.Error, message)
3247
        finally:
3248
            # Close the db connection
3249
            conn.close()
3250 3222

  
3251 3223
        return res
3252 3224

  
DTI_PID/DTI_PID/Commands/SaveWorkCommand.py
42 42

  
43 43
            db_items = [item for item in items if issubclass(type(item), QEngineeringAbstractItem) and type(item) is not QGraphicsBoundingBoxItem and type(item) is not QEngineeringErrorItem]
44 44
            db_items.extend([line for line in appDocData.tracerLineNos if type(line) is QEngineeringTrimLineNoTextItem])
45
            print('count={}'.format(len(db_items)))
46
            #appDocData.saveToDatabase(db_items)
45
            appDocData.saveToDatabase(db_items)
47 46

  
48 47
            self.resultStr = SaveWorkCommand.save_to_xml()
49 48

  
DTI_PID/DTI_PID/MainWindow.py
1135 1135
                        child.setCheckState(0, Qt.Checked)
1136 1136
                        break
1137 1137

  
1138
                ## Load data on xml
1139
                path = os.path.join(appDocData.getCurrentProject().getTempPath(), appDocData.imgName + '.xml')
1140
                count = 0
1141
                if os.path.isfile(path):
1142
                    for child in parse(path).getroot().getchildren():
1143
                        count = count + len(child.getchildren())
1144
                if count > 0:
1145
                    try:
1146
                        self.progress = QProgressDialog(self.tr("Please wait for a while"), self.tr("Cancel"), 0, 100, self) if not hasattr(self, 'progress') else self.progress
1147
                        self.progress.setWindowModality(Qt.WindowModal)
1148
                        self.progress.setAutoReset(True)
1149
                        self.progress.setAutoClose(True)
1150
                        self.progress.setMinimum(0)
1151
                        self.progress.resize(600,100)
1152
                        self.progress.setWindowTitle(self.tr("Reading file..."))
1153
                        self.progress.show()
1154

  
1138
                try:
1139
                    self.progress = QProgressDialog(self.tr("Please wait for a while"), self.tr("Cancel"), 0, 100, self) if not hasattr(self, 'progress') else self.progress
1140
                    self.progress.setWindowModality(Qt.WindowModal)
1141
                    self.progress.setAutoReset(True)
1142
                    self.progress.setAutoClose(True)
1143
                    self.progress.setMinimum(0)
1144
                    self.progress.resize(600,100)
1145
                    self.progress.setWindowTitle(self.tr("Reading file..."))
1146
                    self.progress.show()
1147
                    ## Load data on xml
1148
                    path = os.path.join(appDocData.getCurrentProject().getTempPath(), appDocData.imgName + '.xml')
1149
                    if os.path.isfile(path):
1155 1150
                        self.loadRecognitionResultFromXml(path)
1156
                    finally:
1157
                        self.progress.setValue(self.progress.maximum())
1158
                        self.progress.hide()
1151
                    else:
1152
                        self.load_drawing(appDocData.activeDrawing)
1153
                finally:
1154
                    self.progress.setValue(self.progress.maximum())
1155
                    self.progress.hide()
1156

  
1159 1157
                self.changeViewCheckedState(True)
1160 1158
        except Exception as ex:
1161 1159
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
......
2351 2349
        #cv2.destroyAllWindows()
2352 2350
        return (True, mergedOtherLine)
2353 2351

  
2354
    def loadRecognitionResultFromXml(self, xmlPath):
2355
        app_doc_data = AppDocData.instance()
2352
    def load_drawing(self, drawing):
2353
        """ load drawing """
2356 2354
        from xml.etree.ElementTree import Element, SubElement, dump, ElementTree, parse
2357 2355
        from EngineeringRunItem import QEngineeringRunItem
2358 2356
        from QEngineeringTrimLineNoTextItem import QEngineeringTrimLineNoTextItem
2359 2357

  
2358
        app_doc_data = AppDocData.instance()
2360 2359
        try:
2361 2360
            symbols = []
2362 2361
            lines = []
2363 2362

  
2364
            components = app_doc_data.get_components(xmlPath)
2365
            xml = parse(xmlPath)
2366
            root = xml.getroot()
2367
            
2363
            components = app_doc_data.get_components(drawing.UID)
2368 2364
            maxValue = len(components)
2369 2365
            self.progress.setMaximum(maxValue)
2370 2366

  
2371 2367
            """ parsing all symbols """
2372 2368
            for symbol in [component for component in components if component['SymbolType_UID'] != '-1']:
2373
                item = SymbolSvgItem.fromXml(symbol)
2369
                item = SymbolSvgItem.from_database(symbol)
2374 2370
                if item is not None:
2375 2371
                    item.transfer.onRemoved.connect(self.itemRemoved)
2376 2372
                    symbols.append(item)
......
2392 2388
            QApplication.processEvents()
2393 2389

  
2394 2390
            # parse texts
2395
            for text in [component for component in components if component['Name'] == 'Text' and component['SymbolType_UID'] != '-1']:
2391
            for text in [component for component in components if component['Name'] == 'Text' and component['SymbolType_UID'] == '-1']:
2396 2392
                item = QEngineeringTextItem.from_database(text)
2397 2393
                if item is not None:
2398 2394
                    item.uid = text['UID']
......
2406 2402
            QApplication.processEvents()
2407 2403

  
2408 2404
            # note
2409
            for note in [component for component in components if component['Name'] == 'Note' and component['SymbolType_UID'] != '-1']:
2405
            for note in [component for component in components if component['Name'] == 'Note' and component['SymbolType_UID'] == '-1']:
2410 2406
                item = QEngineeringTextItem.from_database(note)
2411 2407
                if item is not None:
2412 2408
                    item.uid = note['UID']
......
2419 2415
                
2420 2416
            QApplication.processEvents()
2421 2417

  
2422
            for line in [component for component in components if component['Name'] == 'Line' and component['SymbolType_UID'] != '-1']:
2418
            for line in [component for component in components if component['Name'] == 'Line' and component['SymbolType_UID'] == '-1']:
2423 2419
                item = QEngineeringLineItem.from_database(line)
2424 2420
                if item:
2425 2421
                    item.transfer.onRemoved.connect(self.itemRemoved)
......
2430 2426
                
2431 2427
            QApplication.processEvents()
2432 2428

  
2433
            for unknown in [component for component in components if component['Name'] == 'Unknown' and component['SymbolType_UID'] != '-1']:
2429
            for unknown in [component for component in components if component['Name'] == 'Unknown' and component['SymbolType_UID'] == '-1']:
2434 2430
                item = QEngineeringUnknownItem.from_database(unknown)
2435 2431
                item.transfer.onRemoved.connect(self.itemRemoved)
2436 2432
                if item is not None:
......
2447 2443
            #    self.addSvgItemToScene(item)
2448 2444
            #    self.itemTreeWidget.addTreeItem(self.itemTreeWidget.root, item)
2449 2445

  
2450
            for component in [component for component in components if component['Name'] == 'Line NO' and component['SymbolType_UID'] != '-1']:
2446
            for component in [component for component in components if component['Name'] == 'Line NO' and component['SymbolType_UID'] == '-1']:
2451 2447
                line_no = QEngineeringLineNoTextItem.from_database(component)
2452 2448
                if line_no is None: continue
2453 2449

  
......
2477 2473
                self.progress.setValue(self.progress.value() + 1)
2478 2474
            QApplication.processEvents()
2479 2475

  
2480
            for component in [component for component in components if component['Name'] == 'Trim Line NO' and component['SymbolType_UID'] != '-1']:
2476
            for component in [component for component in components if component['Name'] == 'Trim Line NO' and component['SymbolType_UID'] == '-1']:
2481 2477
                line_no = QEngineeringTrimLineNoTextItem()
2482 2478
                line_no.uid = uuid.UUID(component['UID'], version=4)
2483 2479

  
......
2498 2494
                for run_item in line_run.items:
2499 2495
                    if issubclass(type(run_item), SymbolSvgItem): self.itemTreeWidget.addTreeItem(line_no_tree_item, run_item)
2500 2496

  
2501
                docData.tracerLineNos.append(line_no)
2497
                app_doc_data.tracerLineNos.append(line_no)
2502 2498

  
2503 2499
                self.progress.setValue(self.progress.value() + 1)
2504 2500

  
2505
            for component in [component for component in components if component['Name'] == 'VendorPackage' and component['SymbolType_UID'] != '-1']:
2501
            for component in [component for component in components if component['Name'] == 'VendorPackage' and component['SymbolType_UID'] == '-1']:
2506 2502
                item = QEngineeringVendorItem.from_database(component)
2507 2503
                item.transfer.onRemoved.connect(self.itemRemoved)
2508 2504
                self.graphicsView.scene.addItem(item)
DTI_PID/DTI_PID/Shapes/EngineeringConnectorItem.py
444 444
        import uuid
445 445

  
446 446
        try:
447
            self.uid = uuid.UUID(record['UID'], version=4)
448 447
            self._connected_at = QEngineeringAbstractItem.CONNECTED_AT_PT if record['Connected_At'] == '0' else QEngineeringAbstractItem.CONNECTED_AT_BODY
449 448

  
450
            connectedItemStr = record('Connected')
449
            connectedItemStr = record['Connected']
451 450
            connectPointStr = [record['X'], record['Y']]
452 451
            sceneConnectPointStr = [record['X'], record['Y']]
453 452

  
454
            self._connectedItem = uuid.UUID(connectedItemStr, version=4) if connectedItemStr != 'None' else None
453
            self._connectedItem = uuid.UUID(connectedItemStr, version=4) if connectedItemStr and connectedItemStr != 'None' else None
455 454
            self.connectPoint = (float(connectPointStr[0]), float(connectPointStr[1]))
456 455
            self.sceneConnectPoint = (float(sceneConnectPointStr[0]), float(sceneConnectPointStr[1]))
457 456

  
DTI_PID/DTI_PID/Shapes/EngineeringEquipmentItem.py
250 250
        sql = 'insert or replace into EQUIPMENT_DATA_LIST({}) values({})'.format(','.join(cols), ','.join(values))
251 251
        res.append((sql, (tuple(param),)))
252 252

  
253
        cols = ['UID', 'Drawings_UID', 'Symbol_UID', 'X', 'Y', 'Width', 'Height', 'Rotation', 'Area', 'Owner', 'Connected', 'SuppliedBy', \
253
        cols = ['UID', 'Drawings_UID', 'Symbol_UID', 'X', 'Y', 'Width', 'Height', 'Rotation', 'Area', 'Owner', 'Connected', '[Supplied By]', \
254 254
                'SpecialItemTypes_UID', 'OriginIndex']
255 255
        values = ['?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?']
256 256
        param = [(str(self.uid), str(appDocData.activeDrawing.UID), str(self.dbUid), self.loc[0], self.loc[1], self.size[0], self.size[1], str(self.angle), 
DTI_PID/DTI_PID/Shapes/EngineeringInstrumentItem.py
298 298
        sql = 'insert or replace into INSTRUMENT_DATA_LIST({}) values({})'.format(','.join(cols), ','.join(values))
299 299
        res.append((sql, tuple(param)))
300 300

  
301
        cols = ['UID', 'Drawings_UID', 'Symbol_UID', 'X', 'Y', 'Width', 'Height', 'Rotation', 'Area', 'Owner', 'Connected', 'SuppliedBy', \
301
        cols = ['UID', 'Drawings_UID', 'Symbol_UID', 'X', 'Y', 'Width', 'Height', 'Rotation', 'Area', 'Owner', 'Connected', '[Supplied By]', \
302 302
                'SpecialItemTypes_UID']
303 303
        values = ['?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?']
304 304
        param = [(str(self.uid), str(appDocData.activeDrawing.UID), str(self.dbUid), self.loc[0], self.loc[1], self.size[0], self.size[1], str(self.angle), 
......
324 324
            values = ['?', '?', '?', '?']
325 325
            params = []
326 326
            for assoc in self.associations():
327
                param = [str(uuid.uuid4()), QEngineeringAbstractItem.assoc_type(assoc), str(self.uid), str(assoc.uid)]
328
                sql = 'insert or replace into Associations({}) values({})'.format(','.join(cols), ','.join(values))
329
                res.append((sql, tuple(param)))
327
                params.append((str(uuid.uuid4()), QEngineeringAbstractItem.assoc_type(assoc), str(self.uid), str(assoc.uid)))
328
            sql = 'insert or replace into Associations({}) values({})'.format(','.join(cols), ','.join(values))
329
            res.append((sql, tuple(params)))
330 330

  
331 331
        # save connectors to database
332 332
        if self.connectors:
DTI_PID/DTI_PID/Shapes/EngineeringLineItem.py
1136 1136
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1137 1137

  
1138 1138
    @staticmethod 
1139
    def from_database(record):
1139
    def from_database(component):
1140 1140
        """ get line from database """
1141 1141
        import uuid
1142 1142
        from AppDocData import AppDocData
......
1144 1144
        
1145 1145
        item = None
1146 1146
        try:
1147
            uidNode = record['UID']
1148
            uid = uidNode.text if uidNode is not None else uuid.uuid4() # generate UUID
1149
            owner = uuid.UUID(record['Owner'], version=4) if record['Owner'] and record['Owner'] != 'None' else None
1147
            uidNode = component['UID']
1148
            uid = uidNode if uidNode is not None else uuid.uuid4() # generate UUID
1149
            owner = uuid.UUID(component['Owner'], version=4) if component['Owner'] and component['Owner'] != 'None' else None
1150 1150

  
1151 1151
            app_doc_data = AppDocData.instance()
1152 1152
            connectors = app_doc_data.get_component_connectors(uid)
1153
            if 2 != len(connectors): return item
1153 1154
            startPoint = [float(connectors[0]['X']), float(connectors[0]['Y'])]
1154 1155
            endPoint = [float(connectors[1]['X']), float(connectors[1]['Y'])]
1155 1156

  
1156 1157
            item = QEngineeringLineItem(vertices=[startPoint, endPoint], uid=uid)
1157 1158
            item.setVisible(False)
1158
            item.lineType = record['LineType'] if record['LineType'] else 'Secondary'
1159
            attrs = app_doc_data.get_component_attributes(uid)
1160
            matches = [attr for attr in attrs if attr['Attribute'] == 'LineType']
1161
            item.lineType = matches[0]['Value'] if matches else 'Secondary'
1159 1162
            ## assign area
1160
            if record['Area']:
1163
            if component['Area']:
1161 1164
                for area in app_doc_data.getAreaList():
1162 1165
                    if area.contains(startPoint) and area.contains(endPoint):
1163 1166
                        item.area = area.name
1164 1167
                        break
1165 1168
            else:
1166
                item.area = record['Area']
1169
                item.area = component['Area']
1167 1170
            ## up to here
1168 1171

  
1169
            thicknessNode = record('Thickness')
1170
            item.thickness = int(thicknessNode.text) if thicknessNode is not None and thicknessNode.text != 'None' else None
1172
            matches = [attr for attr in attrs if attr['Attribute'] == 'Thickness']
1173
            item.thickness = int(matches[0]['Value']) if matches and matches[0]['Value'] != 'None' else None
1171 1174

  
1172
            flowMarkNode = record['FlowMark']
1173
            item.flowMark = int(flowMarkNode.text) if flowMarkNode is not None and flowMarkNode.text != 'None' else None
1175
            matches = [attr for attr in attrs if attr['Attribute'] == 'FlowMark']
1176
            item.flowMark = int(matches[0]['Value']) if matches and matches[0]['Value'] != 'None' else None
1174 1177

  
1175 1178
            if connectors:
1176 1179
                iterIndex = 0
......
1379 1382
                str(self.uid), index, connector.connectPoint[0], connector.connectPoint[1],\
1380 1383
                str(connector.connectedItem.uid) if connector.connectedItem else None,\
1381 1384
                str(connector._connected_at)))
1385
            index += 1
1382 1386
        sql = 'insert or replace into Points({}) values({})'.format(','.join(cols), ','.join(values))
1383 1387
        res.append((sql, tuple(params)))
1384 1388
        # up to here
1389

  
1390
        # save attributes
1391
        cols = ['UID', 'Components_UID', 'SymbolAttribute_UID', 'Value']
1392
        values = ['?', '?', "(select UID from SymbolAttribute where Attribute='LineType' and SymbolType_UID='-1')", '?']
1393
        param = [(str(uuid.uuid4()), str(self.uid), self.lineType)]
1394
        sql = 'insert or replace into Attributes({}) values({})'.format(','.join(cols), ','.join(values))
1395
        res.append((sql, tuple(param)))
1396
        values = ['?', '?', "(select UID from SymbolAttribute where Attribute='Thickness' and SymbolType_UID='-1')", '?']
1397
        param = [(str(uuid.uuid4()), str(self.uid), str(self.thickness))]
1398
        sql = 'insert or replace into Attributes({}) values({})'.format(','.join(cols), ','.join(values))
1399
        res.append((sql, tuple(param)))
1400
        values = ['?', '?', "(select UID from SymbolAttribute where Attribute='FlowMark' and SymbolType_UID='-1')", '?']
1401
        param = [(str(uuid.uuid4()), str(self.uid), str(self.flowMark))]
1402
        sql = 'insert or replace into Attributes({}) values({})'.format(','.join(cols), ','.join(values))
1403
        res.append((sql, tuple(param)))
1404
        # up to here
1385 1405
        
1386 1406
        return res
1387 1407

  
DTI_PID/DTI_PID/Shapes/EngineeringLineNoTextItem.py
309 309
        item = None
310 310

  
311 311
        try:
312
            location = node.find('LOCATION').text if node.find('LOCATION') is not None else '0,0'
313 312
            x = float(component['X'])
314 313
            y = float(component['Y'])
315
            width = float(component('Width')) if component['Width'] is not None else 0
314
            width = float(component['Width']) if component['Width'] is not None else 0
316 315
            height = float(component['Height']) if component['Height'] is not None else 0
317 316
            angle = float(component['Rotation']) if component['Rotation'] is not None else 0
318 317
            text = component['Value']
......
321 320

  
322 321
            item = TextItemFactory.instance().createTextItem(textInfo)
323 322
            if item is not None:
323
                item.setVisible(False)
324 324
                for key in item._properties.keys():
325 325
                    item._properties[key] = key.parse_value(component[key.Attribute])
326 326
                    
DTI_PID/DTI_PID/Shapes/EngineeringReducerItem.py
163 163
        sql = 'insert or replace into VALVE_DATA_LIST({}) values({})'.format(','.join(cols), ','.join(values))
164 164
        res.append((sql, tuple(param)))
165 165

  
166
        cols = ['UID', 'Drawings_UID', 'Symbol_UID', 'X', 'Y', 'Width', 'Height', 'Rotation', 'Area', 'Owner', 'Connected', 'SuppliedBy', \
166
        cols = ['UID', 'Drawings_UID', 'Symbol_UID', 'X', 'Y', 'Width', 'Height', 'Rotation', 'Area', 'Owner', 'Connected', '[Supplied By]', \
167 167
                'SpecialItemTypes_UID']
168 168
        values = ['?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?']
169 169
        param = [(str(self.uid), str(appDocData.activeDrawing.UID), str(self.dbUid), self.loc[0], self.loc[1], self.size[0], self.size[1], str(self.angle), 
DTI_PID/DTI_PID/Shapes/EngineeringTextItem.py
450 450

  
451 451
        return visited
452 452
    
453
    @staticmethod
454
    def from_database(component):
455
        """ get text item from database """
456
        import uuid
457
        from AppDocData import AppDocData
458
        from TextItemFactory import TextItemFactory
459
        from SymbolAttr import SymbolAttr
460

  
461
        item = None
462

  
463
        try:
464
            x = float(component['X'])
465
            y = float(component['Y'])
466
            width = float(component['Width']) if component['Width'] is not None else 0
467
            height = float(component['Height']) if component['Height'] is not None else 0
468
            angle = float(component['Rotation']) if component['Rotation'] is not None else 0
469
            text = component['Value']
470
            textInfo = TextInfo(text, x, y, width, height, angle)
471
            connline = component['Connected'] if component['Connected'] is not None else None
472

  
473
            item = TextItemFactory.instance().createTextItem(textInfo)
474
            if item is not None:
475
                item.setVisible(False)
476
                item.uid = uuid.UUID(component['UID'], version=4)
477
                item.loc = [x, y]
478
                item.size = (width, height)
479
                item.angle = angle
480
                item.setToolTip('<b>{}</b><br>LINE NO={}'.format(str(item.uid), text))
481

  
482
                if component['Owner'] and component['Owner'] != 'None':
483
                    item._owner = uuid.UUID(component['Owner'], version=4)
484

  
485
                ## assign area
486
                if not component['Area']:
487
                    app_doc_data = AppDocData.instance()
488
                    for area in app_doc_data.getAreaList():
489
                        if area.contains([x, y]):
490
                            item.area = area.name
491
                            break
492
                else:
493
                    item.area = component['Area']
494
                ## up to here
495

  
496
                """ apply freeze value """
497
                #item.freeze_item.update_freeze(item.prop('Freeze'))
498

  
499
                if connline is not None:
500
                    item.conns.append(connline)
501
        except Exception as ex:
502
            from App import App
503
            from AppDocData import MessageType
504

  
505
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
506
            App.mainWnd().addMessage.emit(MessageType.Error, message)
507
            return None
508

  
509
        return item
510

  
453 511
    '''
454 512
        @brief      parse xml code
455 513
        @author     humkyung
......
485 543
                    item.loc = [x, y]
486 544
                    item.size = [width, height]
487 545
                    item.angle = angle
488
            '''
489
            if name == 'NOTE':
490
                item = TextItemFactory.instance().createTextItem(textInfo)
491
                if item is not None:
492
                    item.loc = (x, y)
493
                    item.size = (width, height)
494
                    item.angle = angle
495
                    item.setPlainText(value)
496
                    item.setToolTip('{} = {}'.format(item.type, value))
497
            elif name == 'SIZE':
498
                item = QEngineeringSizeTextItem()
499
                if item is not None:
500
                    item.loc = (x, y)
501
                    item.size = (width, height)
502
                    item.angle = angle
503
                    item.setPlainText(value)
504
                    item.setToolTip('{} = {}'.format(item.type, value))
505
            elif name == 'VALVE OPER CODE':
506
                item = QEngineeringValveOperCodeTextItem()
507
                if item is not None:
508
                    item.loc = (x, y)
509
                    item.size = (width, height)
510
                    item.angle = angle
511
                    item.setPlainText(value)
512
                    item.setToolTip('{} = {}'.format(item.type, value))
513
            else:
514
                item = TextItemFactory.instance().createTextItem(textInfo)
515
                if item is not None:
516
                    item.loc = (x, y)
517
                    item.size = (width, height)
518
                    item.angle = angle
519
            '''
520 546

  
521 547
            # set uid and owner of item
522 548
            if item is not None:
DTI_PID/DTI_PID/Shapes/EngineeringUnknownItem.py
188 188
            app_doc_data = AppDocData.instance()
189 189
            connectors = app_doc_data.get_component_connectors(component['UID'])
190 190
            points = [[float(connector['X']), float(connector['Y'])] for connector in connectors]
191

  
192
            misc = component['Misc']
193
            if misc:
194
                lineIndicator = misc.split('#')
191
            
192
            attrs = app_doc_data.get_component_attributes(component['UID'])
193
            matches = [attr for attr in attrs if attr['Attribute'] == 'LineIndicator']
194
            line_indicator = matches[0]['Value'] if matches else None
195
            if line_indicator:
196
                lineIndicator = line_indicator.split('#')
195 197
                if lineIndicator[0] == 'True':
196 198
                    item = QEngineeringUnknownItem(points, 'True', lineIndicator[1], [round(float(lineIndicator[2])), round(float(lineIndicator[3])), round(float(lineIndicator[4])), round(float(lineIndicator[5]))])
197 199
                elif lineIndicator[0] == 'Match':
......
330 332
        res = []
331 333

  
332 334
        appDocData = AppDocData.instance()
333
        cols = ['UID', 'Drawings_UID', 'Symbol_UID', 'X', 'Y', 'Width', 'Height', 'Area', 'Misc']
334
        values = ['?', '?', "(select UID from Symbol where Name='Unknown' and SymbolType_UID='-1')", '?', '?', '?', '?', '?', '?']
335
        misc = None
336
        if self.lineIndicator == 'True':
337
            misc = 'True' + '#' + self.isVH + '#' + str(self.otherLine[0]) + '#' + str(self.otherLine[1]) + '#' + str(self.otherLine[2]) + '#' + str(self.otherLine[3])
338
        elif self.lineIndicator == 'Match':
339
            misc = 'Match' + '#' + self.isVH + '#' + str(self.otherLine[0]) + '#' + str(self.otherLine[1]) + '#' + str(self.otherLine[2]) + '#' + str(self.otherLine[3])
340
        else:
341
            misc = 'False' + '#' + 'None' + '#' + 'None'
342

  
335
        cols = ['UID', 'Drawings_UID', 'Symbol_UID', 'X', 'Y', 'Width', 'Height', 'Area']
336
        values = ['?', '?', "(select UID from Symbol where Name='Unknown' and SymbolType_UID='-1')", '?', '?', '?', '?', '?']
343 337
        rect = self.sceneBoundingRect()
344
        param = [(str(self.uid), str(appDocData.activeDrawing.UID), rect.x(), rect.y(), rect.width(), rect.height(), self.area, misc)]
338
        param = [(str(self.uid), str(appDocData.activeDrawing.UID), rect.x(), rect.y(), rect.width(), rect.height(), self.area)]
345 339
        sql = 'insert or replace into Components({}) values({})'.format(','.join(cols), ','.join(values))
346 340
        res.append((sql, tuple(param)))
347 341

  
......
356 350
        sql = 'insert or replace into Points({}) values({})'.format(','.join(cols), ','.join(values))
357 351
        res.append((sql, tuple(params)))
358 352

  
353
        # save attributes
354
        cols = ['UID', 'Components_UID', 'SymbolAttribute_UID', 'Value']
355
        values = ['?', '?', "(select UID from SymbolAttribute where Attribute='LineIndicator' and SymbolType_UID='-1')", '?']
356
        line_indicator = None
357
        if self.lineIndicator == 'True':
358
            line_indicator = 'True' + '#' + self.isVH + '#' + str(self.otherLine[0]) + '#' + str(self.otherLine[1]) + '#' + str(self.otherLine[2]) + '#' + str(self.otherLine[3])
359
        elif self.lineIndicator == 'Match':
360
            line_indicator = 'Match' + '#' + self.isVH + '#' + str(self.otherLine[0]) + '#' + str(self.otherLine[1]) + '#' + str(self.otherLine[2]) + '#' + str(self.otherLine[3])
361
        else:
362
            line_indicator = 'False' + '#' + 'None' + '#' + 'None'
363
        param = [(str(uuid.uuid4()), str(self.uid), line_indicator)]
364
        sql = 'insert or replace into Attributes({}) values({})'.format(','.join(cols), ','.join(values))
365
        res.append((sql, tuple(param)))
366
        # up to here
367

  
359 368
        return res
360 369

  
361 370
    '''
DTI_PID/DTI_PID/Shapes/SymbolSvgItem.py
405 405
        sql = 'insert or replace into VALVE_DATA_LIST({}) values({})'.format(','.join(cols), ','.join(values))
406 406
        res.append((sql, tuple(param)))
407 407

  
408
        cols = ['UID', 'Drawings_UID', 'Symbol_UID', 'X', 'Y', 'Width', 'Height', 'Rotation', 'Area', 'Owner', 'Connected', 'SuppliedBy', \
408
        cols = ['UID', 'Drawings_UID', 'Symbol_UID', 'X', 'Y', 'Width', 'Height', 'Rotation', 'Area', 'Owner', 'Connected', '[Supplied By]', \
409 409
                'SpecialItemTypes_UID', 'OriginIndex']
410 410
        values = ['?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?']
411 411
        param = [(str(self.uid), str(appDocData.activeDrawing.UID), str(self.dbUid), self.loc[0], self.loc[1], self.size[0], self.size[1], str(self.angle), 
......
432 432
            values = ['?', '?', '?', '?']
433 433
            params = []
434 434
            for assoc in self.associations():
435
                param = [str(uuid.uuid4()), QEngineeringAbstractItem.assoc_type(assoc), str(self.uid), str(assoc.uid)]
436
                sql = 'insert or replace into Associations({}) values({})'.format(','.join(cols), ','.join(values))
437
                res.append((sql, tuple(param)))
435
                params.append((str(uuid.uuid4()), QEngineeringAbstractItem.assoc_type(assoc), str(self.uid), str(assoc.uid)))
436
            sql = 'insert or replace into Associations({}) values({})'.format(','.join(cols), ','.join(values))
437
            res.append((sql, tuple(params)))
438 438

  
439 439
        # save connectors to database
440 440
        if self.connectors:
......
1168 1168

  
1169 1169
        return node 
1170 1170

  
1171
    def from_database(self, component):
1171
    @staticmethod
1172
    def from_database(component):
1172 1173
        """ create a item related to given component from database """
1173 1174
        import uuid
1174 1175
        from EngineeringSpecBreakItem import QEngineeringSpecBreakItem
......
1180 1181
            app_doc_data = AppDocData.instance()
1181 1182

  
1182 1183
            uid = component['UID']
1183
            pt = [float(component('X')), float(component('Y'))]
1184
            size = [float(component('Width')), float(component('Height'))]
1185

  
1186
            dbUidNode = component['Symbol_UID']
1187
            dbUid = int(dbUidNode.text) if dbUidNode is not None else None
1188
            if dbUid:
1189
                dbData = app_doc_data.getSymbolByQuery('UID', dbUid)
1190
            name = node.find('NAME').text if dbUidNode is None else dbData.sName
1184
            pt = [float(component['X']), float(component['Y'])]
1185
            size = [float(component['Width']), float(component['Height'])]
1191 1186

  
1187
            dbUid = int(component['Symbol_UID'])
1188
            dbData = app_doc_data.getSymbolByQuery('UID', dbUid)
1189
            name = dbData.sName
1190
            _type = dbData.sType
1192 1191
            angle = float(component['Rotation'])
1193
            _type = component['Type'] if dbUidNode is None else dbData.sType
1194 1192
            origin = [float(x) for x in component['OriginalPoint'].split(',')]
1195 1193
            connPts = []
1196
            if component['ConnectionPoint'] is not None:
1194
            if component['ConnectionPoint']:
1197 1195
                for conn_pt in component['ConnectionPoint'].split('/'):
1198 1196
                    tokens = conn_pt.split(',')
1199 1197
                    connPts.append(('AUTO', float(tokens[0]), float(tokens[1]), '0') if len(tokens) == 2 else \
1200
                                   (tokens[0], float(tokens[1]), float(tokens[2]), '0') if len(tokens) == 3 else \
1201
                                   (tokens[0], float(tokens[1]), float(tokens[2]), tokens[3]))
1202
            baseSymbol = component['BaseSymbol'] if dbUidNode is None else dbData.baseSymbol
1198
                                (tokens[0], float(tokens[1]), float(tokens[2]), '0') if len(tokens) == 3 else \
1199
                                (tokens[0], float(tokens[1]), float(tokens[2]), tokens[3]))
1203 1200

  
1204
            childSymbolNode = component('AdditionalSymbol')
1205
            childSymbol = ''
1206
            if childSymbolNode is not None:
1207
                childSymbol = childSymbolNode.text
1201
            baseSymbol = dbData.baseSymbol
1202

  
1203
            childSymbolNode = component['AdditionalSymbol']
1204
            childSymbol = childSymbolNode if childSymbolNode is not None else ''
1208 1205
            
1209 1206
            owner = component['Owner'] if component['Owner'] is not None and component['Owner'] != 'None' else None
1210 1207

  
1211 1208
            hasInstrumentLabelNode = component['HasInstrumentLabel']
1212
            hasInstrumentLabel = hasInstrumentLabelNode.text if hasInstrumentLabelNode is not None else 'False'
1209
            hasInstrumentLabel = hasInstrumentLabelNode if hasInstrumentLabelNode is not None else 'False'
1213 1210

  
1214 1211
            flipLabelNode = component['Flip']
1215
            flipLabel = int(flipLabelNode.text) if flipLabelNode is not None else 0
1212
            flipLabel = int(flipLabelNode) if flipLabelNode is not None else 0
1216 1213

  
1217 1214
            project = app_doc_data.getCurrentProject()
1218 1215
            svgFilePath = os.path.join(project.getSvgFilePath(), _type, name + '.svg')
......
1235 1232
                    return None
1236 1233

  
1237 1234
                for key in item._properties.keys():
1238
                    item._properties[key] = key.parse_value(component[key.Attribute]) if component[key.Attribute] else ''
1235
                    if key.Attribute in component:
1236
                        item._properties[key] = key.parse_value(component[key.Attribute]) if component[key.Attribute] else ''
1239 1237

  
1240 1238
                ## assign area
1241 1239
                areaNode = component['Area']
......
1245 1243
                            item.area = area.name
1246 1244
                            break
1247 1245
                else:
1248
                    item.area = areaNode.text
1246
                    item.area = areaNode
1249 1247
                ## up to here
1250 1248
                
1251 1249
                connectors = app_doc_data.get_component_connectors(uid)
......
1285 1283
                        
1286 1284
                currentPointModeIndex = component['OriginIndex']
1287 1285
                if currentPointModeIndex is not None:
1288
                    item.currentPointModeIndex = int(currentPointModeIndex.text)
1286
                    item.currentPointModeIndex = int(currentPointModeIndex)
1289 1287
        except Exception as ex:
1290 1288
            from App import App 
1291 1289
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
DTI_PID/DTI_PID/SymbolAttr.py
100 100
        else:
101 101
            return uuid.UUID(text, version=4) if text and SymbolProp.is_valid_uuid(text) else text if text else ''
102 102

  
103
    def parse_record(self, record):
104
        """ parse record for property """
105
        import uuid
106
        
107
        self.UID = uuid.UUID(record['UID'], version=4)
108
        self.Freeze = record['Freeze'] == 'True' if record['Freeze'] else False
109
        self.Attribute = record['Attribute']
110
        self.AttributeType = record['AttributeType']
111
        self.DisplayAttribute = record['DisplayAttribute']
112
        self.Expression = record['Expression']
113
        self.Length = record['Length']
114

  
115 103
    def toXml(self):
116 104
        """ generate xml code for symbol property """
117 105
        from xml.etree.ElementTree import Element, SubElement, dump, ElementTree
......
146 134
        self.IsProp = None
147 135

  
148 136
    @staticmethod
137
    def from_record(record):
138
        """ parse record for property """
139
        import uuid
140
        
141
        attr = SymbolAttr()
142
        attr.UID = uuid.UUID(record['UID'], version=4)
143
        #attr.Freeze = record['Freeze'] == 'True' if record['Freeze'] else False
144
        attr.Attribute = record['Attribute']
145
        attr.DisplayAttribute = record['DisplayAttribute']
146
        attr.AttributeType = record['AttributeType']
147
        attr.AttrAt = record['AttrAt']
148
        attr.Expression = record['Expression']
149
        attr.Length = record['Length']
150
        attr.IsProp = int(record['Property'])
151

  
152
        return attr
153

  
154
    @staticmethod
149 155
    def fromXml(node):
150 156
        """ generate SymbolAttr instance from xml node """
151 157
        import uuid

내보내기 Unified diff

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