프로젝트

일반

사용자정보

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

hytos / DTI_PID / DTI_PID / AppDocData.py @ de3f62c6

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

1
# coding: utf-8
2
""" This is document data(SDI) class """
3

    
4
import sys
5
import os
6
import sqlite3
7
import datetime
8
from enum import Enum
9
from PIL import PngImagePlugin, JpegImagePlugin
10
from PIL import Image
11
from PIL.ImageQt import ImageQt
12

    
13
try:
14
    from PyQt5.QtCore import *
15
    from PyQt5.QtGui import *
16
    from PyQt5 import QtWidgets
17
except ImportError:
18
    from PyQt4.QtCore import *
19
    from PyQt4.QtGui import *
20

    
21
from SingletonInstance import SingletonInstance
22
import symbol
23
from NominalPipeSize import NominalPipeSize
24

    
25

    
26
class Config:
27
    def __init__(self, section, key, value):
28
        self.section = section
29
        self.key = key
30
        self.value = value
31

    
32
    '''
33
        @brief  return size value string
34
        @author humkyung
35
        @date   2018.04.24
36
    '''
37

    
38
    def sizeValue(self):
39
        return self.inchStr if 'Inch' == self.sizeUnit else self.metricStr
40

    
41

    
42
'''
43
    @brief  Pipe color class
44
'''
45

    
46

    
47
class Color:
48
    def __init__(self, index, red, green, blue):
49
        self.index = index
50
        self.red = red
51
        self.green = green
52
        self.blue = blue
53

    
54

    
55
'''
56
    @brief      MessageType
57
    @author     humkyung 
58
    @date       2018.07.31
59
'''
60

    
61

    
62
class MessageType(Enum):
63
    Normal = 1
64
    Error = 2
65
    Check = 3
66

    
67

    
68
class AppDocData(SingletonInstance):
69
    DATABASE = 'ITI_PID.db'
70

    
71
    def __init__(self):
72
        from DisplayColors import DisplayColors
73

    
74
        self._imgFilePath = None
75
        self.imgName = None
76
        self._OCRData = None
77
        self._imgSrc = None
78

    
79
        self._areas = []
80
        self.equipments = []
81
        self.lineNos = []
82
        self.lines = []
83
        self.texts = []
84
        self.symbols = []
85
        self.unknowns = []
86
        self.allItems = []
87
        self.tracerLineNos = []
88
        self.lineIndicators = []
89
        self._colors = None
90
        self._lineNoProperties = None
91
        self._lineTypes = None
92
        self._lineTypeConfigs = None
93
        self._activeDrawing = None
94
        self._hmbTable = None
95
        self._titleBlockProperties = None
96
        self.needReOpening = None
97

    
98
        # caches
99
        self._configs = None
100
        self._symbolBase = {}
101
        self._symbolType = {}
102
        self._lineNoPropertiesUID = {}
103
        self._attributeByType = {}
104

    
105
        # for load drawing data from database
106
        self._connecterss = {}
107
        self._associationss = {}
108
        self._attributess = {}
109

    
110
    def clearTempDBData(self):
111
        self._connecterss = {}
112
        self._associationss = {}
113
        self._attributess = {}
114

    
115
    def clearItemList(self, trim):
116
        '''
117
            @brief      clear item list
118
            @author     euisung
119
            @date       2018.11.28
120
        '''
121
        self.equipments.clear()
122
        self.symbols.clear()
123
        self.lineNos.clear()
124
        self.texts.clear()
125
        self.unknowns.clear()
126
        self.allItems.clear()
127
        self.lineIndicators.clear()
128
        if trim:
129
            self.tracerLineNos.clear()
130
            self.lines.clear()
131

    
132
    '''
133
        @brief      clear
134
        @author     humkyung
135
        @date       2018.09.06
136
    '''
137

    
138
    def clear(self):
139
        if self.activeDrawing and self.activeDrawing.UID:
140
            self.clear_occupying_drawing(self.activeDrawing.UID)
141

    
142
        self._imgFilePath = None
143
        self.imgName = None
144
        self._imgSrc = None
145

    
146
        self._areas.clear()
147
        self.equipments.clear()
148
        self.lineNos.clear()
149
        self.lines.clear()
150
        self.texts.clear()
151
        self.symbols.clear()
152
        self.unknowns.clear()
153
        self.allItems.clear()
154
        self.tracerLineNos.clear()
155
        self.lineIndicators.clear()
156
        self._colors = None
157
        self._lineNoProperties = None
158
        self._lineTypeConfigs = None
159
        self._activeDrawing = None
160
        self._hmbTable = None
161
        self._titleBlockProperties = None
162

    
163
        self._configs = None
164
        self._symbolBase = {}
165
        self._symbolType = {}
166
        self._lineNoPropertiesUID = {}
167
        self._attributeByType = {}
168

    
169
        self._connecterss = {}
170
        self._associationss = {}
171
        self._attributess = {}
172

    
173
    def clear_occupying_drawing(self, drawing):
174
        """ clear drawing access """
175
        conn = self.project.database.connect()
176
        with conn:
177
            try:
178
                # Get a cursor object
179
                cursor = conn.cursor()
180
                if drawing:
181
                    sql = "UPDATE Drawings SET [OCCUPIED]=null WHERE [OCCUPIED]='{}' and UID='{}'".format(os.environ['COMPUTERNAME'], drawing)
182
                else:
183
                    sql = "UPDATE Drawings SET [OCCUPIED]=null"
184
                cursor.execute(sql)
185

    
186
                conn.commit()
187
            # Catch the exception
188
            except Exception as ex:
189
                conn.rollback()
190

    
191
                from App import App 
192
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
193
                App.mainWnd().addMessage.emit(MessageType.Error, message)
194

    
195
    def set_occupying_drawing(self, drawing):
196
        """ set drawing access return true if success"""
197
        conn = self.project.database.connect()
198
        with conn:
199
            try:
200
                # Get a cursor object
201
                cursor = conn.cursor()
202
                sql = "select OCCUPIED from Drawings where [UID]='{}'".format(drawing)
203
                cursor.execute(sql)
204

    
205
                rows = cursor.fetchall()
206
                if not rows[0][0] or rows[0][0] == os.environ['COMPUTERNAME']:
207
                    sql = "UPDATE Drawings SET [OCCUPIED]='{}' WHERE UID='{}'".format(os.environ['COMPUTERNAME'], drawing)
208
                    cursor.execute(sql)
209
                    conn.commit()
210
                    return True
211
                else:
212
                    return False
213

    
214
            # Catch the exception
215
            except Exception as ex:
216
                conn.rollback()
217

    
218
                from App import App 
219
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
220
                App.mainWnd().addMessage.emit(MessageType.Error, message)
221

    
222
                return False
223

    
224
    '''
225
        @brief      Get drawing file list
226
        @author     euisung
227
        @date       2018.09.28
228
    '''
229

    
230
    def getDrawingFileList(self):
231
        """ get drawing files which's extension is .png or jpg from drawing folder """
232
        drawingFileList = []
233

    
234
        try:
235
            project = AppDocData.instance().getCurrentProject()
236
            path = project.getDrawingFilePath()
237
            drawingFileList = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f)) and
238
                               (os.path.splitext(f)[1].upper() == '.PNG' or os.path.splitext(f)[1].upper() == '.JPG' or
239
                                os.path.splitext(f)[1].upper() == '.JPEG')]
240
            drawingFileList.sort()
241
        except Exception as ex:
242
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
243
                                                      sys.exc_info()[-1].tb_lineno))
244

    
245
        return drawingFileList
246

    
247
    '''
248
        @brief      Get Training file list
249
        @author     euisung
250
        @date       2018.10.16
251
    '''
252

    
253
    def getTrainingFileList(self):
254
        try:
255
            project = AppDocData.instance().getCurrentProject()
256
            path = project.getTrainingFilePath()
257
            trainingFileList = os.listdir(path)
258
            trainingFileList.sort()
259
        except Exception as ex:
260
            from App import App
261
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
262
                                                          sys.exc_info()[-1].tb_lineno)
263
            App.mainWnd().addMessage.emit(MessageType.Error, message)
264

    
265
        return trainingFileList
266

    
267
    def getTrainingSymbolFileList(self):
268
        """  Get Symbol Training file list """
269
        try:
270
            project = AppDocData.instance().getCurrentProject()
271
            path = project.getTrainingSymbolFilePath()
272
            symbolTrainingFileList = os.listdir(path)
273
            symbolTrainingFileList.sort()
274
        except Exception as ex:
275
            from App import App
276
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
277
                                                          sys.exc_info()[-1].tb_lineno)
278
            App.mainWnd().addMessage.emit(MessageType.Error, message)
279

    
280
        return symbolTrainingFileList
281

    
282
    '''
283
        @brief      Get DB file path in ProgramData
284
        @author     Jeongwoo
285
        @date       2018.06.27
286
        @history    2018.06.29  Jeongwoo    Change method to get template db path
287
    '''
288

    
289
    def getTemplateDbPath(self):
290
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
291
        templateDbPath = os.path.join(path, 'Template.db')
292
        return templateDbPath
293

    
294
    def get_template_symbol_library_path(self):
295
        """return template symbol library path"""
296

    
297
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
298
        return os.path.join(path, 'SymbolLibrary.syl')
299

    
300
    def getAppDbPath(self):
301
        """
302
        @brief      Get application DB file path in ProgramData
303
        @author     humkyung
304
        @date       2018.10.01
305
        """
306

    
307
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
308
        app_database = os.path.join(path, 'App.db')
309
        return app_database
310

    
311
    '''
312
        @brief  getter of colors 
313
        @author humkyung
314
        @date   2018.06.18
315
    '''
316

    
317
    @property
318
    def colors(self):
319
        import random
320

    
321
        if self._colors is None or self._colors == []:
322
            self._colors = []
323
            with self.project.database.connect() as conn:
324
                try:
325
                    cursor = conn.cursor()
326
                    sql = 'SELECT UID,RED,GREEN,BLUE FROM Colors'
327
                    cursor.execute(sql)
328
                    rows = cursor.fetchall()
329
                    for row in rows:
330
                        self._colors.append(Color(int(row[0]), int(row[1]), int(row[2]), int(row[3])))
331
                # Catch the exception
332
                except Exception as ex:
333
                    from App import App
334
                    message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
335
                                                                  sys.exc_info()[-1].tb_lineno)
336
                    App.mainWnd().addMessage.emit(MessageType.Error, message)
337

    
338
        return self._colors.pop(random.randrange(0, len(self._colors)))
339

    
340
    '''
341
        @brief  setter of colors
342
        @author humkyung
343
        @date   2018.06.18
344
    '''
345

    
346
    @colors.setter
347
    def colors(self, value):
348
        self._colors = value
349

    
350
    '''
351
        @brief      set image file path
352
        @author     humkyung
353
        @date       2018.07.30
354
    '''
355

    
356
    def setImgFilePath(self, path):
357
        self._imgFilePath = path
358
        self.imgName = os.path.splitext(os.path.basename(self._imgFilePath))[0]
359

    
360
    @staticmethod
361
    def my_imread(file_path):
362
        """ read a file which's name contains unicode string : ref http://devdoftech.co.kr:82/redmine/issues/631 """
363
        import numpy as np
364
        import cv2
365

    
366
        _bytes = None
367
        with open(file_path.encode('utf-8'), 'rb') as stream:
368
            _bytes = bytearray(stream.read())
369

    
370
        numpyArray = np.asarray(_bytes, dtype=np.uint8)
371
        res = cv2.imdecode(numpyArray, cv2.IMREAD_UNCHANGED)
372
        return res
373

    
374
    @property
375
    def imgSrc(self):
376
        """return the image of active drawing"""
377

    
378
        if self.activeDrawing:
379
            return self.activeDrawing.image
380

    
381
        return None
382

    
383
    @imgSrc.setter
384
    def imgSrc(self, value):
385
        """set the image of active drawing with given value"""
386

    
387
        if self.activeDrawing:
388
            self.activeDrawing.image = value
389

    
390
    '''
391
        @brief  getter of line type configs
392
        @author humkyung
393
        @date   2018.06.28
394
    '''
395

    
396
    @property
397
    def lineTypeConfigs(self):
398
        from PyQt5.QtCore import Qt
399

    
400
        if self._lineTypeConfigs is None:
401
            self._lineTypeConfigs = []
402

    
403
            styleMap = [('SolidLine', Qt.SolidLine), ('DashLine', Qt.DashLine), ('DotLine', Qt.DotLine),
404
                        ('DashDotLine', Qt.DashDotLine),
405
                        ('DashDotDotLine', Qt.DashDotDotLine), ('CustomDashLine', Qt.CustomDashLine)]
406

    
407
            configs = self.getConfigs('LineTypes')
408
            for config in configs:
409
                color, width, _style, transparent = config.value.split(',')
410
                matches = [param for param in styleMap if param[0] == _style]
411
                style = matches[0][1] if matches else Qt.SolidLine
412
                self._lineTypeConfigs.append((config.key, color, int(width), style, float(transparent)))
413

    
414
        return self._lineTypeConfigs
415

    
416
    '''
417
        @brief  setter of line type configs
418
        @author humkyung
419
        @date   2018.06.28
420
    '''
421

    
422
    @lineTypeConfigs.setter
423
    def lineTypeConfigs(self, value):
424
        self._lineTypeConfigs = value
425

    
426
    @property
427
    def drain_size(self):
428
        """ getter of drain_size """
429
        if not hasattr(self, '_drain_size') or not self._drain_size:
430
            configs = self.getConfigs('Drain Size Rule', 'Size')
431
            self._drain_size = configs[0].value if configs else '1"'
432

    
433
        return self._drain_size
434

    
435
    @drain_size.setter
436
    def drain_size(self, value):
437
        """ setter of drain_size """
438
        self._drain_size = value
439

    
440
    '''
441
        @brief      getter of hmb table
442
        @author     humkyung
443
        @date       2018.07.16
444
    '''
445

    
446
    @property
447
    def hmbTable(self):
448
        from HMBTable import HMBTable
449

    
450
        if self._hmbTable is None:
451
            self._hmbTable = HMBTable()
452
            self._hmbTable.loadData()
453

    
454
        return self._hmbTable
455

    
456
    '''
457
        @brief      setter of hmb table
458
        @author     humkyung
459
        @date       2018.07.16
460
    '''
461

    
462
    @hmbTable.setter
463
    def hmbTable(self, value):
464
        self._hmbTable = value
465

    
466
    '''
467
        @brief  get line type config of given line type
468
        @author humkyung
469
        @date   2018.06.28
470
    '''
471

    
472
    def getLineTypeConfig(self, lineType):
473
        from PyQt5.QtCore import Qt
474

    
475
        matches = [config for config in self.lineTypeConfigs if config[0] == lineType]
476
        return matches[0] if matches else (lineType, '#0000FF', 5, Qt.SolidLine, 50)
477

    
478
    def getCurrentPidSource(self):
479
        return self.activeDrawing.currentPidSource
480

    
481
    '''
482
        @brief      Check if exist file name or not
483
        @author     Jeongwoo
484
        @date       2018.05.03
485
    '''
486

    
487
    def isExistFileName(self, name):
488
        rows = None
489
        with self.project.database.connect() as conn:
490
            try:
491
                cursor = conn.cursor()
492
                sql = "SELECT * FROM Symbol WHERE name = '" + name + "'"
493
                cursor.execute(sql)
494
                rows = cursor.fetchall()
495
            # Catch the exception
496
            except Exception as ex:
497
                # Roll back any change if something goes wrong
498
                conn.rollback()
499
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
500
                                                          sys.exc_info()[-1].tb_lineno))
501
            finally:
502
                if rows is not None and len(rows) > 0:
503
                    return True
504
                else:
505
                    return False
506

    
507
    '''
508
        @brief      Insert new symbol into Symbol Table, Moved from SG_DbHelper
509
        @author     Jeongwoo
510
        @date       2018.05.03
511
    '''
512

    
513
    def insertSymbol(self, symbol):
514
        isAdded = False
515
        with self.project.database.connect() as conn:
516
            try:
517
                sql = self.project.database.to_sql("""
518
                    INSERT INTO Symbol(name, SymbolType_UID, threshold, minMatchPoint, isDetectOrigin, rotationCount, ocrOption, isContainChild, originalPoint, connectionPoint, baseSymbol, additionalSymbol, isExceptDetect, hasInstrumentLabel, width, height, flip) 
519
                    VALUES(?, (select UID from SymbolType where Type=?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
520
                """)
521

    
522
                cursor = conn.cursor()
523
                query = (symbol.getName(), symbol.getType(), symbol.getThreshold()
524
                         , symbol.getMinMatchCount(), symbol.getIsDetectOnOrigin(), symbol.getRotationCount()
525
                         , symbol.getOcrOption(), symbol.getIsContainChild()
526
                         , symbol.getOriginalPoint(), symbol.getConnectionPoint()
527
                         , symbol.getBaseSymbol(), symbol.getAdditionalSymbol(), symbol.getIsExceptDetect(),
528
                         symbol.getHasInstrumentLabel()
529
                         , symbol.width, symbol.height, symbol.detectFlip)
530
                cursor.execute(sql, query)
531
                conn.commit()
532
                isAdded = True
533
            # Catch the exception
534
            except Exception as ex:
535
                # Roll back any change if something goes wrong
536
                conn.rollback()
537

    
538
                from App import App
539
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
540
                                                              sys.exc_info()[-1].tb_lineno)
541
                App.mainWnd().addMessage.emit(MessageType.Error, message)
542
            finally:
543
                return (isAdded, symbol.getType(), symbol.getName(), symbol.getPath())
544

    
545
    '''
546
        @brief      Update symbol in Symbol Table, Moved from SG_DbHelper
547
        @author     Jeongwoo
548
        @date       2018.05.03
549
    '''
550

    
551
    def updateSymbol(self, symbol):
552
        isUpdated = False
553

    
554
        with self.project.database.connect() as conn:
555
            try:
556
                sql = self.project.database.to_sql("""
557
                    UPDATE Symbol
558
                    SET
559
                        name = ?, SymbolType_UID=(select UID from SymbolType where Type=?), threshold = ?, minMatchPoint = ?, isDetectOrigin = ?,
560
                        rotationCount = ?, ocrOption = ?, isContainChild = ?, originalPoint = ?, connectionPoint = ?,
561
                        baseSymbol = ?, additionalSymbol = ?, isExceptDetect = ?, hasInstrumentLabel = ?, width = ?, height = ?, flip = ?
562
                    WHERE uid = ?
563
                """)
564

    
565
                cursor = conn.cursor()
566
                query = (symbol.getName(), symbol.getType(), symbol.getThreshold()
567
                         , symbol.getMinMatchCount(), symbol.getIsDetectOnOrigin(), symbol.getRotationCount()
568
                         , symbol.getOcrOption(), symbol.getIsContainChild()
569
                         , symbol.getOriginalPoint(), symbol.getConnectionPoint()
570
                         , symbol.getBaseSymbol(), symbol.getAdditionalSymbol(), symbol.getIsExceptDetect(),
571
                         symbol.getHasInstrumentLabel(), symbol.width, symbol.height, symbol.detectFlip,
572
                         symbol.getUid())
573
                cursor.execute(sql, query)
574
                conn.commit()
575
                isUpdated = True
576
            # Catch the exception
577
            except Exception as ex:
578
                # Roll back any change if something goes wrong
579
                conn.rollback()
580

    
581
                from App import App
582
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
583
                                                              sys.exc_info()[-1].tb_lineno)
584
                App.mainWnd().addMessage.emit(MessageType.Error, message)
585
            finally:
586
                self._symbolBase = {}
587
                return (isUpdated, symbol.getType(), symbol.getName(), symbol.getPath())
588

    
589
    '''
590
        @brief      Get Detecting Target Symbol List (Field 'isExceptDetect' == False(0))
591
        @author     Jeongwoo
592
        @date       18.04.24
593
        @history    humkyung 2018.06.28 select symbol order by threshold descending
594
    '''
595

    
596
    def getTargetSymbolList(self):
597
        targetSymbolList = []
598

    
599
        with self.project.database.connect() as conn:
600
            cursor = conn.cursor()
601
            sql = """SELECT a.UID,a.Name,b.Type,a.Threshold,a.MinMatchPoint,a.IsDetectOrigin,a.RotationCount,a.OCROption,a.IsContainChild,a.OriginalPoint,a.ConnectionPoint,
602
                    a.BaseSymbol,a.AdditionalSymbol,a.IsExceptDetect,a.HasInstrumentLabel,a.flip,b.UID FROM Symbol a inner join SymbolType b on a.SymbolType_UID=b.UID WHERE a.IsExceptDetect = 0 order by width * height desc"""
603
            try:
604
                cursor.execute(sql)
605
                rows = cursor.fetchall()
606
                for row in rows:
607
                    sym = symbol.SymbolBase(row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9],
608
                                            row[10], row[11], row[12], row[13], row[14], row[0], iType=row[16],
609
                                            detectFlip=row[15])  # uid is last item
610
                    targetSymbolList.append(sym)
611
            except Exception as ex:
612
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
613
                                                          sys.exc_info()[-1].tb_lineno))
614

    
615
        return targetSymbolList
616

    
617
    def buildAppDatabase(self):
618
        """build application database"""
619
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
620
        appDatabaseFilePath = os.path.join(path, 'App.db')
621

    
622
        # Creates or opens a file called mydb with a SQLite3 DB
623
        with sqlite3.connect(appDatabaseFilePath) as conn:
624
            try:
625
                # Get a cursor object
626
                cursor = conn.cursor()
627

    
628
                sqlFiles = ['App.Configuration.sql', 'App.Styles.sql']
629
                for sqlFile in sqlFiles:
630
                    filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', sqlFile)
631
                    try:
632
                        file = QFile(filePath)
633
                        file.open(QFile.ReadOnly)
634
                        sql = file.readAll()
635
                        sql = str(sql, encoding='utf8')
636
                        cursor.executescript(sql)
637
                    finally:
638
                        file.close()
639
                conn.commit()
640
            # Catch the exception
641
            except Exception as ex:
642
                # Roll back any change if something goes wrong
643
                conn.rollback()
644
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
645
                                                          sys.exc_info()[-1].tb_lineno))
646

    
647
        # expiration date is 2019-11-9-23-59-59 : e52SoJJRdZ-apJuhlFWtnFWC
648
        # configs = [Config('app', 'error origin point', '51,72'), Config('app', 'expiration', 'e52SoJJRdZ-apJuhlFWtnFWC')]
649

    
650
        configs = self.getAppConfigs('app', 'expiration')
651
        if not configs:
652
            configs = self.getAppConfigs('app', 'license')
653
            if configs and 'DOFTECH' in configs[0].value:
654
                self.deleteAppConfigs('app', 'mode')
655
                configs = None
656
            else:
657
                configs = [Config('app', 'mode', 'advanced')]
658
        else:
659
            configs = None
660

    
661
        if configs:
662
            self.saveAppConfigs(configs)
663

    
664
    '''
665
        @brief  load app style
666
        @author humkyung
667
        @date   2018.04.20
668
    '''
669

    
670
    def loadAppStyle(self):
671
        style = 'Fusion'
672

    
673
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
674
        if not os.path.exists(path): os.makedirs(path)
675

    
676
        self.buildAppDatabase()
677
        try:
678
            appDatabaseFilePath = os.path.join(path, 'App.db')
679
            # Creates or opens a file called mydb with a SQLite3 DB
680
            conn = sqlite3.connect(appDatabaseFilePath)
681
            # Get a cursor object
682
            cursor = conn.cursor()
683

    
684
            sql = "select Value from Configuration where Section='App' and Key='Style'"
685
            cursor.execute(sql)
686
            rows = cursor.fetchall()
687
            style = rows[0][0] if 1 == len(rows) else 'Fusion'
688
        # Catch the exception
689
        except Exception as ex:
690
            # Roll back any change if something goes wrong
691
            conn.rollback()
692
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
693
                                                      sys.exc_info()[-1].tb_lineno))
694
        finally:
695
            # Close the db connection
696
            conn.close()
697

    
698
        return style
699

    
700
    '''
701
        @brief  load app styles and then return a list
702
        @author humkyung
703
        @date   2018.04.20
704
    '''
705

    
706
    def loadAppStyles(self):
707
        styles = []
708

    
709
        try:
710
            self.buildAppDatabase()
711

    
712
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
713
            appDatabaseFilePath = os.path.join(path, 'App.db')
714

    
715
            # Creates or opens a file called mydb with a SQLite3 DB
716
            conn = sqlite3.connect(appDatabaseFilePath)
717
            # Get a cursor object
718
            cursor = conn.cursor()
719

    
720
            sql = 'select UID,Value from Styles'
721
            cursor.execute(sql)
722
            rows = cursor.fetchall()
723
            for row in rows: styles.append(row[1])
724
            if 0 == len(rows): rows.append('fusion')
725
        # Catch the exception
726
        except Exception as ex:
727
            # Roll back any change if something goes wrong
728
            conn.rollback()
729
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
730
                                                      sys.exc_info()[-1].tb_lineno))
731
        finally:
732
            # Close the db connection
733
            conn.close()
734

    
735
        return styles
736

    
737
    '''
738
        @brief  Set current Project
739
        @history    2018.06.27  Jeongwoo    If DB file is not, copy DB file from ProgramData
740
    '''
741

    
742
    def setCurrentProject(self, project):
743
        self.project = project
744
        project.make_sub_directories()
745
        try:
746
            if self.project.database.db_type == 'SQLite':
747
                # Creates or opens a file called mydb with a SQLite3 DB
748
                db_path = self.project.database.file_path
749

    
750
                if not os.path.isfile(db_path):
751
                    templatePath = self.getTemplateDbPath()
752
                    templateFile = QFile(templatePath)
753
                    templateFile.copy(db_path)
754

    
755
                try:
756
                    conn = self.project.database.connect()
757
                    with conn:
758
                        # Get a cursor object
759
                        cursor = conn.cursor()
760

    
761
                        fileNames = os.listdir(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts'))
762
                        for fileName in fileNames:
763
                            if fileName.endswith(".sql") and ('SQLite_Project' == os.path.splitext(fileName)[0].split('.')[0]):
764
                                try:
765
                                    file = QFile(
766
                                        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', fileName))
767
                                    file.open(QFile.ReadOnly)
768
                                    sql = file.readAll()
769
                                    sql = str(sql, encoding='utf8')
770
                                    cursor.executescript(sql)
771
                                finally:
772
                                    file.close()
773
                        conn.commit()
774
                        self.saveConfigs([Config('Project', 'Unit', project.prj_unit)])
775
                except Exception as ex:
776
                    print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
777
                                                              sys.exc_info()[-1].tb_lineno))
778
        # Catch the exception
779
        except Exception as ex:
780
            # Roll back any change if something goes wrong
781
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
782
                                                      sys.exc_info()[-1].tb_lineno))
783
        finally:
784
            pass
785

    
786
    '''
787
        @brief  Get current Project
788
    '''
789

    
790
    def getCurrentProject(self):
791
        return self.project
792

    
793
    '''
794
        @brief      return project database path
795
        @history    humkyung 2018.04.19 return Project.db in Program Data folder instead of PROJECT_DB_PATH variable
796
    '''
797

    
798
    def getPrjDatabasePath(self):
799
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
800
        if not os.path.exists(path): os.makedirs(path)
801

    
802
        prjDatabaseFilePath = os.path.join(path, 'Project.db')
803
        try:
804
            # Creates or opens a file called mydb with a SQLite3 DB
805
            conn = sqlite3.connect(prjDatabaseFilePath)
806
            # Get a cursor object
807
            cursor = conn.cursor()
808

    
809
            filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', 'Project.Projects.sql')
810
            try:
811
                file = QFile(filePath)
812
                file.open(QFile.ReadOnly)
813
                sql = file.readAll()
814
                sql = str(sql, encoding='utf8')
815
                cursor.executescript(sql)
816
            finally:
817
                file.close()
818
            conn.commit()
819
        # Catch the exception
820
        except Exception as ex:
821
            # Roll back any change if something goes wrong
822
            conn.rollback()
823
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
824
                                                      sys.exc_info()[-1].tb_lineno))
825
        finally:
826
            # Close the db connection
827
            conn.close()
828

    
829
        return prjDatabaseFilePath
830

    
831
    def getErrorItemSvgPath(self):
832
        '''
833
            @brief  return error item svg path
834
            @author euisung
835
            @date   2019.04.02
836
        '''
837
        return os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID', 'Explode.svg')
838

    
839
    def updateTitleBlockProperties(self, titleBlockProps):
840
        '''
841
            @brief  update title block properties
842
            @author euisung
843
            @date   2018.11.09
844
        '''
845
        try:
846
            originTitleBlockProps = self.getTitleBlockProperties()
847
            deletedTitleBlockProps = []
848
            for originTitleBlockProp in originTitleBlockProps:
849
                for titleBlockProp in titleBlockProps:
850
                    # uid compare for determine delete props
851
                    if originTitleBlockProp[0] == titleBlockProp[0]:
852
                        break
853
                deletedTitleBlockProps.append(originTitleBlockProp[0])
854

    
855
            # Creates or opens a file called mydb with a SQLite3 DB
856
            conn = self.project.database.connect()
857
            with conn:
858
                try:
859
                    # Get a cursor object
860
                    cursor = conn.cursor()
861

    
862
                    for deletedTitleBlockProp in deletedTitleBlockProps:
863
                        sql = "delete from TitleBlockValues where TitleBlockProperties_UID='{}'".format(deletedTitleBlockProp)
864
                        cursor.execute(sql)
865
                        sql = "delete from TitleBlockProperties where UID='{}'".format(deletedTitleBlockProp)
866
                        cursor.execute(sql)
867

    
868
                    for titleBlockProp in titleBlockProps:
869
                        sql = self.project.database.to_sql("insert into [TitleBlockProperties]([UID], [NAME], [AREA], [TEXT]) values(?,?,?,?)")
870
                        param = (titleBlockProp[0], titleBlockProp[1], titleBlockProp[2], titleBlockProp[3])  # uid, name, area, text
871
                        cursor.execute(sql, param)
872
                    conn.commit()
873
                    # Catch the exception
874
                except Exception as ex:
875
                    # Roll back any change if something goes wrong
876
                    conn.rollback()
877
                    from App import App
878
                    from AppDocData import MessageType
879
                    message = 'error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename,
880
                                                                   sys.exc_info()[-1].tb_lineno)
881
                    App.mainWnd().addMessage.emit(MessageType.Error, message)
882
        # Catch the exception
883
        except Exception as ex:
884
            from App import App
885
            from AppDocData import MessageType
886
            message = 'error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename,
887
                                                           sys.exc_info()[-1].tb_lineno)
888
            App.mainWnd().addMessage.emit(MessageType.Error, message)
889

    
890
        self._titleBlockProperties = None
891

    
892
    def getTitleBlockProperties(self):
893
        """"return title block properties"""
894

    
895
        res = None
896
        if self._titleBlockProperties is None:
897
            self._titleBlockProperties = []
898

    
899
            # Creates or opens a file called mydb with a SQLite3 DB
900
            conn = self.project.database.connect()
901
            with conn:
902
                try:
903
                    # Get a cursor object
904
                    cursor = conn.cursor()
905

    
906
                    sql = "select UID, Name, AREA, [TEXT] from TitleBlockProperties"
907
                    cursor.execute(sql)
908
                    rows = cursor.fetchall()
909
                    for row in rows:
910
                        attr = []
911
                        attr.append(row[0])  # uid
912
                        attr.append(row[1])  # name
913
                        attr.append(row[2])  # area
914
                        attr.append(row[3])  # text
915
                        self._titleBlockProperties.append(attr)
916

    
917
                    res = self._titleBlockProperties
918
                # Catch the exception
919
                except Exception as ex:
920
                    print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
921
                                                              sys.exc_info()[-1].tb_lineno))
922
        else:
923
            res = self._titleBlockProperties
924

    
925
        return res
926

    
927
    def clearLineNoProperties(self):
928
        self._lineNoProperties = None
929
        self._lineNoPropertiesUID = {}
930

    
931
    def getLineProperties(self):
932
        """return line no properties"""
933
        from SymbolAttr import SymbolAttr
934

    
935
        res = None
936
        if self._lineNoProperties is None:
937
            self._lineNoProperties = []
938

    
939
            with self.project.database.connect() as conn:
940
                try:
941
                    # Get a cursor object
942
                    cursor = conn.cursor()
943

    
944
                    sql = "select UID, Name, DisplayName, Type, LimitNumber, [index] from LineProperties " \
945
                          "order by [index]"
946
                    cursor.execute(sql)
947
                    rows = cursor.fetchall()
948
                    for row in rows:
949
                        attr = SymbolAttr()
950
                        attr.UID = row[0]
951
                        attr.Attribute = row[1]
952
                        attr.DisplayAttribute = row[2]
953
                        attr.AttributeType = row[3]
954
                        attr.Length = row[4]
955
                        self._lineNoProperties.append(attr)
956

    
957
                    res = self._lineNoProperties
958
                # Catch the exception
959
                except Exception as ex:
960
                    print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
961
                                                              sys.exc_info()[-1].tb_lineno))
962
        else:
963
            res = self._lineNoProperties
964

    
965
        return res
966

    
967
    def get_equipment_attributes(self):
968
        """ return equipment attributes """
969

    
970
        from SymbolAttr import SymbolAttr
971

    
972
        res = None
973
        if not hasattr(self, '_equipment_attributes'):
974
            self._equipment_attributes = []
975

    
976
            with self.project.database.connect() as conn:
977
                try:
978
                    # Get a cursor object
979
                    cursor = conn.cursor()
980

    
981
                    sql = "select distinct A.Attribute from SymbolAttribute A join SymbolType B on " \
982
                          "A.SymbolType_UID=B.UID where B.Category = 'Equipment'"
983
                    cursor.execute(sql)
984
                    rows = cursor.fetchall()
985
                    for row in rows:
986
                        attr = SymbolAttr()
987
                        attr.Attribute = row[0]
988
                        self._equipment_attributes.append(attr)
989

    
990
                    res = self._equipment_attributes
991
                # Catch the exception
992
                except Exception as ex:
993
                    print('error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename,
994
                                                               sys.exc_info()[-1].tb_lineno))
995
        else:
996
            res = self._equipment_attributes
997

    
998
        return res
999

    
1000
    '''
1001
        @brief  return line properties
1002
        @author humkyung
1003
        @date   2018.04.09
1004
    '''
1005

    
1006
    def getLinePropertiesByUID(self, UID):
1007
        from SymbolAttr import SymbolAttr
1008

    
1009
        res = []
1010
        if UID in self._lineNoPropertiesUID:
1011
            res = self._lineNoPropertiesUID[UID]
1012
            return res
1013

    
1014
        with self.project.database.connect() as conn:
1015
            try:
1016
                # Get a cursor object
1017
                cursor = conn.cursor()
1018

    
1019
                sql = f"select UID, Name, DisplayName, Type, LimitNumber, [index] from LineProperties where " \
1020
                      f"uid = '{UID}'"
1021
                cursor.execute(sql)
1022
                rows = cursor.fetchall()
1023
                for row in rows:
1024
                    attr = SymbolAttr()
1025
                    attr.UID = row[0]
1026
                    attr.Attribute = row[1]
1027
                    attr.DisplayAttribute = row[2]
1028
                    attr.AttributeType = row[3]
1029
                    attr.Length = row[4]
1030
                    res.append(attr)
1031
                self._lineNoPropertiesUID[UID] = res
1032
            # Catch the exception
1033
            except Exception as ex:
1034
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1035
                                                          sys.exc_info()[-1].tb_lineno))
1036

    
1037
        return res
1038

    
1039
    '''
1040
        @brief  return line types 
1041
        @author humkyung
1042
        @date   2018.06.27
1043
    '''
1044

    
1045
    def getLineTypes(self):
1046
        from LineTypeConditions import LineTypeConditions
1047

    
1048
        res = []
1049
        conn = self.project.database.connect()
1050
        with conn:
1051
            try:
1052
                cursor = conn.cursor() if self.project.database.db_type == 'SQLite' else conn.cursor(as_dict=True)
1053
                sql = "select UID,Name,Type1,Conditions1,Type2,Conditions2 from LineTypes order by Name"
1054
                cursor.execute(sql)
1055
                rows = cursor.fetchall()
1056
                for row in rows:
1057
                    line_type = LineTypeConditions(row['UID'], row['Name'])
1058
                    line_type._conditions[0][0] = row['Type1']
1059
                    line_type._conditions[0][1] = row['Conditions1']
1060
                    line_type._conditions[1][0] = row['Type2']
1061
                    line_type._conditions[1][1] = row['Conditions2']
1062
                    res.append(line_type)
1063
            # Catch the exception
1064
            except Exception as ex:
1065
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1066
                                                          sys.exc_info()[-1].tb_lineno))
1067

    
1068
        return res
1069

    
1070
    '''
1071
        @brief      Insert New Project Info
1072
        @author     Jeongwoo
1073
        @date       2018.04.06
1074
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
1075
    '''
1076

    
1077
    def insertProjectInfo(self, desc, prj_unit, dir):
1078
        prjDatabaseFilePath = self.getPrjDatabasePath()
1079
        conn = sqlite3.connect(prjDatabaseFilePath)
1080
        with conn:
1081
            try:
1082
                folderName = dir.split('/')[-1]
1083
                if folderName:
1084
                    nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
1085
                    sql = "insert or replace into Projects(Name, [Desc], [Unit], Path, CreatedDate, UpdatedDate) values(?, ?, ?, ?, ?, ?)"
1086
                    param = (folderName, desc, prj_unit, dir, nowDate, nowDate)
1087

    
1088
                    cursor = conn.cursor()
1089
                    cursor.execute(sql, param)
1090
                    conn.commit()
1091
                else:
1092
                    print("Empty folder name")
1093
            except Exception as ex:
1094
                # Roll back any change if something goes wrong
1095
                conn.rollback()
1096
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1097
                                                          sys.exc_info()[-1].tb_lineno))
1098

    
1099
    def removeProjectInfo(self, targetProject):
1100
        '''
1101
        @brief      Remove Project Info
1102
        @author     Euisung
1103
        @date       2019.01.28
1104
        '''
1105
        prjDatabaseFilePath = self.getPrjDatabasePath()
1106
        conn = sqlite3.connect(prjDatabaseFilePath)
1107
        with conn:
1108
            try:
1109
                sql = "delete from Projects where Id = '{}'".format(targetProject.id)
1110
                cur = conn.cursor()
1111
                cur.execute(sql)
1112
                conn.commit()
1113
            except Exception as ex:
1114
                # Roll back any change if something goes wrong
1115
                conn.rollback()
1116
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1117
                                                          sys.exc_info()[-1].tb_lineno))
1118

    
1119
    '''
1120
        @brief      update project
1121
        @author     Jeongwoo
1122
        @date       2018.04.06
1123
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
1124
    '''
1125

    
1126
    def updateProjectUpdatedDate(self, project):
1127
        prjDatabaseFilePath = self.getPrjDatabasePath()
1128
        conn = sqlite3.connect(prjDatabaseFilePath)
1129
        with conn:
1130
            try:
1131
                nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
1132
                sql = '''
1133
                    UPDATE Projects
1134
                    SET UpdatedDate = ?,[Desc]=?,[Unit]=? 
1135
                    WHERE Id = ?
1136
                '''
1137
                cur = conn.cursor()
1138
                cur.execute(sql, (nowDate, project.desc, project.prj_unit, project.getId()))
1139

    
1140
                sql = 'insert or replace into DBSettings(Projects_UID, DBTypes_UID, Host, User, Password, FilePath) values(?,(select UID from DBTypes where Name=?),?,?,?,?)'
1141
                cur = conn.cursor()
1142
                cur.execute(sql, (
1143
                    project.getId(), project.database.db_type, project.database.host, project.database.user,
1144
                    project.database.password, project.database.file_path))
1145
                conn.commit()
1146
            except Exception as ex:
1147
                # Roll back any change if something goes wrong
1148
                conn.rollback()
1149
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1150
                                                          sys.exc_info()[-1].tb_lineno))
1151

    
1152
    '''
1153
        @brief  get project list from database
1154
        @history    humkyung 2018.04.18 add only project which's project exists
1155
    '''
1156

    
1157
    def getProjectList(self):
1158
        from Project import Project
1159

    
1160
        projectList = []
1161

    
1162
        conn = sqlite3.connect(self.getPrjDatabasePath())
1163
        with conn:
1164
            conn.row_factory = sqlite3.Row
1165
            cursor = conn.cursor()
1166
            sql = "select a.Id,a.Name,a.[Desc],a.[Unit],a.Path,a.CreatedDate,a.UpdatedDate,\
1167
                (select \
1168
                CASE \
1169
                WHEN b.DBTypes_UID is NULL THEN 'SQLite' \
1170
                ELSE (select Name from DBTypes where UID=b.DBTypes_UID) \
1171
                END \
1172
                ) DBType,b.Host,b.User,b.Password \
1173
                from projects a left join dbsettings b on a.Id=b.Projects_UID order by strftime(a.UpdatedDate) desc"
1174
            try:
1175
                cursor.execute(sql)
1176
                rows = cursor.fetchall()
1177
                for row in rows:
1178
                    if os.path.isdir(row['Path']):  # check if folder exists
1179
                        projectList.append(Project(row))
1180
            except Exception as ex:
1181
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1182
                                                          sys.exc_info()[-1].tb_lineno))
1183

    
1184
        return projectList
1185

    
1186
    '''
1187
        @brief  get sliding window size
1188
        @author humkyung
1189
    '''
1190

    
1191
    def getSlidingWindowSize(self):
1192
        res = [25, 20]
1193
        try:
1194
            configs = self.getConfigs('Sliding Window')
1195
            for config in configs:
1196
                if config.key == 'Width':
1197
                    res[0] = int(config.value)
1198
                elif config.key == 'Height':
1199
                    res[1] = int(config.value)
1200
        # Catch the exception
1201
        except Exception as ex:
1202
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1203
                                                      sys.exc_info()[-1].tb_lineno))
1204

    
1205
        return res
1206

    
1207
    '''
1208
        @brief  get line no configuration
1209
        @author humkyung
1210
        @date   2018.04.16
1211
    '''
1212

    
1213
    def getLineNoConfiguration(self):
1214
        res = None
1215

    
1216
        conn = self.project.database.connect()
1217
        with conn:
1218
            try:
1219
                # Get a cursor object
1220
                cursor = conn.cursor()
1221

    
1222
                delimiter = None
1223
                sql = "select * from configuration where section='Line No' and key='Delimiter"
1224
                cursor.execute(sql)
1225
                rows = cursor.fetchall()
1226
                if len(rows) == 1:
1227
                    delimiter = rows[0][2]
1228

    
1229
                if delimiter is not None:
1230
                    sql = "select * from configuration where section='Line No' and key='Configuration'"
1231
                    cursor.execute(sql)
1232
                    rows = cursor.fetchall()
1233
                    if len(rows) == 1:
1234
                        res = rows[0][2].split(delimiter)
1235
            # Catch the exception
1236
            except Exception as ex:
1237
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1238
                                                          sys.exc_info()[-1].tb_lineno))
1239

    
1240
        return res
1241

    
1242
    '''
1243
        @brief  get area list
1244
        @author humkyung
1245
        @history    euisung     2018.11.20 (0,0),(0,0) process add
1246
    '''
1247

    
1248
    def getAreaList(self):
1249
        from Area import Area
1250

    
1251
        if len(self._areas) == 0:
1252
            conn = self.project.database.connect()
1253
            with conn:
1254
                try:
1255
                    # Get a cursor object
1256
                    cursor = conn.cursor()
1257

    
1258
                    sql = "select * from configuration where section='Area'"
1259
                    cursor.execute(sql)
1260
                    rows = cursor.fetchall()
1261
                    for row in rows:
1262
                        name = row[1]
1263
                        area = Area(name)
1264
                        area.parse(row[2])
1265
                        self._areas.append(area)
1266
                # Catch the exception
1267
                except Exception as ex:
1268
                    print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1269
                                                              sys.exc_info()[-1].tb_lineno))
1270

    
1271
        return self._areas
1272

    
1273
    '''
1274
        @brief  get area of given name
1275
        @author humkyung
1276
        @date   2018.04.07
1277
    '''
1278

    
1279
    def getArea(self, name):
1280
        areas = self.getAreaList()
1281
        matches = [area for area in areas if area.name == name]
1282
        if 1 == len(matches) and matches[0].height is not 0 and matches[0].width is not 0:
1283
            return matches[0]
1284

    
1285
        return None
1286

    
1287
    def getConfigs(self, section, key=None):
1288
        """ get configurations from database """
1289
        res = []
1290

    
1291
        if self._configs is None:
1292
            self._configs = []
1293
            conn = self.project.database.connect()
1294
            with conn:
1295
                try:
1296
                    # Get a cursor object
1297
                    cursor = conn.cursor()
1298

    
1299
                    sql = "select * from configuration"
1300

    
1301
                    cursor.execute(sql)
1302
                    rows = cursor.fetchall()
1303
                    for row in rows:
1304
                        self._configs.append(Config(row[0], row[1], row[2]))
1305
                # Catch the exception
1306
                except Exception as ex:
1307
                    print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1308
                                                              sys.exc_info()[-1].tb_lineno))
1309

    
1310
        if key is not None:
1311
            return [con for con in self._configs if con.section == section and con.key == key]
1312
        else:
1313
            return [con for con in self._configs if con.section == section]
1314

    
1315
        return res
1316

    
1317
    def getAppConfigs(self, section, key=None):
1318
        """
1319
            @brief  get application configurations
1320
            @author humkyung
1321
            @date   2018.11.01
1322
        """
1323

    
1324
        res = []
1325

    
1326
        # Creates or opens a file called mydb with a SQLite3 DB
1327
        dbPath = self.getAppDbPath()
1328
        conn = sqlite3.connect(dbPath)
1329
        with conn:
1330
            try:
1331
                # Get a cursor object
1332
                cursor = conn.cursor()
1333

    
1334
                if key is not None:
1335
                    sql = "select * from configuration where section=? and key=?"
1336
                    param = (section, key)
1337
                else:
1338
                    sql = "select * from configuration where section=?"
1339
                    param = (section,)
1340

    
1341
                cursor.execute(sql, param)
1342
                rows = cursor.fetchall()
1343
                for row in rows:
1344
                    res.append(Config(row[0], row[1], row[2]))
1345
            # Catch the exception
1346
            except Exception as ex:
1347
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1348
                                                          sys.exc_info()[-1].tb_lineno))
1349

    
1350
        return res
1351

    
1352
    '''
1353
        @brief      save configurations
1354
        @author     humkyung
1355
        @date       2018.04.16
1356
        @history    humkyung 2018.07.03 replace ' with " if value has '
1357
                    kyouho 2018.07.09 change query method
1358
    '''
1359

    
1360
    def saveConfigs(self, configs):
1361
        conn = self.project.database.connect()
1362
        with conn:
1363
            try:
1364
                # Get a cursor object
1365
                cursor = conn.cursor()
1366

    
1367
                for config in configs:
1368
                    if type(config) is Config:
1369
                        value = config.value
1370
                        if type(value) is str and "'" in value:
1371
                            value = value.replace("'", "''")
1372

    
1373
                        sql = self.project.database.to_sql(
1374
                            "insert into configuration(Section,[Key],Value) select ?,?,? where not exists(select 1 from configuration where Section=? and [Key]=?)")
1375
                        param = (config.section, config.key, str(value), config.section, config.key)
1376
                        cursor.execute(sql, param)
1377
                        sql = self.project.database.to_sql(
1378
                            "update configuration set Value=? where Section=? and [Key]=?")
1379
                        param = (str(value), config.section, config.key)
1380
                        cursor.execute(sql, param)
1381
                    elif hasattr(config, 'toSql'):
1382
                        sql = config.toSql()
1383
                        if type(sql) is list:
1384
                            for item in sql:
1385
                                if item is not None and 2 == len(item):
1386
                                    cursor.execute(self.project.database.to_sql(item[0]), item[1])
1387
                        else:
1388
                            if sql is not None and 2 == len(sql):
1389
                                cursor.execute(self.project.database.to_sql(sql[0]), sql[1])
1390
                self._configs = None  # reset config table
1391
                conn.commit()
1392
            # Catch the exception
1393
            except Exception as ex:
1394
                # Roll back any change if something goes wrong
1395
                conn.rollback()
1396

    
1397
                from App import App
1398
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1399
                                                              sys.exc_info()[-1].tb_lineno)
1400
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1401

    
1402
    def saveAppConfigs(self, configs):
1403
        """
1404
        @brief      save application configurations
1405
        @author     humkyung
1406
        @date       2018.10.01
1407
        """
1408

    
1409
        # Creates or opens a file called mydb with a SQLite3 DB
1410
        dbPath = self.getAppDbPath()
1411
        conn = sqlite3.connect(dbPath)
1412
        with conn:
1413
            try:
1414
                # Get a cursor object
1415
                cursor = conn.cursor()
1416

    
1417
                for config in configs:
1418
                    value = config.value
1419
                    if type(value) is str and "'" in value:
1420
                        value = value.replace("'", "''")
1421

    
1422
                    sql = "insert or replace into configuration values(?,?,?)"
1423
                    param = (config.section, config.key, value)
1424

    
1425
                    cursor.execute(sql, param)
1426
                conn.commit()
1427
            # Catch the exception
1428
            except Exception as ex:
1429
                # Roll back any change if something goes wrong
1430
                conn.rollback()
1431
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1432
                                                          sys.exc_info()[-1].tb_lineno))
1433

    
1434
    '''
1435
        @brief  delete configurations
1436
        @author humkyung
1437
        @date   2018.06.29
1438
    '''
1439

    
1440
    def deleteConfigs(self, section, key=None):
1441
        conn = self.project.database.connect()
1442
        with conn:
1443
            try:
1444
                # Get a cursor object
1445
                cursor = conn.cursor()
1446

    
1447
                if key is not None:
1448
                    sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
1449
                else:
1450
                    sql = "delete from configuration where section='{}'".format(section)
1451
                cursor.execute(sql)
1452

    
1453
                conn.commit()
1454
            # Catch the exception
1455
            except Exception as ex:
1456
                # Roll back any change if something goes wrong
1457
                conn.rollback()
1458
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1459
                                                          sys.exc_info()[-1].tb_lineno))
1460

    
1461
    def deleteAppConfigs(self, section, key=None):
1462
        """
1463
        @brief  delete application configurations
1464
        @author humkyung
1465
        @date   2018.11.01
1466
        """
1467

    
1468
        # Creates or opens a file called mydb with a SQLite3 DB
1469
        dbPath = self.getAppDbPath()
1470
        conn = sqlite3.connect(dbPath)
1471
        with conn:
1472
            try:
1473
                # Get a cursor object
1474
                cursor = conn.cursor()
1475

    
1476
                if key is not None:
1477
                    sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
1478
                else:
1479
                    sql = "delete from configuration where section='{}'".format(section)
1480
                cursor.execute(sql)
1481

    
1482
                conn.commit()
1483
            # Catch the exception
1484
            except Exception as ex:
1485
                # Roll back any change if something goes wrong
1486
                conn.rollback()
1487
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1488
                                                          sys.exc_info()[-1].tb_lineno))
1489

    
1490
    '''
1491
        @brief      set area list
1492
        @history    humkyung 2018.05.18 round area coordinate and dimension before saving
1493
        @history    euisung  2018.11.20 add self._area reset process
1494
    '''
1495

    
1496
    def setAreaList(self, areas):
1497
        for area in areas:
1498
            matches = [x for x in self._areas if x.name == area.name]
1499
            if 1 == len(matches):
1500
                matches[0].x = area.x
1501
                matches[0].y = area.y
1502
                matches[0].width = area.width
1503
                matches[0].height = area.height
1504
            elif 0 == len(matches):
1505
                self._areas.append(area)
1506

    
1507
        # Creates or opens a file called mydb with a SQLite3 DB
1508
        conn = self.project.database.connect()
1509
        with conn:
1510
            try:
1511
                # Get a cursor object
1512
                cursor = conn.cursor()
1513

    
1514
                for area in self._areas:
1515
                    sql = "insert into configuration select 'Area','{}','({},{}),({},{})' where not exists(select 1 from configuration where Section='Area' and [Key]='{}')".format(
1516
                        area.name, round(area.x), round(area.y), round(area.width), round(area.height), area.name)
1517
                    cursor.execute(sql)
1518
                    sql = "update configuration set Value='({},{}),({},{})' where Section='Area' and [Key]='{}'".format(
1519
                        round(area.x), round(area.y), round(area.width), round(area.height), area.name)
1520
                    cursor.execute(sql)
1521
                conn.commit()
1522
            # Catch the exception
1523
            except Exception as ex:
1524
                # Roll back any change if something goes wrong
1525
                conn.rollback()
1526

    
1527
                from App import App
1528
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1529
                                                              sys.exc_info()[-1].tb_lineno)
1530
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1531
            finally:
1532
                # Close the db connection
1533
                self._areas = []
1534

    
1535
    def getSymbolNameList(self):
1536
        """ get symbol name list """
1537
        symbolNametList = []
1538

    
1539
        conn = self.project.database.connect()
1540
        with conn:
1541
            cursor = conn.cursor()
1542
            sql = 'SELECT * FROM SymbolName'
1543
            try:
1544
                cursor.execute(sql)
1545
                rows = cursor.fetchall()
1546
                for row in rows:
1547
                    symbolNametList.append(row[4])  # Name String
1548
            except Exception as ex:
1549
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1550
                                                          sys.exc_info()[-1].tb_lineno))
1551

    
1552
        return symbolNametList
1553

    
1554
    '''
1555
        @brief      get symbol name list by symbol Type
1556
        @author     Jeongwoo
1557
        @date       18.04.06
1558
        @history    .
1559
    '''
1560

    
1561
    def getSymbolNameListByType(self, type):
1562
        symbolNametList = []
1563

    
1564
        conn = self.project.database.connect()
1565
        with conn:
1566
            cursor = conn.cursor()
1567
            sql = ''
1568
            if type is not None:
1569
                sql = self.project.database.to_sql('SELECT * FROM SymbolName WHERE [Type]=?')
1570
                try:
1571
                    cursor.execute(sql, (type,))
1572
                    rows = cursor.fetchall()
1573
                    for row in rows:
1574
                        symbolNametList.append(row[4])  # Name String
1575
                except Exception as ex:
1576
                    print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1577
                                                              sys.exc_info()[-1].tb_lineno))
1578

    
1579
        return symbolNametList
1580

    
1581
    '''
1582
        @brief  delete added symbol data
1583
    '''
1584

    
1585
    def deleteSymbol(self, fileName):
1586
        ret = False
1587

    
1588
        conn = self.project.database.connect()
1589
        with conn:
1590
            try:
1591
                cursor = conn.cursor()
1592
                sql = self.project.database.to_sql("DELETE FROM Symbol WHERE name = ?")
1593
                try:
1594
                    cursor.execute(sql, (fileName,))
1595
                    conn.commit()
1596
                    ret = True
1597
                except Exception as ex:
1598
                    conn.rollback()
1599
                    print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1600
                                                              sys.exc_info()[-1].tb_lineno))
1601
                    ret = False
1602
            finally:
1603
                self._symbolBase = {}
1604
                return (ret, fileName)
1605

    
1606
    '''
1607
        @brief  get symbol name
1608
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1609
    '''
1610

    
1611
    def getSymbolByQuery(self, fieldName, param):
1612
        ret = None
1613

    
1614
        if fieldName in self._symbolBase:
1615
            if param in self._symbolBase[fieldName]:
1616
                ret = self._symbolBase[fieldName][param]
1617
                return ret
1618
        else:
1619
            self._symbolBase[fieldName] = {}
1620

    
1621
        with self.project.database.connect() as conn:
1622
            cursor = conn.cursor()
1623
            sql = self.project.database.to_sql("""SELECT a.UID,a.Name,b.Type,a.Threshold,a.MinMatchPoint,a.IsDetectOrigin,a.RotationCount,a.OCROption,a.IsContainChild,a.OriginalPoint,a.ConnectionPoint,
1624
                        a.BaseSymbol,a.AdditionalSymbol,a.IsExceptDetect,a.HasInstrumentLabel,a.flip,b.UID FROM Symbol a inner join SymbolType b on a.SymbolType_UID=b.UID WHERE """ + "a." + fieldName + '=?')
1625
            try:
1626
                cursor.execute(sql, (param,))
1627
                rows = cursor.fetchall()
1628
                if rows is not None and len(rows) > 0:
1629
                    symbolTuple = rows[0]
1630
                    ret = symbol.SymbolBase(symbolTuple[1], symbolTuple[2], symbolTuple[3]
1631
                                            , symbolTuple[4], symbolTuple[5], symbolTuple[6], symbolTuple[7],
1632
                                            symbolTuple[8]
1633
                                            , symbolTuple[9], symbolTuple[10], symbolTuple[11], symbolTuple[12],
1634
                                            symbolTuple[13], symbolTuple[14], symbolTuple[0], iType=symbolTuple[16],
1635
                                            detectFlip=symbolTuple[15])  ## uid is last item
1636
                    self._symbolBase[fieldName][param] = ret
1637
            except Exception as ex:
1638
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1639
                                                          sys.exc_info()[-1].tb_lineno))
1640

    
1641
        return ret
1642

    
1643
    '''
1644
        @brief  get symbol name list
1645
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1646
    '''
1647

    
1648
    def getSymbolListByType(self, field_name=None, param=None):
1649
        ret = []
1650

    
1651
        conn = self.project.database.connect()
1652
        with conn:
1653
            cursor = conn.cursor()
1654
            if field_name is not None and param is not None:
1655
                sql = """SELECT a.UID,a.Name,b.Type,a.Threshold,a.MinMatchPoint,a.IsDetectOrigin,a.RotationCount,a.OCROption,a.IsContainChild,a.OriginalPoint,a.ConnectionPoint,
1656
                        a.BaseSymbol,a.AdditionalSymbol,a.IsExceptDetect,a.HasInstrumentLabel,a.flip,b.UID
1657
                        FROM Symbol a inner join SymbolType b on a.SymbolType_UID=b.UID WHERE SymbolType_UID = (select UID from SymbolType where {}={})""".format(
1658
                    field_name, self.project.database.place_holder)
1659
            else:
1660
                sql = """SELECT a.UID,a.Name,b.Type,a.Threshold,a.MinMatchPoint,a.IsDetectOrigin,a.RotationCount,a.OCROption,a.IsContainChild,a.OriginalPoint,a.ConnectionPoint,
1661
                        a.BaseSymbol,a.AdditionalSymbol,a.IsExceptDetect,a.HasInstrumentLabel,a.flip FROM Symbol a inner join SymbolType b on a.SymbolType_UID=b.UID"""
1662
            try:
1663
                cursor.execute(sql, (param,)) if param is not None else cursor.execute(sql)
1664
                rows = cursor.fetchall()
1665
                if rows is not None and len(rows) > 0:
1666
                    for symbolTuple in rows:
1667
                        sym = symbol.SymbolBase(symbolTuple[1], symbolTuple[2], symbolTuple[3], symbolTuple[4]
1668
                                                , symbolTuple[5], symbolTuple[6], symbolTuple[7], symbolTuple[8],
1669
                                                symbolTuple[9]
1670
                                                , symbolTuple[10], symbolTuple[11], symbolTuple[12], symbolTuple[13],
1671
                                                symbolTuple[14], symbolTuple[0], iType=symbolTuple[16],
1672
                                                detectFlip=symbolTuple[15])  ## uid is last item
1673
                        ret.append(sym)
1674
            except Exception as ex:
1675
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1676
                                                          sys.exc_info()[-1].tb_lineno))
1677

    
1678
        return ret
1679

    
1680
    '''
1681
        @brief      get NominalDiameter
1682
        @author     humkyung
1683
        @date       2018.04.20
1684
        @history    humkyung 2018.04.24 read MetricStr column and set size unit
1685
                    kyouho 2018.07.04 forCheckLineNumber get only inch or metric
1686
                    kyouho 2018.07.16 edit query order by code
1687
    '''
1688

    
1689
    def getNomialPipeSizeData(self, forCheckLineNumber=False, orderStr="MetricStr"):
1690
        res = []
1691
        configs = self.getConfigs('Line No', 'Size Unit')
1692
        sizeUnit = configs[0].value if 1 == len(configs) else 'Metric'
1693

    
1694
        conn = self.project.database.connect()
1695
        with conn:
1696
            try:
1697
                # Get a cursor object
1698
                cursor = conn.cursor()
1699

    
1700
                sql = "select UID,Code,Metric,Inch,InchStr,AllowableInchStr,MetricStr,AllowableMetricStr from NominalDiameter ORDER BY {} DESC".format(
1701
                    orderStr)
1702
                cursor.execute(sql)
1703
                rows = cursor.fetchall()
1704
                for row in rows:
1705
                    pipeSize = NominalPipeSize(row[0], row[1], float(row[2]) if row[2] else None,
1706
                                               float(row[3]) if row[3] else None, row[4], row[5], row[6], row[7])
1707
                    pipeSize.sizeUnit = sizeUnit
1708
                    if forCheckLineNumber:
1709
                        if sizeUnit == 'Inch' and pipeSize.inchStr:
1710
                            res.append(pipeSize.inchStr)
1711
                        elif sizeUnit == 'Metric' and pipeSize.metricStr:
1712
                            res.append(pipeSize.metricStr)
1713
                    else:
1714
                        res.append(pipeSize)
1715
            # Catch the exception
1716
            except Exception as ex:
1717
                from App import App
1718
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1719
                                                              sys.exc_info()[-1].tb_lineno)
1720
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1721

    
1722
        return res
1723

    
1724
    '''
1725
        @brief      insert NominalDiameter table
1726
        @author     kyouho
1727
        @date       2018.07.16
1728
    '''
1729

    
1730
    def insertNomialPipeSize(self, pipeSizes):
1731
        conn = self.project.database.connect()
1732
        with conn:
1733
            try:
1734
                # Get a cursor object
1735
                cursor = conn.cursor()
1736
                for pipeSize in pipeSizes:
1737
                    sql = pipeSize.toSql()
1738
                    if type(sql) is list and len(sql) == 1:
1739
                        cursor.execute(self.project.database.to_sql(sql[0][0]), sql[0][1])
1740

    
1741
                conn.commit()
1742
            # Catch the exception
1743
            except Exception as ex:
1744
                # Roll back any change if something goes wrong
1745
                conn.rollback()
1746

    
1747
                from App import App
1748
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1749
                                                              sys.exc_info()[-1].tb_lineno)
1750
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1751

    
1752
    '''
1753
        @brief      delete NominalDiameter table
1754
        @author     kyouho
1755
        @date       2018.07.16
1756
    '''
1757

    
1758
    def deleteNomialPipeSize(self):
1759
        conn = self.project.database.connect()
1760
        with conn:
1761
            cursor = conn.cursor()
1762
            sql = "DELETE FROM NominalDiameter"
1763
            try:
1764
                cursor.execute(sql)
1765
                conn.commit()
1766
            except Exception as ex:
1767
                conn.rollback()
1768
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1769
                                                          sys.exc_info()[-1].tb_lineno))
1770

    
1771
    '''
1772
        @brief      convert inch to metric
1773
        @author     kyouho
1774
        @date       2018.07.09
1775
    '''
1776

    
1777
    def convertInchToMetric(self, inch):
1778
        result = ''
1779
        conn = self.project.database.connect()
1780
        with conn:
1781
            try:
1782
                # Get a cursor object
1783
                cursor = conn.cursor()
1784

    
1785
                sql = "select MetricStr from NominalDiameter WHERE InchStr = ?"
1786
                param = (inch,)
1787
                cursor.execute(sql, param)
1788
                rows = cursor.fetchall()
1789

    
1790
                if rows:
1791
                    result = rows[0][0]
1792
                # Catch the exception
1793
            except Exception as ex:
1794
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1795
                                                          sys.exc_info()[-1].tb_lineno))
1796

    
1797
        return result
1798

    
1799
    '''
1800
        @brief      get Color MaxUID
1801
        @author     kyouho
1802
        @date       2018.07.03
1803
    '''
1804

    
1805
    def getMaxColorUID(self):
1806
        result = 0
1807

    
1808
        conn = self.project.database.connect()
1809
        with conn:
1810
            try:
1811
                # Get a cursor object
1812
                cursor = conn.cursor()
1813

    
1814
                sql = "select MAX(UID) from Colors"
1815
                cursor.execute(sql)
1816
                rows = cursor.fetchall()
1817

    
1818
                result = rows[0][0]
1819
                # Catch the exception
1820
            except Exception as ex:
1821
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1822
                                                          sys.exc_info()[-1].tb_lineno))
1823

    
1824
        return result
1825

    
1826
    '''
1827
        @brief      insert Color property
1828
        @author     kyouho
1829
        @date       2018.07.09
1830
    '''
1831

    
1832
    def setPropertyColor(self, _color):
1833
        conn = self.project.database.connect()
1834
        with conn:
1835
            try:
1836
                # Get a cursor object
1837
                cursor = conn.cursor()
1838
                sql = "INSERT INTO Colors(UID, RED, GREEN, BLUE, PROPERTY, VALUE) VALUES(?,?,?,?,?,?)"
1839
                param = (_color.index, _color.red, _color.green, _color.blue, _color._property, _color.value)
1840
                cursor.execute(sql, param)
1841
                conn.commit()
1842
            # Catch the exception
1843
            except Exception as ex:
1844
                # Roll back any change if something goes wrong
1845
                conn.rollback()
1846
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1847
                                                          sys.exc_info()[-1].tb_lineno))
1848

    
1849
    '''
1850
        @brief      delete Color property
1851
        @author     kyouho
1852
        @date       2018.07.09
1853
    '''
1854

    
1855
    def deletePropertyColor(self, property):
1856
        conn = self.project.database.connect()
1857
        with conn:
1858
            try:
1859
                # Get a cursor object
1860
                cursor = conn.cursor()
1861

    
1862
                sql = "DELETE FROM Colors WHERE PROPERTY = '{}'".format(property)
1863
                cursor.execute(sql)
1864
                conn.commit()
1865
                # Catch the exception
1866
            except Exception as ex:
1867
                # Roll back any change if something goes wrong
1868
                conn.rollback()
1869
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1870
                                                          sys.exc_info()[-1].tb_lineno))
1871

    
1872
    '''
1873
        @brief      get Fluid Code
1874
        @author     kyouho
1875
        @date       2018.07.03
1876
        @history    kyouho 2018.07.04 kyouho 2018.07.04 forCheckLineNumber get only code
1877
    '''
1878

    
1879
    def getFluidCodeData(self, forCheckLineNumber=False):
1880
        from FluidCodeData import FluidCodeData
1881
        result = []
1882

    
1883
        conn = self.project.database.connect()
1884
        with conn:
1885
            try:
1886
                # Get a cursor object
1887
                cursor = conn.cursor()
1888

    
1889
                sql = 'select uid, code, description from FluidCode order by length(code) DESC'
1890
                cursor.execute(sql)
1891
                rows = cursor.fetchall()
1892
                for row in rows:
1893
                    data = FluidCodeData(row[0], row[1], row[2])
1894
                    if forCheckLineNumber:
1895
                        result.append(data.code)
1896
                    else:
1897
                        result.append(data)
1898
                # Catch the exception
1899
            except Exception as ex:
1900
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1901
                                                          sys.exc_info()[-1].tb_lineno))
1902

    
1903
        return result
1904

    
1905
    '''
1906
        @brief      get Symbol Attribute
1907
        @author     kyouho
1908
        @date       2018.07.18
1909
    '''
1910

    
1911
    def checkAttribute(self, attr):
1912
        conn = self.project.database.connect()
1913
        with conn:
1914
            try:
1915
                # Get a cursor object
1916
                cursor = conn.cursor()
1917

    
1918
                sql = 'select UID from SymbolAttribute where UID = ?'
1919
                param = (attr,)
1920
                cursor.execute(sql, param)
1921
                rows = cursor.fetchall()
1922
                if len(rows):
1923
                    return True
1924
                else:
1925
                    return False
1926
                # Catch the exception
1927
            except Exception as ex:
1928
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1929
                                                          sys.exc_info()[-1].tb_lineno))
1930

    
1931
        return False
1932

    
1933
    def read_drawing_shape(self, drawing):
1934
        """read drawing shape"""
1935

    
1936
        res = None
1937

    
1938
        with self.project.database.connect() as conn:
1939
            try:
1940
                # Get a cursor object
1941
                cursor = conn.cursor()
1942

    
1943
                sql = f"select Image from Drawings where UID='{drawing}'"
1944
                cursor.execute(sql)
1945
                records = cursor.fetchall()
1946
                for record in records:
1947
                    res = record[0]
1948
                    break
1949

    
1950
            # Catch the exception
1951
            except Exception as ex:
1952
                from App import App
1953
                # Roll back any change if something goes wrong
1954
                conn.rollback()
1955

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

    
1960
        return res
1961

    
1962
    def read_symbol_shape(self, symbol_name):
1963
        """read symbol shape(image and svg)"""
1964

    
1965
        res = (None, None)
1966

    
1967
        with self.project.database.connect() as conn:
1968
            try:
1969
                # Get a cursor object
1970
                cursor = conn.cursor()
1971

    
1972
                sql = f"select Image, Svg from Symbol where Name='{symbol_name}'"
1973
                cursor.execute(sql)
1974
                records = cursor.fetchall()
1975
                for record in records:
1976
                    res = (record[0], record[1])
1977
                    break
1978

    
1979
            # Catch the exception
1980
            except Exception as ex:
1981
                from App import App
1982
                # Roll back any change if something goes wrong
1983
                conn.rollback()
1984

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

    
1989
        return res
1990

    
1991

    
1992
    def update_symbol_shape(self, symbol_name, image_file, svg_file, image_display_file):
1993
        """update symbol shape"""
1994

    
1995
        with self.project.database.connect() as conn:
1996
            try:
1997
                # Get a cursor object
1998
                cursor = conn.cursor()
1999

    
2000
                cols = []
2001
                params = []
2002

    
2003
                image_blob_data = None
2004
                if image_file and os.path.isfile(image_file):
2005
                    with open(image_file, 'rb') as file:
2006
                        image_blob_data = file.read()
2007
                    cols.append('Image=?')
2008
                    params.append(image_blob_data)
2009

    
2010
                svg_blob_data = None
2011
                if svg_file and os.path.isfile(svg_file):
2012
                    with open(svg_file, 'rb') as file:
2013
                        svg_blob_data = file.read()
2014
                    cols.append('Svg=?')
2015
                    params.append(svg_blob_data)
2016

    
2017
                image_display_blob_data = None
2018
                if image_file and image_display_file and os.path.isfile(image_display_file):
2019
                    with open(image_file, 'rb') as file:
2020
                        image_display_blob_data = file.read()
2021
                    cols.append('Image_display=?')
2022
                    params.append(image_display_blob_data)
2023

    
2024
                sql = f"update Symbol set {','.join(cols)} where Name='{symbol_name}'"
2025
                # Convert data into tuple format
2026
                cursor.execute(self.project.database.to_sql(sql), tuple(params))
2027
                conn.commit()
2028

    
2029
            # Catch the exception
2030
            except Exception as ex:
2031
                from App import App
2032
                # Roll back any change if something goes wrong
2033
                conn.rollback()
2034

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

    
2039
    def getCustomTables(self):
2040
        ''' get custom code tables '''
2041

    
2042
        with self.project.database.connect() as conn:
2043
            try:
2044
                # Get a cursor object
2045
                cursor = conn.cursor()
2046

    
2047
                sql = self.project.database.to_sql('select UID, Name, Desciption from CustomTables')
2048
                cursor.execute(sql)
2049
                rows = cursor.fetchall()
2050
                for row in rows:
2051
                    attr = SymbolAttr()
2052
                    attr.UID = uuid.UUID(row[0])
2053
                    attr.Attribute = row[1]
2054
                    attr.DisplayAttribute = row[2]
2055
                    attr.AttributeType = row[3]
2056
                    attr.AttrAt = row[4]
2057
                    attr.Expression = row[5]
2058
                    attr.Target = row[7]
2059
                    attr.IsProp = row[8]
2060
                    attr.Codes = CodeTable.instance('SymbolAttributeCodeTable', row[0])
2061
                    result.append(attr)
2062
            # Catch the exception
2063
            except Exception as ex:
2064
                from App import App
2065
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2066
                                                              sys.exc_info()[-1].tb_lineno)
2067
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2068

    
2069
        return result
2070

    
2071
    '''
2072
        @brief      get Symbol Attribute
2073
        @author     kyouho
2074
        @date       2018.07.18
2075
        @history    humkyung 2018.10.13 load expression
2076
    '''
2077
    def getSymbolAttribute(self, _type):
2078
        import uuid
2079
        from SymbolAttr import SymbolAttr
2080
        from CodeTables import CodeTable
2081

    
2082
        result = []
2083

    
2084
        if self._attributeByType and _type in self._attributeByType:
2085
            new_attr_without_any_binding_data = []
2086
            for attr_old in self._attributeByType[_type]:
2087
                attr = SymbolAttr()
2088
                attr.UID = attr_old.UID
2089
                attr.Attribute = attr_old.Attribute
2090
                attr.DisplayAttribute = attr_old.DisplayAttribute
2091
                attr.AttributeType = attr_old.AttributeType
2092
                attr.AttrAt = attr_old.AttrAt
2093
                attr.Expression = attr_old.Expression
2094
                attr.Target = attr_old.Target
2095
                attr.IsProp = attr_old.IsProp
2096
                attr.Codes = attr_old.Codes
2097
                new_attr_without_any_binding_data.append(attr)
2098
            self._attributeByType[_type] = new_attr_without_any_binding_data
2099

    
2100
            return self._attributeByType[_type]
2101

    
2102
        with self.project.database.connect() as conn:
2103
            try:
2104
                # Get a cursor object
2105
                cursor = conn.cursor()
2106

    
2107
                sql = self.project.database.to_sql(
2108
                    'select a.UID, a.Attribute, a.DisplayAttribute, a.AttributeType, a.[AttrAt], a.[Expression], a.[index], a.[Target], a.[Property] from SymbolAttribute a inner join SymbolType t on a.SymbolType_UID = t.UID and t.type = ? order by a.[index]')
2109
                param = (_type,)
2110
                cursor.execute(sql, param)
2111
                rows = cursor.fetchall()
2112
                for row in rows:
2113
                    attr = SymbolAttr()
2114
                    attr.UID = uuid.UUID(row[0])
2115
                    attr.Attribute = row[1]
2116
                    attr.DisplayAttribute = row[2]
2117
                    attr.AttributeType = row[3]
2118
                    attr.AttrAt = row[4]
2119
                    attr.Expression = row[5]
2120
                    attr.Target = row[7]
2121
                    attr.IsProp = row[8]
2122
                    attr.Codes = CodeTable.instance('SymbolAttributeCodeTable', row[0])
2123
                    result.append(attr)
2124
            # Catch the exception
2125
            except Exception as ex:
2126
                from App import App
2127
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2128
                                                              sys.exc_info()[-1].tb_lineno)
2129
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2130

    
2131
        self._attributeByType[_type] = result
2132
        return result
2133

    
2134
    '''
2135
        @brief      get Symbol Attribute by UID
2136
        @author     kyouho
2137
        @date       2018.08.17
2138
        @history    humkyung 2018.10.13 load expression
2139
    '''
2140

    
2141
    def getSymbolAttributeByUID(self, UID):
2142
        from SymbolAttr import SymbolAttr
2143

    
2144
        res = None
2145

    
2146
        conn = self.project.database.connect()
2147
        with conn:
2148
            try:
2149
                # Get a cursor object
2150
                cursor = conn.cursor()
2151

    
2152
                sql = 'select Attribute, DisplayAttribute, AttributeType, AttrAt, Expression, Target, Property from SymbolAttribute where uid = "{}"'.format(
2153
                    UID)
2154
                cursor.execute(sql)
2155
                rows = cursor.fetchall()
2156
                if len(rows):
2157
                    res = SymbolAttr()
2158
                    res.UID = UID
2159
                    res.Attribute = rows[0][0]
2160
                    res.DisplayAttribute = rows[0][1]
2161
                    res.AttributeType = rows[0][2]
2162
                    res.AttrAt = rows[0][3]
2163
                    res.Expression = rows[0][4]
2164
                    res.Target = rows[0][5]
2165
                    res.IsProp = row[0][6]
2166
                # Catch the exception
2167
            except Exception as ex:
2168
                from App import App
2169
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2170
                                                              sys.exc_info()[-1].tb_lineno)
2171
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2172

    
2173
        return res
2174

    
2175
    '''
2176
        @brief      save symbol attributes
2177
        @author     humkyung
2178
        @date       2018.08.14
2179
        @history    humkyung 2018.10.13 save expression
2180
    '''
2181
    def saveSymbolAttributes(self, type, attrs, type_str):
2182
        from CodeTables import CodeTable
2183

    
2184
        conn = self.project.database.connect()
2185
        with conn:
2186
            try:
2187
                # Get a cursor object
2188
                cursor = conn.cursor()
2189

    
2190
                # delete symbol attribute code table data
2191
                origin_attrs = self.getSymbolAttribute(type_str)
2192
                for origin_attr in origin_attrs:
2193
                    '''
2194
                    # delete symbol attribute code table data for deleted symbol attribute, and backup not edited attribute code table data
2195
                    remain = False
2196
                    for attr in attrs:
2197
                        if str(origin_attr.UID) == attr[0]:
2198
                            remain = True
2199
                            break
2200
                    if remain and attr[-1] and type(attr[-1][0][3]) is list: # this means not edited and need backup
2201
                        attr[-1] = self.getCodeTable('SymbolAttributeCodeTable', forCheckLineNumber=False, symbol_attribute_uid=origin_attr.UID)
2202
                    '''
2203
                    
2204
                    sql = "delete from SymbolAttributeCodeTable where SymbolAttribute_UID = '{}'".format(origin_attr.UID)
2205
                    cursor.execute(sql)
2206
                # up to here
2207

    
2208
                # update symbol attribute
2209
                sql = self.project.database.to_sql('delete from SymbolAttribute where SymbolType_UID = ?')
2210
                param = (type,)
2211
                cursor.execute(sql, param)
2212

    
2213
                for attr in attrs:
2214
                    sql = self.project.database.to_sql(
2215
                        'insert into SymbolAttribute(UID, SymbolType_UID, Attribute, DisplayAttribute, AttributeType, '
2216
                        'AttrAt, Expression, Target, [index], [Property]) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')
2217
                    attr.insert(1, type)
2218
                    cursor.execute(sql, tuple(attr[:-1]))
2219
                # up to here
2220

    
2221
                # update symbol attribute code table data
2222
                for attr in attrs:
2223
                    if attr[-1]:
2224
                        for code in attr[-1]:
2225
                            sql = self.project.database.to_sql( \
2226
                                "insert into SymbolAttributeCodeTable(UID, Code, Description, Allowables, SymbolAttribute_UID) VALUES(?,?,?,?,?)")
2227
                            param = (code[0], code[1], code[2], ','.join(code[3]), attr[0])
2228
                            cursor.execute(sql, param)
2229
                # up to here
2230

    
2231
                conn.commit()
2232

    
2233
                if hasattr(self, '_equipment_attributes'):
2234
                    del self._equipment_attributes
2235

    
2236
                if hasattr(self, '_valve_attributes'):
2237
                    del self._valve_attributes
2238

    
2239
                if hasattr(self, '_inst_attributes'):
2240
                    del self._inst_attributes
2241

    
2242
                if hasattr(self, '_note_attributes'):
2243
                    del self._note_attributes
2244
            # Catch the exception
2245
            except Exception as ex:
2246
                # Roll back any change if something goes wrong
2247
                conn.rollback()
2248

    
2249
                from App import App
2250
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2251
                                                              sys.exc_info()[-1].tb_lineno)
2252
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2253

    
2254
            self._attributeByType = {}
2255
            CodeTable.clearTables()
2256

    
2257
    def saveCustomCodes(self, tables):
2258
        ''' save custom code tables and codes '''
2259

    
2260
        from CodeTables import CodeTable
2261

    
2262
        conn = self.project.database.connect()
2263
        with conn:
2264
            try:
2265
                # Get a cursor object
2266
                cursor = conn.cursor()
2267

    
2268
                # delete custom codes and tables
2269
                sql = "delete from CustomCodes"
2270
                cursor.execute(sql)
2271

    
2272
                sql = "delete from CustomTables"
2273
                cursor.execute(sql)
2274
                # up to here
2275

    
2276
                # update symbol attribute code table data
2277
                for table in tables:
2278
                    sql = self.project.database.to_sql("insert into CustomTables (UID, Name, Description) VALUES(?,?,?)")
2279
                    param = (table[0], table[1], table[2])
2280
                    cursor.execute(sql, param)
2281

    
2282
                    for code in table[3]:
2283
                        sql = self.project.database.to_sql( \
2284
                            "insert into CustomCodes(UID, Code, Description, Allowables, Table_UID) VALUES(?,?,?,?,?)")
2285
                        param = (code[0], code[1], code[2], ','.join(code[3]), table[0])
2286
                        cursor.execute(sql, param)
2287
                # up to here
2288

    
2289
                conn.commit()
2290

    
2291
            # Catch the exception
2292
            except Exception as ex:
2293
                # Roll back any change if something goes wrong
2294
                conn.rollback()
2295

    
2296
                from App import App
2297
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2298
                                                              sys.exc_info()[-1].tb_lineno)
2299
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2300

    
2301
            CodeTable.clearTables()
2302

    
2303
    '''
2304
        @brief      save symbol attributes
2305
        @author     humkyung
2306
        @date       2018.08.14
2307
    '''
2308
    def saveLineAttributes(self, attrs):
2309
        conn = self.project.database.connect()
2310
        with conn:
2311
            try:
2312
                # Get a cursor object
2313
                cursor = conn.cursor()
2314

    
2315
                sql = 'delete from LineProperties'
2316
                cursor.execute(sql)
2317

    
2318
                for attr in attrs:
2319
                    sql = self.project.database.to_sql(
2320
                        'insert into LineProperties(UID, Name, DisplayName, Type, LimitNumber, [index]) values(?, ?, ?, ?, ?, ?)')
2321
                    cursor.execute(sql, tuple(attr))
2322

    
2323
                conn.commit()
2324

    
2325
                self._lineNoProperties = None
2326
                self._lineNoPropertiesUID = {}
2327
            # Catch the exception
2328
            except Exception as ex:
2329
                # Roll back any change if something goes wrong
2330
                conn.rollback()
2331

    
2332
                from App import App
2333
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2334
                                                              sys.exc_info()[-1].tb_lineno)
2335
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2336

    
2337
    '''
2338
        @brief      get symbol type id
2339
        @author     kyouho
2340
        @date       2018.08.17
2341
    '''
2342

    
2343
    def getSymbolTypeId(self, symbolType):
2344
        result = []
2345

    
2346
        conn = self.project.database.connect()
2347
        with conn:
2348
            try:
2349
                # Get a cursor object
2350
                cursor = conn.cursor()
2351

    
2352
                sql = self.project.database.to_sql('select UID from SymbolType where Type = ?')
2353
                param = (symbolType,)
2354
                cursor.execute(sql, param)
2355
                rows = cursor.fetchall()
2356

    
2357
                if len(rows):
2358
                    result = rows[0][0]
2359
                else:
2360
                    result = -1
2361
                # Catch the exception
2362
            except Exception as ex:
2363
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2364
                                                          sys.exc_info()[-1].tb_lineno))
2365

    
2366
        return result
2367

    
2368
    '''
2369
        @brief      get Code Table Data
2370
        @author     kyouho
2371
        @date       2018.07.10
2372
    '''
2373

    
2374
    def getCodeTable(self, property, forCheckLineNumber=False, symbol_attribute_uid=None, custom_table_uid=None):
2375
        result = []
2376
        conn = self.project.database.connect()
2377
        with conn:
2378
            try:
2379
                # Get a cursor object
2380
                cursor = conn.cursor()
2381

    
2382
                if property.upper().replace(' ', '') == "NOMINALDIAMETER" and forCheckLineNumber:
2383
                    sql = 'select InchStr, MetricStr from [{}] order by Metric ASC'.format(property)
2384
                    cursor.execute(sql)
2385
                    rows = cursor.fetchall()
2386
                    for index in range(2):
2387
                        for row in rows:
2388
                            if row[index] != '' and result.count(row[index].replace("'", '"')) == 0:
2389
                                result.append(row[index].replace("'", '"'))
2390
                else:
2391
                    """
2392
                    sql = "select name from sqlite_master where type='table'"# AND name={}".format(property)
2393
                    cursor.execute(sql)
2394
                    rows = cursor.fetchall()
2395
                    if property.upper() in [name[0].upper() for name in rows]:
2396
                    """
2397
                    if not symbol_attribute_uid and not custom_table_uid:
2398
                        sql = 'select uid, code, description, Allowables from [{}] order by code DESC'.format(property)
2399
                    elif symbol_attribute_uid and not custom_table_uid:
2400
                        sql = "select uid, code, description, Allowables from [{}] where SymbolAttribute_UID='{}' order by code DESC".format(property, symbol_attribute_uid)
2401
                    elif not symbol_attribute_uid and custom_table_uid:
2402
                        sql = "select uid, code, description, Allowables from [{}] where Table_UID='{}' order by code DESC".format(property, custom_table_uid)
2403
                    cursor.execute(sql)
2404
                    rows = cursor.fetchall()
2405
                    for row in rows:
2406
                        if forCheckLineNumber:
2407
                            data = row[1]
2408
                        else:
2409
                            data = (row[0], row[1], row[2], row[3])
2410
                        result.append(data)
2411
                    # else:
2412
                    #    result = None
2413
            # Catch the exception
2414
            except Exception as ex:
2415
                from App import App
2416
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2417
                                                              sys.exc_info()[-1].tb_lineno)
2418
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2419

    
2420
        return result
2421

    
2422
    def get_components(self, drawing):
2423
        """ get components in given drawing """
2424

    
2425
        with self.project.database.connect() as conn:
2426
            try:
2427
                # Get a cursor object
2428
                cursor = conn.cursor() if self.project.database.db_type == 'SQLite' else conn.cursor(as_dict=True)
2429

    
2430
                sql = "select a.*,b.Name,b.SymbolType_UID,b.[Type],b.OriginalPoint,b.ConnectionPoint,b.BaseSymbol," \
2431
                      "b.AdditionalSymbol,b.HasInstrumentLabel,b.Flip as DetectFlip from Components a " \
2432
                      "join Symbol b on a.Symbol_UID=b.UID where a.Drawings_UID='{}'".format(drawing)
2433
                cursor.execute(sql)
2434
                return cursor.fetchall()
2435
                # Catch the exception
2436
            except Exception as ex:
2437
                from App import App
2438
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2439
                                                              sys.exc_info()[-1].tb_lineno)
2440
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2441

    
2442
    def get_opcs(self):
2443
        """ get opc in project """
2444
        with self.project.database.connect() as conn:
2445
            try:
2446
                # Get a cursor object
2447
                cursor = conn.cursor() if self.project.database.db_type == 'SQLite' else conn.cursor(as_dict=True)
2448

    
2449
                sql = "select (select Name from Drawings where UID=a.Drawings_UID) as Drawing," \
2450
                      "(select Value from Components where UID=a.Owner) as [Line No]," \
2451
                      "UID as OPC from Components a " \
2452
                      "where Symbol_UID in (select UID from Symbol where SymbolType_UID in " \
2453
                      "(select UID from SymbolType where Type='Instrument OPC''s' or Type='Piping OPC''s'))"
2454
                cursor.execute(sql)
2455
                return cursor.fetchall()
2456
                # Catch the exception
2457
            except Exception as ex:
2458
                from App import App
2459
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2460
                                                              sys.exc_info()[-1].tb_lineno)
2461
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2462

    
2463
    def get_opc_relations(self):
2464
        """ get opc relations """
2465
        conn = self.project.database.connect()
2466
        with conn:
2467
            try:
2468
                # Get a cursor object
2469
                cursor = conn.cursor() if self.project.database.db_type == 'SQLite' else conn.cursor(as_dict=True)
2470

    
2471
                sql = "select (select Name from Drawings where UID=a.From_Drawings_UID) as From_Drawing,\
2472
                a.From_LineNo_UID as From_LineNo,\
2473
                a.From_OPC_UID,\
2474
                (select Name from Drawings where UID=a.To_Drawings_UID) as To_Drawing,\
2475
                a.To_LineNo_UID as To_LineNo,\
2476
                a.To_OPC_UID \
2477
                from OPCRelations a"
2478
                cursor.execute(sql)
2479
                return cursor.fetchall()
2480
                # Catch the exception
2481
            except Exception as ex:
2482
                from App import App
2483
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2484
                                                              sys.exc_info()[-1].tb_lineno)
2485
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2486

    
2487
    def save_opc_relations(self, opcs):
2488
        """ save opc relations """
2489
        conn = self.project.database.connect()
2490
        with conn:
2491
            try:
2492
                # Get a cursor object
2493
                cursor = conn.cursor()
2494
                sql = 'delete from OPCRelations'
2495
                cursor.execute(sql)
2496

    
2497
                for opc in opcs:
2498
                    sql = 'insert into OPCRelations(From_Drawings_UID,From_LineNo_UID,From_OPC_UID,To_Drawings_UID,To_LineNo_UID,To_OPC_UID) \
2499
                        values({},{},{},{},{},{})'.format(
2500
                        "(select UID from Drawings where Name='{}')".format(opc[0]),
2501
                        "'{}'".format(opc[1]) if opc[1] else 'null',
2502
                        "'{}'".format(opc[2]) if opc[2] else 'null',
2503
                        "(select UID from Drawings where Name='{}')".format(opc[3]) if opc[3] else 'null',
2504
                        "'{}'".format(opc[4]) if opc[4] else 'null',
2505
                        "'{}'".format(opc[5]) if opc[5] else 'null')
2506
                    cursor.execute(sql)
2507

    
2508
                conn.commit()
2509
            # Catch the exception
2510
            except Exception as ex:
2511
                conn.rollback()
2512

    
2513
                from App import App
2514
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2515
                                                              sys.exc_info()[-1].tb_lineno)
2516
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2517

    
2518
    def get_component_connectors(self, component):
2519
        """ get connectors of given component """
2520
        if self._connecterss and component in self._connecterss:
2521
            return self._connecterss[component]
2522

    
2523
        conn = self.project.database.connect()
2524
        with conn:
2525
            try:
2526
                # Get a cursor object
2527
                cursor = conn.cursor() if self.project.database.db_type == 'SQLite' else conn.cursor(as_dict=True)
2528

    
2529
                sql = f"select a.* from Points a join Components b on a.Components_UID=b.[UID] where Drawings_UID=" \
2530
                      f"'{self.activeDrawing.UID}' order by Components_UID, [Index]"
2531
                cursor.execute(sql)
2532

    
2533
                pre = ''
2534
                rows = cursor.fetchall()
2535
                for row in rows:
2536
                    if pre != row['Components_UID']:
2537
                        if pre != '':
2538
                            self._connecterss[pre] = compo
2539
                        pre = row['Components_UID']
2540
                        compo = []
2541
                        compo.append(row)
2542
                    else:
2543
                        compo.append(row)
2544

    
2545
                return self._connecterss[component] if component in self._connecterss else []
2546
                # Catch the exception
2547
            except Exception as ex:
2548
                from App import App
2549
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2550
                                                              sys.exc_info()[-1].tb_lineno)
2551
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2552

    
2553
    def get_component_associations(self, component):
2554
        """ get associations of given component """
2555
        if self._associationss and component in self._associationss:
2556
            return self._associationss[component]
2557
        elif self._associationss:
2558
            return []
2559

    
2560
        conn = self.project.database.connect()
2561
        with conn:
2562
            try:
2563
                # Get a cursor object
2564
                cursor = conn.cursor() if self.project.database.db_type == 'SQLite' else conn.cursor(as_dict=True)
2565

    
2566
                # sql = "select * from Associations where Components_UID='{}'".format(component)
2567
                sql = "select a.* from Associations a \
2568
                            join Components b on a.Components_UID=b.[UID] where Drawings_UID='{}' order by Components_UID".format(
2569
                    self.activeDrawing.UID)
2570
                cursor.execute(sql)
2571

    
2572
                pre = ''
2573
                rows = cursor.fetchall()
2574
                for row in rows:
2575
                    if pre != row['Components_UID']:
2576
                        if pre != '':
2577
                            self._associationss[pre] = compo
2578
                        pre = row['Components_UID']
2579
                        compo = []
2580
                        compo.append(row)
2581
                    else:
2582
                        compo.append(row)
2583

    
2584
                return self._associationss[component] if component in self._associationss else []
2585
                # Catch the exception
2586
            except Exception as ex:
2587
                from App import App
2588
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2589
                                                              sys.exc_info()[-1].tb_lineno)
2590
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2591

    
2592
    def get_component_attributes(self, component):
2593
        """ get attributes of given component """
2594
        if self._attributess and component in self._attributess:
2595
            return self._attributess[component]
2596
        elif self._attributess:
2597
            return []
2598

    
2599
        conn = self.project.database.connect()
2600
        with conn:
2601
            try:
2602
                # Get a cursor object
2603
                cursor = conn.cursor() if self.project.database.db_type == 'SQLite' else conn.cursor(as_dict=True)
2604

    
2605
                sql = "select a.*, b.* from Attributes a \
2606
                            join SymbolAttribute b on a.SymbolAttribute_UID=b.UID \
2607
                            join Components c on a.Components_UID=c.UID \
2608
                        where Drawings_UID='{}' order by a.Components_UID, b.[index]".format(self.activeDrawing.UID)
2609
                cursor.execute(sql)
2610

    
2611
                pre = ''
2612
                rows = cursor.fetchall()
2613
                for row in rows:
2614
                    if pre != row['Components_UID']:
2615
                        if pre != '':
2616
                            self._attributess[pre] = compo
2617
                        pre = row['Components_UID']
2618
                        compo = []
2619
                        compo.append(row)
2620
                    else:
2621
                        compo.append(row)
2622

    
2623
                return self._attributess[component] if component in self._attributess else []
2624
                # Catch the exception
2625
            except Exception as ex:
2626
                from App import App
2627
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2628
                                                              sys.exc_info()[-1].tb_lineno)
2629
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2630

    
2631
    def get_pipe_runs(self, component):
2632
        """ get line runs of given component """
2633
        conn = self.project.database.connect()
2634
        with conn:
2635
            try:
2636
                # Get a cursor object
2637
                cursor = conn.cursor() if self.project.database.db_type == 'SQLite' else conn.cursor(as_dict=True)
2638

    
2639
                sql = "select * from PipeRuns where Owner='{}' order by [Index]".format(component)
2640
                cursor.execute(sql)
2641
                return cursor.fetchall()
2642
                # Catch the exception
2643
            except Exception as ex:
2644
                from App import App
2645
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2646
                                                              sys.exc_info()[-1].tb_lineno)
2647
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2648

    
2649
    def get_pipe_run_items(self, pipe_run):
2650
        """ get line run items of given pipe run """
2651
        conn = self.project.database.connect()
2652
        with conn:
2653
            try:
2654
                # Get a cursor object
2655
                cursor = conn.cursor() if self.project.database.db_type == 'SQLite' else conn.cursor(as_dict=True)
2656

    
2657
                sql = "select * from PipeRunItems where PipeRuns_UID='{}' order by [Index]".format(pipe_run)
2658
                cursor.execute(sql)
2659
                return cursor.fetchall()
2660
                # Catch the exception
2661
            except Exception as ex:
2662
                from App import App
2663
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2664
                                                              sys.exc_info()[-1].tb_lineno)
2665
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2666

    
2667
    '''
2668
        @brief      get special item types from database
2669
        @author     humkyung
2670
        @date       2019.08.10
2671
    '''
2672

    
2673
    def get_special_item_types(self):
2674
        conn = self.project.database.connect()
2675
        with conn:
2676
            try:
2677
                # Get a cursor object
2678
                cursor = conn.cursor() if self.project.database.db_type == 'SQLite' else conn.cursor(as_dict=True)
2679

    
2680
                sql = 'select UID, Code, Type, Allowables from SpecialItemTypes order by Code DESC'
2681
                cursor.execute(sql)
2682
                return cursor.fetchall()
2683
                # Catch the exception
2684
            except Exception as ex:
2685
                from App import App
2686
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2687
                                                              sys.exc_info()[-1].tb_lineno)
2688
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2689

    
2690
    '''
2691
        @brief      save special item types
2692
        @author     humkyung
2693
        @date       2019.08.10
2694
    '''
2695

    
2696
    def save_special_item_types(self, datas):
2697
        import uuid
2698

    
2699
        conn = self.project.database.connect()
2700
        with conn:
2701
            try:
2702
                # Get a cursor object
2703
                cursor = conn.cursor()
2704

    
2705
                for data in datas:
2706
                    uid, code, _type, allowables = data[0], data[1], data[2], data[3]
2707
                    if not uid:
2708
                        sql = self.project.database.to_sql(
2709
                            'insert into SpecialItemTypes(UID, Code, Type, Allowables) values(?, ?, ?, ?)')
2710
                        param = (str(uuid.uuid4()), data[1], data[2], data[3])
2711
                    elif uid == '-1':
2712
                        sql = self.project.database.to_sql('delete from SpecialItemTypes where uid=?')
2713
                        param = (data[-1],)
2714
                    else:
2715
                        sql = self.project.database.to_sql(
2716
                            'update SpecialItemTypes SET Code=?, Type=?, Allowables=? WHERE UID = ?')
2717
                        param = (data[1], data[2], data[3], data[0])
2718
                    cursor.execute(sql, param)
2719

    
2720
                conn.commit()
2721
            # Catch the exception
2722
            except Exception as ex:
2723
                # Roll back any change if something goes wrong
2724
                conn.rollback()
2725

    
2726
                from App import App
2727
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2728
                                                              sys.exc_info()[-1].tb_lineno)
2729
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2730

    
2731
    def get_special_items(self, drawings=None):
2732
        """ get special items from database """
2733
        result = []
2734

    
2735
        conn = self.project.database.connect()
2736
        with conn:
2737
            try:
2738
                # get a cursor object
2739
                cursor = conn.cursor()
2740

    
2741
                sql = 'select distinct (select Value from Components where UID=D.Owner) as "Line No",C.Code from Components A \
2742
                    left join Drawings B on A.Drawings_UID=B.UID \
2743
                    left join SpecialItemTypes C on A.SpecialItemTypes_UID=C.UID \
2744
                    left join Components D on A.Connected=D.UID \
2745
                    where A.SpecialItemTypes_UID is not null order by "Line No"'
2746
                if drawings is not None:
2747
                    doc_names = "','".join(drawings)
2748
                    sql += f" and A.Drawings_UID in (select UID from Drawings where Name in ('{doc_names}'))"
2749
                cursor.execute(sql)
2750

    
2751
                return cursor.fetchall()
2752
            # catch the exception
2753
            except Exception as ex:
2754
                from App import App
2755
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2756
                                                              sys.exc_info()[-1].tb_lineno)
2757
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2758

    
2759
        return None
2760

    
2761
    '''
2762
        @brief      Set Common Code Data
2763
        @author     kyouho
2764
        @date       2018.07.12
2765
    '''
2766

    
2767
    def saveCommonCodeData(self, tableName, datas):
2768
        import uuid
2769

    
2770
        conn = self.project.database.connect()
2771
        with conn:
2772
            try:
2773
                # Get a cursor object
2774
                cursor = conn.cursor()
2775

    
2776
                for data in datas:
2777
                    uid, code, description, allowables = data[0], data[1], data[2], data[3]
2778
                    if not uid:
2779
                        sql = self.project.database.to_sql(
2780
                            "insert into {}(UID, CODE, DESCRIPTION, ALLOWABLES) values(?, ?, ?, ?)".format(tableName))
2781
                        param = (str(uuid.uuid4()), data[1], data[2], data[3])
2782
                    elif uid == '-1':
2783
                        sql = self.project.database.to_sql('delete from {} where uid=?'.format(tableName))
2784
                        param = (data[-1],)
2785
                    else:
2786
                        sql = self.project.database.to_sql(
2787
                            "update {} SET CODE=?, DESCRIPTION=?, ALLOWABLES=? WHERE UID = ?".format(tableName))
2788
                        param = (data[1], data[2], data[3], data[0])
2789
                    cursor.execute(sql, param)
2790

    
2791
                conn.commit()
2792
            # Catch the exception
2793
            except Exception as ex:
2794
                # Roll back any change if something goes wrong
2795
                conn.rollback()
2796

    
2797
                from App import App
2798
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2799
                                                              sys.exc_info()[-1].tb_lineno)
2800
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2801

    
2802
    '''
2803
        @brief      Set Common Code Data
2804
        @author     kyouho
2805
        @date       2018.07.12
2806
    '''
2807

    
2808
    def deleteCommonCodeData(self, datas):
2809
        try:
2810
            conn = self.project.database.connect()
2811
            with conn:
2812
                # Get a cursor object
2813
                cursor = conn.cursor()
2814

    
2815
                for data in datas:
2816
                    uid = data[0]
2817
                    tableName = data[1]
2818

    
2819
                    if uid:
2820
                        sql = "delete from {} where UID = ?".format(tableName)
2821
                        param = (uid,)
2822
                        cursor.execute(sql, param)
2823

    
2824
                    cursor.execute(sql, param)
2825

    
2826
                conn.commit()
2827

    
2828
        # Catch the exception
2829
        except Exception as ex:
2830
            # Roll back any change if something goes wrong
2831
            conn.rollback()
2832
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2833
                                                      sys.exc_info()[-1].tb_lineno))
2834

    
2835
    '''
2836
        @brief      delete data list
2837
        @author     kyouho
2838
        @date       2018.08.16
2839
    '''
2840

    
2841
    def deleteDataList(self, tableName, UID):
2842
        conn = self.project.database.connect()
2843
        with conn:
2844
            try:
2845
                # Get a cursor object
2846
                cursor = conn.cursor()
2847
                sql = 'delete from {} where UID = {}'.format(tableName, UID)
2848
                cursor.execute(sql)
2849
                conn.commit()
2850

    
2851
            # Catch the exception
2852
            except Exception as ex:
2853
                # Roll back any change if something goes wrong
2854
                conn.rollback()
2855
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2856
                                                          sys.exc_info()[-1].tb_lineno))
2857

    
2858
    def get_document_name_list(self):
2859
        """ get document name list """
2860
        result = []
2861

    
2862
        conn = self.project.database.connect()
2863
        with conn:
2864
            try:
2865
                # Get a cursor object
2866
                cursor = conn.cursor()
2867

    
2868
                sql = "select distinct B.Name as 'Drawing_Name' from Components A join Drawings B on A.Drawings_UID=B.UID"
2869
                cursor.execute(sql)
2870

    
2871
                rows = cursor.fetchall()
2872
                for row in rows:
2873
                    result.append(row[0])
2874

    
2875
                result.sort()
2876
            # Catch the exception
2877
            except Exception as ex:
2878
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2879
                                                          sys.exc_info()[-1].tb_lineno))
2880

    
2881
        return result
2882

    
2883
    '''
2884
        @brief      get line documentName list
2885
        @author     kyouho
2886
        @date       2018.08.13
2887
    '''
2888

    
2889
    def getLineDocumentNameList(self):
2890
        result = []
2891

    
2892
        conn = self.project.database.connect()
2893
        with conn:
2894
            try:
2895
                # Get a cursor object
2896
                cursor = conn.cursor()
2897

    
2898
                sql = 'select DISTINCT(PNID_NO) from LINE_DATA_LIST'
2899

    
2900
                cursor.execute(sql)
2901
                rows = cursor.fetchall()
2902
                for row in rows:
2903
                    result.append(row[0])
2904
            # Catch the exception
2905
            except Exception as ex:
2906
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2907
                                                          sys.exc_info()[-1].tb_lineno))
2908

    
2909
        return result
2910

    
2911
    '''
2912
        @brief      get line data list
2913
        @author     kyouho
2914
        @date       2018.08.13
2915
    '''
2916

    
2917
    def get_line_data_list(self, drawings=None):
2918
        result = []
2919

    
2920
        conn = self.project.database.connect()
2921
        with conn:
2922
            try:
2923
                # Get a cursor object
2924
                cursor = conn.cursor()
2925

    
2926
                sql = 'select A.UID,B.Name from Components A left join Drawings B on A.Drawings_UID=B.UID'
2927
                if drawings is not None:
2928
                    doc_names = "','".join(drawings)
2929
                    sql += f" where Drawings_UID in (select UID from Drawings where Name in ('{doc_names}'))"
2930
                cursor.execute(sql)
2931
                comps = [(row[0], row[1]) for row in cursor.fetchall()]
2932
                for comp in comps:
2933
                    sql = "select b.Name,a.Value from LineNoAttributes a left join LineProperties b on a.LineProperties_UID=b.UID where a.Components_UID='{}'".format(
2934
                        comp[0])
2935
                    cursor.execute(sql)
2936
                    attrs = cursor.fetchall()
2937
                    data = []
2938
                    for attr in attrs:
2939
                        data.append([attr[0], attr[1]])
2940
                    if data:
2941
                        data.insert(0, ['Drawing Name', comp[1]])
2942
                        data.insert(0, ['UID', comp[0]])
2943
                        result.append(data)
2944

    
2945
            # catch the exception
2946
            except Exception as ex:
2947
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2948
                                                          sys.exc_info()[-1].tb_lineno))
2949

    
2950
        return result
2951

    
2952
    def get_equipment_data_list(self, drawings=None):
2953
        """ get equipment data list """
2954

    
2955
        result = []
2956

    
2957
        with self.project.database.connect() as conn:
2958
            try:
2959
                # Get a cursor object
2960
                cursor = conn.cursor()
2961

    
2962
                sql = "select A.UID,B.NAME,C.SymbolType_UID,D.Type from Components A join Drawings B on A.Drawings_UID=B.UID\
2963
                        join Symbol C on A.Symbol_UID=C.UID\
2964
                        join SymbolType D on C.SymbolType_UID=D.UID\
2965
                        where D.Category in ('Equipment','Equipment Components')"
2966

    
2967
                if drawings is not None:
2968
                    doc_names = "','".join(drawings)
2969
                    sql += f" and A.Drawings_UID in (select UID from Drawings where Name in ('{doc_names}'))"
2970

    
2971
                cursor.execute(sql)
2972
                comps = [(row[0], row[1], row[2], row[3]) for row in cursor.fetchall()]
2973
                for comp in comps:
2974
                    sql = f"select distinct B.Attribute,A.Value from Attributes A left join SymbolAttribute B on " \
2975
                          f"A.SymbolAttribute_UID=B.UID where A.Components_UID='{comp[0]}'"
2976
                    cursor.execute(sql)
2977
                    attrs = cursor.fetchall()
2978
                    data = []
2979
                    for attr in attrs:
2980
                        data.append([attr[0], attr[1]])
2981
                    if data:
2982
                        data.insert(0, ['Type', comp[3]])
2983
                        data.insert(0, ['Drawing Name', comp[1]])
2984
                        data.insert(0, ['UID', comp[0]])
2985
                        result.append(data)
2986

    
2987
            # catch the exception
2988
            except Exception as ex:
2989
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2990
                                                           sys.exc_info()[-1].tb_lineno))
2991

    
2992
        return result
2993

    
2994
    '''
2995
        @brief      set line data list
2996
        @author     kyouho
2997
        @date       2018.08.13
2998
    '''
2999

    
3000
    def setLineDataList(self, dataLists):
3001
        conn = self.project.database.connect()
3002
        with conn:
3003
            try:
3004
                # Get a cursor object
3005
                cursor = conn.cursor()
3006

    
3007
                for data in dataLists:
3008
                    sql = "insert into LINE_DATA_LIST(UID, LINE_SIZE, LINE_SYMBOL, LINE_NO, LINE_CLASS, LINE_ROUTING_FROM, LINE_ROUTING_TO, SERVICE_FLUID, SERVICE_DENSITY, SERVICE_STATE, OPERATION_CONDITION_TEMP, OPERATION_CONDITION_PRESS, DESIGN_CONDITION_TEMP, DESIGN_CONDITION_PRESS, TEST_CONDITION_TEMP, TEST_CONDITION_PRESS, INSUL_CODE, PAINT_CODE, NDE_CODE, PWHT, PNID_NO) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
3009
                    param = tuple(data)
3010
                    cursor.execute(sql, param)
3011

    
3012
                conn.commit()
3013

    
3014
            # Catch the exception
3015
            except Exception as ex:
3016
                # Roll back any change if something goes wrong
3017
                conn.rollback()
3018
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3019
                                                          sys.exc_info()[-1].tb_lineno))
3020

    
3021
    '''
3022
        @brief      delete line data list
3023
        @author     kyouho
3024
        @date       2018.08.13
3025
    '''
3026
    def deleteLineDataList(self, removeUID):
3027
        conn = self.project.database.connect()
3028
        with conn:
3029
            try:
3030
                # Get a cursor object
3031
                cursor = conn.cursor()
3032

    
3033
                for uid in removeUID:
3034
                    sql = "delete from LINE_DATA_LIST where uid = '{}'".format(uid)
3035
                    cursor.execute(sql)
3036

    
3037
                conn.commit()
3038

    
3039
            # Catch the exception
3040
            except Exception as ex:
3041
                # Roll back any change if something goes wrong
3042
                conn.rollback()
3043
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3044
                                                          sys.exc_info()[-1].tb_lineno))
3045

    
3046
    '''
3047
        @brief      delete line data list
3048
        @author     kyouho
3049
        @date       2018.08.13
3050
    '''
3051

    
3052
    def deleteLineDataList_LineNo(self, removeUID):
3053
        conn = self.project.database.connect()
3054
        with conn:
3055
            try:
3056
                # Get a cursor object
3057
                cursor = conn.cursor()
3058

    
3059
                for uid in removeUID:
3060
                    sql = "delete from LINE_DATA_LIST where LINE_NO = ?"
3061
                    param = (uid,)
3062
                    cursor.execute(sql, param)
3063

    
3064
                conn.commit()
3065

    
3066
            # Catch the exception
3067
            except Exception as ex:
3068
                # Roll back any change if something goes wrong
3069
                conn.rollback()
3070
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3071
                                                          sys.exc_info()[-1].tb_lineno))
3072

    
3073
    '''
3074
        @brief      delete equip data list
3075
        @author     kyouho
3076
        @date       2018.08.14
3077
    '''
3078

    
3079
    def deleteEquipDataList(self, removeUID):
3080
        conn = self.project.database.connect()
3081
        with conn:
3082
            try:
3083
                # Get a cursor object
3084
                cursor = conn.cursor()
3085

    
3086
                for uid in removeUID:
3087
                    sql = "delete from EQUIPMENT_DATA_LIST where uid = '{}'".format(uid)
3088
                    cursor.execute(sql)
3089

    
3090
                conn.commit()
3091

    
3092
            # Catch the exception
3093
            except Exception as ex:
3094
                # Roll back any change if something goes wrong
3095
                conn.rollback()
3096
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3097
                                                          sys.exc_info()[-1].tb_lineno))
3098

    
3099
    '''
3100
        @brief      delete inst data list
3101
        @author     kyouho
3102
        @date       2018.08.14
3103
    '''
3104

    
3105
    def deleteInstDataList(self, removeUID):
3106
        conn = self.project.database.connect()
3107
        with conn:
3108
            try:
3109
                # Get a cursor object
3110
                cursor = conn.cursor()
3111

    
3112
                for uid in removeUID:
3113
                    sql = "delete from INSTRUMENT_DATA_LIST where uid = '{}'".format(uid)
3114
                    cursor.execute(sql)
3115

    
3116
                conn.commit()
3117

    
3118
            # Catch the exception
3119
            except Exception as ex:
3120
                # Roll back any change if something goes wrong
3121
                conn.rollback()
3122
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3123
                                                          sys.exc_info()[-1].tb_lineno))
3124

    
3125
    '''
3126
        @brief      delete note data list
3127
        @author     kyouho
3128
        @date       2018.10.10
3129
    '''
3130

    
3131
    def deleteNoteDataList(self, removeUID):
3132
        conn = self.project.database.connect()
3133
        with conn:
3134
            try:
3135
                # Get a cursor object
3136
                cursor = conn.cursor()
3137

    
3138
                for uid in removeUID:
3139
                    sql = "delete from NOTE_DATA_LIST where uid = '{}'".format(uid)
3140
                    cursor.execute(sql)
3141

    
3142
                conn.commit()
3143

    
3144
            # Catch the exception
3145
            except Exception as ex:
3146
                # Roll back any change if something goes wrong
3147
                conn.rollback()
3148
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3149
                                                          sys.exc_info()[-1].tb_lineno))
3150

    
3151
    def get_valve_attributes(self):
3152
        """ return valve attributes """
3153

    
3154
        from SymbolAttr import SymbolAttr
3155

    
3156
        res = None
3157
        if not hasattr(self, '_valve_attributes'):
3158
            self._valve_attributes = []
3159

    
3160
            conn = self.project.database.connect()
3161
            with conn:
3162
                try:
3163
                    # Get a cursor object
3164
                    cursor = conn.cursor()
3165

    
3166
                    sql = "select distinct A.Attribute from SymbolAttribute A join SymbolType B on A.SymbolType_UID=B.UID " \
3167
                          "where B.Category = 'Piping'"
3168
                    cursor.execute(sql)
3169
                    rows = cursor.fetchall()
3170
                    for row in rows:
3171
                        attr = SymbolAttr()
3172
                        attr.Attribute = row[0]
3173
                        self._valve_attributes.append(attr)
3174

    
3175
                    res = self._valve_attributes
3176
                # Catch the exception
3177
                except Exception as ex:
3178
                    print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3179
                                                               sys.exc_info()[-1].tb_lineno))
3180
        else:
3181
            res = self._valve_attributes
3182

    
3183
        return res
3184

    
3185
    def get_valve_data_list(self, drawings=None):
3186
        """get valve data list"""
3187

    
3188
        result = []
3189
        conn = self.project.database.connect()
3190
        with conn:
3191
            try:
3192
                # Get a cursor object
3193
                cursor = conn.cursor() if self.project.database.db_type == 'SQLite' else conn.cursor(as_dict=True)
3194

    
3195
                sql = "select a.UID,D.Name,E.Name as 'Drawing Name',C.Attribute,B.Value from Components a " \
3196
                      "join Attributes B on a.UID=B.Components_UID " \
3197
                      "join SymbolAttribute C on B.SymbolAttribute_UID=C.UID " \
3198
                      "join Symbol D on a.Symbol_UID=D.UID " \
3199
                      "join Drawings E on a.Drawings_UID=E.UID " \
3200
                      "where a.Symbol_UID in (select UID from Symbol where SymbolType_UID in " \
3201
                      "(select UID from SymbolType where Category in ('Piping')))"
3202
                if drawings is not None:
3203
                    doc_names = "','".join(drawings)
3204
                    sql += f" and A.Drawings_UID in (select UID from Drawings where Name in ('{doc_names}'))"
3205

    
3206
                cursor.execute(sql)
3207
                rows = cursor.fetchall()
3208
                for row in rows:
3209
                    matches = [res for res in result if res['UID'] == row['UID']]
3210
                    if matches:
3211
                        matches[0][row['Attribute']] = row['Value']
3212
                    else:
3213
                        data = {'UID': row['UID'], 'ITEM_NO': row['Name'], 'Drawing Name': row['Drawing Name'],
3214
                                row['Attribute']: row['Value']}
3215
                        result.append(data)
3216

    
3217
            # Catch the exception
3218
            except Exception as ex:
3219
                from App import App
3220
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3221
                                                              sys.exc_info()[-1].tb_lineno)
3222
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3223

    
3224
        return result
3225

    
3226
    def get_instrument_attributes(self):
3227
        """ return valve attributes """
3228

    
3229
        from SymbolAttr import SymbolAttr
3230

    
3231
        res = None
3232
        if not hasattr(self, '_inst_attributes'):
3233
            self._inst_attributes = []
3234

    
3235
            conn = self.project.database.connect()
3236
            with conn:
3237
                try:
3238
                    # Get a cursor object
3239
                    cursor = conn.cursor()
3240

    
3241
                    sql = "select distinct A.Attribute from SymbolAttribute A join SymbolType B on A.SymbolType_UID=B.UID " \
3242
                          "where B.Category = 'Instrumentation'"
3243
                    cursor.execute(sql)
3244
                    rows = cursor.fetchall()
3245
                    for row in rows:
3246
                        attr = SymbolAttr()
3247
                        attr.Attribute = row[0]
3248
                        self._inst_attributes.append(attr)
3249

    
3250
                    res = self._inst_attributes
3251
                # Catch the exception
3252
                except Exception as ex:
3253
                    print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3254
                                                               sys.exc_info()[-1].tb_lineno))
3255
        else:
3256
            res = self._inst_attributes
3257

    
3258
        return res
3259

    
3260
    '''
3261
        @brief      get instrument data list
3262
        @author     kyouho
3263
        @date       2018.08.14
3264
    '''
3265

    
3266
    def get_instrument_data_list(self, drawings=None):
3267
        result = []
3268
        conn = self.project.database.connect()
3269
        with conn:
3270
            try:
3271
                # Get a cursor object
3272
                cursor = conn.cursor() if self.project.database.db_type == 'SQLite' else conn.cursor(as_dict=True)
3273

    
3274
                sql = "select a.UID,D.Name,E.Name as 'Drawing Name',C.Attribute,B.Value from Components a " \
3275
                      "join Attributes B on a.UID=B.Components_UID " \
3276
                      "join SymbolAttribute C on B.SymbolAttribute_UID=C.UID " \
3277
                      "join Symbol D on a.Symbol_UID=D.UID " \
3278
                      "join Drawings E on a.Drawings_UID=E.UID " \
3279
                      "where a.Symbol_UID in (select UID from Symbol where SymbolType_UID in " \
3280
                      "(select UID from SymbolType where Category in ('Instrumentation')))"
3281
                if drawings is not None:
3282
                    doc_names = "','".join(drawings)
3283
                    sql += f" and A.Drawings_UID in (select UID from Drawings where Name in ('{doc_names}'))"
3284

    
3285
                cursor.execute(sql)
3286
                rows = cursor.fetchall()
3287
                for row in rows:
3288
                    matches = [res for res in result if res['UID'] == row['UID']]
3289
                    if matches:
3290
                        matches[0][row['Attribute']] = row['Value']
3291
                    else:
3292
                        data = {'UID': row['UID'], 'ITEM_NO': row['Name'], 'Drawing Name': row['Drawing Name'],
3293
                                row['Attribute']: row['Value']}
3294
                        result.append(data)
3295
            # Catch the exception
3296
            except Exception as ex:
3297
                from App import App
3298
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3299
                                                              sys.exc_info()[-1].tb_lineno)
3300
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3301

    
3302
        return result
3303

    
3304
    def get_note_attributes(self):
3305
        """ return note attributes """
3306

    
3307
        from SymbolAttr import SymbolAttr
3308

    
3309
        res = None
3310
        if not hasattr(self, '_note_attributes'):
3311
            self._note_attributes = []
3312

    
3313
            conn = self.project.database.connect()
3314
            with conn:
3315
                try:
3316
                    # Get a cursor object
3317
                    cursor = conn.cursor()
3318

    
3319
                    sql = "select distinct A.Attribute from SymbolAttribute A join SymbolType B on A.SymbolType_UID=B.UID " \
3320
                          "where B.Category='General' and B.Type='Notes'"
3321
                    cursor.execute(sql)
3322
                    rows = cursor.fetchall()
3323
                    for row in rows:
3324
                        attr = SymbolAttr()
3325
                        attr.Attribute = row[0]
3326
                        self._note_attributes.append(attr)
3327

    
3328
                    res = self._note_attributes
3329
                # Catch the exception
3330
                except Exception as ex:
3331
                    print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3332
                                                               sys.exc_info()[-1].tb_lineno))
3333
        else:
3334
            res = self._note_attributes
3335

    
3336
        return res
3337

    
3338
    def get_note_data_list(self, drawings=None):
3339
        """ get note data list """
3340
        result = []
3341

    
3342
        conn = self.project.database.connect()
3343
        with conn:
3344
            try:
3345
                # Get a cursor object
3346
                cursor = conn.cursor() if self.project.database.db_type == 'SQLite' else conn.cursor(as_dict=True)
3347

    
3348
                sql = "select a.UID,D.Name,E.Name as 'Drawing Name',C.Attribute,B.Value from Components a " \
3349
                      "join Attributes B on a.UID=B.Components_UID " \
3350
                      "join SymbolAttribute C on B.SymbolAttribute_UID=C.UID " \
3351
                      "join Symbol D on a.Symbol_UID=D.UID " \
3352
                      "join Drawings E on a.Drawings_UID=E.UID " \
3353
                      "where a.Symbol_UID in (select UID from Symbol where SymbolType_UID in " \
3354
                      "(select UID from SymbolType where Category='General' and Type='Notes'))"
3355
                if drawings is not None:
3356
                    doc_names = "','".join(drawings)
3357
                    sql += f" and A.Drawings_UID in (select UID from Drawings where Name in ('{doc_names}'))"
3358

    
3359
                cursor.execute(sql)
3360
                rows = cursor.fetchall()
3361
                for row in rows:
3362
                    matches = [res for res in result if res['UID'] == row['UID']]
3363
                    if matches:
3364
                        matches[0][row['Attribute']] = row['Value']
3365
                    else:
3366
                        data = {'UID': row['UID'], 'ITEM_NO': row['Name'], 'Drawing Name': row['Drawing Name'],
3367
                                row['Attribute']: row['Value']}
3368
                        result.append(data)
3369
            # Catch the exception
3370
            except Exception as ex:
3371
                from App import App
3372
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3373
                                                              sys.exc_info()[-1].tb_lineno)
3374
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3375

    
3376
        return result
3377

    
3378
    def saveToDatabase(self, items, show_progress=None):
3379
        """ save given items to database """
3380
        # delete all datas of current drawing
3381
        drawing_name = self.activeDrawing.name
3382
        drawing_uid = self.activeDrawing.UID
3383

    
3384
        queries = {'first':[], 'second':[]}
3385
        for item in items:
3386
            if hasattr(item, 'toSql_return_separately'):
3387
                sql, sqlLater = item.toSql_return_separately()
3388
                queries['first'].append(sql)
3389
                queries['second'].append(sqlLater)
3390
            else:
3391
                queries['first'].append(item.toSql())
3392

    
3393
        with self.project.database.connect() as conn:
3394
            try:
3395
                # Get a cursor object
3396
                cursor = conn.cursor()
3397
                if self.project.database.db_type == 'SQLite':
3398
                    cursor.execute('begin')
3399

    
3400
                sql = "delete from LINE_DATA_LIST where PNID_NO = '{}'".format(drawing_name)
3401
                cursor.execute(sql)
3402
                sql = "delete from TitleBlockValues where Drawings_UID = '{}'".format(drawing_uid)
3403
                cursor.execute(sql)
3404

    
3405
                # delete LineNoAttributes
3406
                sql = f"delete from LineNoAttributes where Components_UID in " \
3407
                      f"(select UID from Components where Drawings_UID='{drawing_uid}')"
3408
                cursor.execute(sql)
3409

    
3410
                # delete Attributes
3411
                sql = f"delete from Attributes where Components_UID in " \
3412
                      f"(select UID from Components where Drawings_UID='{drawing_uid}')"
3413
                cursor.execute(sql)
3414

    
3415
                # delete Associations
3416
                sql = f"delete from Associations where Components_UID in " \
3417
                      f"(select UID from Components where Drawings_UID='{drawing_uid}')"
3418
                cursor.execute(sql)
3419

    
3420
                # delete Points
3421
                sql = f"delete from Points where Components_UID in " \
3422
                      f"(select UID from Components where Drawings_UID='{drawing_uid}')"
3423
                cursor.execute(sql)
3424

    
3425
                # delete PipeRunItems
3426
                sql = f"delete from PipeRunItems where PipeRuns_UID in " \
3427
                      f"(select UID from PipeRuns where Drawings_UID='{drawing_uid}')"
3428
                cursor.execute(sql)
3429

    
3430
                # delete PipeRuns
3431
                sql = f"delete from PipeRuns where Drawings_UID='{drawing_uid}'"
3432
                cursor.execute(sql)
3433

    
3434
                # delete Components 
3435
                sql = "delete from Components where Drawings_UID='{}'".format(drawing_uid)
3436
                cursor.execute(sql)
3437

    
3438
                progress = 0
3439
                length = len(queries['first']) + len(queries['second'])
3440
                for sql in queries['first']:
3441
                    if type(sql) is list:
3442
                        for item in sql:
3443
                            if item is not None and 2 == len(item):
3444
                                cursor.executemany(self.project.database.to_sql(item[0]), item[1])
3445
                    else:
3446
                        if sql is not None and 2 == len(sql):
3447
                            cursor.executemany(self.project.database.to_sql(sql[0]), sql[1])
3448

    
3449
                    if show_progress:
3450
                        show_progress.emit(int((progress / length)*100))
3451
                    progress += 1
3452

    
3453
                for sql in queries['second']:
3454
                    if type(sql) is list:
3455
                        for item in sql:
3456
                            if item is not None and 2 == len(item):
3457
                                cursor.executemany(self.project.database.to_sql(item[0]), item[1])
3458
                    else:
3459
                        if sql is not None and 2 == len(sql):
3460
                            cursor.executemany(self.project.database.to_sql(sql[0]), sql[1])
3461

    
3462
                    if show_progress:
3463
                        show_progress.emit(int((progress / length)*100))
3464
                    progress += 1
3465

    
3466
                if show_progress:
3467
                    show_progress.emit(99)
3468

    
3469
                if self.project.database.db_type == 'SQLite':
3470
                    cursor.execute('commit')
3471
                else:
3472
                    conn.commit()
3473
            # Catch the exception
3474
            except Exception as ex:
3475
                # Roll back any change if something goes wrong
3476
                conn.rollback()
3477

    
3478
                from App import App
3479
                message = 'error occurred({}\\n{}) in {}:{}'.format(repr(ex), sql,
3480
                                                                    sys.exc_info()[-1].tb_frame.f_code.co_filename,
3481
                                                                    sys.exc_info()[-1].tb_lineno)
3482
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3483

    
3484
    '''
3485
        @brief      set equipment data list
3486
        @author     humkyung
3487
        @date       2018.05.03
3488
    '''
3489

    
3490
    def setEquipmentDataList(self, dataList):
3491
        conn = self.project.database.connect()
3492
        with conn:
3493
            try:
3494
                # Get a cursor object
3495
                cursor = conn.cursor()
3496

    
3497
                for data in dataList:
3498
                    sql = "insert into EQUIPMENT_DATA_LIST(UID, ITEM_NO, SERVICE, NO_REQ, FLUID, DESC_OF_PART, OPERATION_CONDITION_TEMP, OPERATION_CONDITION_PRESS, DESIGN_CONDITION_TEMP, DESIGN_CONDITION_PRESS, MATERIAL, WEIGHT, POWER, INSULATION, PNID_NO, REV) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
3499
                    param = tuple(data)
3500
                    cursor.execute(self.project.database.to_sql(sql), param)
3501
                conn.commit()
3502
            # Catch the exception
3503
            except Exception as ex:
3504
                # Roll back any change if something goes wrong
3505
                conn.rollback()
3506

    
3507
                from App import App
3508
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3509
                                                              sys.exc_info()[-1].tb_lineno)
3510
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3511

    
3512
    '''
3513
        @brief      set instrumnet data list
3514
        @author     kyoyho
3515
        @date       2018.08.14
3516
    '''
3517

    
3518
    def setInstrumentDataList(self, dataList):
3519
        conn = self.project.database.connect()
3520
        with conn:
3521
            try:
3522
                # Get a cursor object
3523
                cursor = conn.cursor()
3524

    
3525
                for data in dataList:
3526
                    sql = "insert into INSTRUMENT_DATA_LIST(UID, ITEM_NO, SERVICE, FLOW_RATE, PRESSURE, TEMPERATURE, TPYE, RANGE, NOR_LEVEL_MM, NOR_LEVEL_PERCENT, DEL_PRESS, SHUT_OFF, LOCATION, PNID_NO, REV) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
3527
                    param = tuple(data)
3528
                    cursor.execute(sql, param)
3529
                conn.commit()
3530

    
3531
            # Catch the exception
3532
            except Exception as ex:
3533
                # Roll back any change if something goes wrong
3534
                conn.rollback()
3535

    
3536
                from App import App
3537
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3538
                                                              sys.exc_info()[-1].tb_lineno)
3539
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3540

    
3541
    def getDrawings(self):
3542
        """ get drawings """
3543
        from Drawing import Drawing
3544

    
3545
        res = []
3546

    
3547
        with self.project.database.connect() as conn:
3548
            try:
3549
                cursor = conn.cursor() if self.project.database.db_type == 'SQLite' else conn.cursor(as_dict=True)
3550
                sql = 'select UID,[NAME],[DATETIME] from Drawings'
3551
                cursor.execute(sql)
3552
                for row in cursor.fetchall():
3553
                    res.append(Drawing(row['UID'], row['NAME'], row['DATETIME']))
3554
            # Catch the exception
3555
            except Exception as ex:
3556
                from App import App
3557
                message = 'error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename,
3558
                                                              sys.exc_info()[-1].tb_lineno)
3559
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3560

    
3561
        return res
3562

    
3563
    def saveDrawings(self, drawings):
3564
        """save given drawings"""
3565

    
3566
        import uuid
3567

    
3568
        with self.project.database.connect() as conn:
3569
            try:
3570
                # Get a cursor object
3571
                cursor = conn.cursor() if self.project.database.db_type == 'SQLite' else conn.cursor(as_dict=True)
3572
                if self.project.database.db_type == 'SQLite':
3573
                    cursor.execute('begin')
3574

    
3575
                for drawing in drawings:
3576
                    if drawing.UID is None:
3577
                        # get image data
3578
                        image_blob_data = None
3579
                        #file_path = os.path.join(self.project.getDrawingFilePath(), drawing.name)
3580
                        #if drawing.name and os.path.isfile(file_path):
3581
                        #    with open(file_path.encode('utf-8'), 'rb') as file:
3582
                        #        image_blob_data = file.read()
3583
                        # up to here
3584

    
3585
                        sql = self.project.database.to_sql(
3586
                            'insert into Drawings(UID, [NAME], [DATETIME], [Image]) values(?, ?, ?, ?)')
3587
                        param = tuple([str(uuid.uuid4()), drawing.name, '', image_blob_data])
3588
                        drawing.UID = param[0]
3589
                    else:
3590
                        sql = self.project.database.to_sql("update Drawings set [NAME]=?,[DATETIME]=? where UID=?")
3591
                        param = (drawing.name, drawing.datetime, str(drawing.UID))
3592
                        #param = (drawing.name, drawing.datetime, image_blob_data, str(drawing.UID))
3593

    
3594
                    cursor.execute(sql, param)
3595

    
3596
                if self.project.database.db_type == 'SQLite':
3597
                    cursor.execute('commit')
3598
                else:
3599
                    conn.commit()
3600
            # Catch the exception
3601
            except Exception as ex:
3602
                # Roll back any change if something goes wrong
3603
                conn.rollback()
3604

    
3605
                from App import App
3606
                message = 'error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename,
3607
                                                              sys.exc_info()[-1].tb_lineno)
3608
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3609

    
3610
    '''
3611
        @brief  get IsOriginDetect ComboBox Items
3612
    '''
3613

    
3614
    def getIsOriginDetectComboBoxItems(self):
3615
        return [("원본 도면", 0), ("텍스트 제거 도면", 1)]
3616

    
3617
    '''
3618
        @brief  get IsOriginDetect ComboBox Items
3619
    '''
3620

    
3621
    def getOcrOptionComboBoxItems(self):
3622
        return [("OCR 미적용", 0), ("일반 심볼", 1), ("Instrument 계통", 2)]
3623

    
3624
    '''
3625
        @brief      Return Symbol Type Items
3626
        @author     Jeongwoo
3627
        @date       18.04.20
3628
        @history    18.05.08    Jeongwoo type index changed
3629
    '''
3630

    
3631
    def getSymbolTypeList(self):
3632
        symbolTypeList = []
3633

    
3634
        conn = self.project.database.connect()
3635
        with conn:
3636
            cursor = conn.cursor()
3637
            sql = 'SELECT * FROM SymbolType ORDER BY Type ASC'
3638
            try:
3639
                cursor.execute(sql)
3640
                rows = cursor.fetchall()
3641
                for row in rows:
3642
                    symbolTypeList.append((row[0], row[1], row[2]))  # UID, category, type
3643
            except Exception as ex:
3644
                from App import App
3645
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3646
                                                              sys.exc_info()[-1].tb_lineno)
3647
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3648

    
3649
        return symbolTypeList
3650

    
3651
    '''
3652
        @brief      Get Symbol Category by Symbol Type
3653
        @author     Jeongwoo
3654
        @date       2018.05.09
3655
    '''
3656

    
3657
    def getSymbolCategoryByType(self, type):
3658
        category = None
3659
        if type in self._symbolType:
3660
            return self._symbolType[type]
3661

    
3662
        conn = self.project.database.connect()
3663
        with conn:
3664
            try:
3665
                cursor = conn.cursor()
3666
                sql = self.project.database.to_sql('SELECT Category FROM SymbolType WHERE [Type] = ?')
3667
                cursor.execute(sql, (type,))
3668
                rows = cursor.fetchall()
3669
                if rows is not None and len(rows) > 0:
3670
                    category = rows[0][0]
3671
                    self._symbolType[type] = category
3672
            except Exception as ex:
3673
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3674
                                                          sys.exc_info()[-1].tb_lineno))
3675

    
3676
        return category
3677

    
3678
    '''
3679
        @brief      Check Symbol Type is included in 'Equipment' Category
3680
        @author     Jeongwoo
3681
        @date       2018.05.09
3682
    '''
3683

    
3684
    def isEquipmentType(self, type):
3685
        category = self.getSymbolCategoryByType(type)
3686
        return (category is not None and category == 'Equipment')
3687

    
3688
    '''
3689
        @brief      Return Symbol Type Items with "None"
3690
        @author     Jeongwoo
3691
        @date       18.04.06
3692
        @history    Seperate SymbolTypeList and "None"
3693
    '''
3694

    
3695
    def getSymbolTypeComboBoxItems(self):
3696
        symbolTypeList = self.getSymbolTypeList()
3697
        symbolTypeList.insert(0, ('None', 'None', 'None'))
3698

    
3699
        return symbolTypeList
3700

    
3701
    '''
3702
        @brief  get Base Symbol ComboBox Items
3703
    '''
3704

    
3705
    def getBaseSymbolComboBoxItems(self, type=None):
3706
        bsymbolNameList = self.getSymbolNameListByType(type)
3707
        bsymbolNameList.sort()
3708
        bsymbolNameList.insert(0, "None")
3709
        return bsymbolNameList
3710

    
3711
    '''
3712
        @brief  get Additional Symbol ComboBox Items
3713
    '''
3714

    
3715
    def getAdditionalSymbolComboBoxItems(self):
3716
        asymbolNameList = self.getSymbolNameList()
3717
        asymbolNameList.sort()
3718
        asymbolNameList.insert(0, "None")
3719
        return asymbolNameList
3720

    
3721
    '''
3722
        @brief  get Additional Symbol's default direction ComboBox Items
3723
    '''
3724

    
3725
    def getDefaultSymbolDirectionComboBoxItems(self):
3726
        return [("UP", 0), ("DOWN", 2), ("LEFT", 3), ("RIGHT", 1)]
3727

    
3728
    '''
3729
        @brief  getter of activeDrawing
3730
        @author humkyung
3731
        @date   2018.07.07
3732
    '''
3733

    
3734
    @property
3735
    def activeDrawing(self):
3736
        return self._activeDrawing
3737

    
3738
    '''
3739
        @brief  setter of activeDrawing
3740
        @author humkyung
3741
        @date   2018.07.07
3742
    '''
3743

    
3744
    @activeDrawing.setter
3745
    def activeDrawing(self, value):
3746
        if self._activeDrawing:
3747
            del self._activeDrawing
3748

    
3749
        self._activeDrawing = value
3750

    
3751
    def getColNames(self, table):
3752
        """ return column names of given table and attribute names if tabe is VALVE_DATA_LIST or EQUIPMET_DATA_LIST """
3753
        res = None
3754

    
3755
        conn = self.project.database.connect()
3756
        with conn:
3757
            try:
3758
                cursor = conn.cursor()
3759
                cursor.execute('select * from {}'.format(table))
3760
                res = [col_name[0] for col_name in cursor.description]
3761

    
3762
                if table == 'EQUIPMET_DATA_LIST' or table == 'VALVE_DATA_LIST':
3763
                    sql = 'select distinct c.Attribute from {} a left join Attributes b on a.uid=b.Components_UID ' \
3764
                          'left join SymbolAttribute c on b.SymbolAttribute_UID=c.UID where c.Attribute is not NULL'.format(
3765
                        table)
3766
                    cursor.execute(sql)
3767
                    rows = cursor.fetchall()
3768
                    for row in rows:
3769
                        res.append(row[0])
3770
            # Catch the exception
3771
            except Exception as ex:
3772
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3773
                                                          sys.exc_info()[-1].tb_lineno))
3774

    
3775
        return res
3776

    
3777
    '''
3778
        @brief  getter of OCRData
3779
        @author humkyung
3780
        @date   2018.11.19
3781
    '''
3782

    
3783
    @property
3784
    def OCRData(self):
3785
        if self._OCRData is None:
3786
            configs = self.getConfigs('Text Recognition', 'OCR Data')
3787
            self._OCRData = configs[0].value if 1 == len(configs) else 'eng'
3788

    
3789
        return self._OCRData
3790

    
3791
    '''
3792
        @brief  setter of OCRData
3793
        @author humkyung
3794
        @date   2018.11.19
3795
    '''
3796

    
3797
    @OCRData.setter
3798
    def OCRData(self, value):
3799
        self._OCRData = value
3800

    
3801

    
3802
if __name__ == '__main__':
3803
    from AppDocData import AppDocData
3804

    
3805
    instance = AppDocData.instance()
클립보드 이미지 추가 (최대 크기: 500 MB)