프로젝트

일반

사용자정보

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

hytos / DTI_PID / DTI_PID / AppDocData.py @ 8c9f8074

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

1
# coding: utf-8
2
"""
3
    This is document data(SDI) class
4
"""
5
import sys
6
import os
7
import sqlite3
8
import datetime
9
from enum import Enum
10
from PIL import PngImagePlugin, JpegImagePlugin
11
from PIL import Image
12
from PIL.ImageQt import ImageQt
13

    
14
try:
15
    from PyQt5.QtCore import *
16
    from PyQt5.QtGui import *
17
    from PyQt5 import QtWidgets
18
except ImportError:
19
    from PyQt4.QtCore import *
20
    from PyQt4.QtGui import *
21
import numpy as np
22

    
23
from SingletonInstance import SingletonInstane
24
import symbol
25

    
26
class Source:
27
    def __init__(self, source):
28
        if type(source) is np.ndarray:
29
            self.source = Image.fromarray(source)
30
        elif type(source) is PngImagePlugin.PngImageFile or type(source) is JpegImagePlugin.JpegImageFile:
31
            self.source = source
32
        elif type(source) is QImage:
33
            self.source = Image.fromqimage(source)
34
        elif type(source) is QPixmap:
35
            self.source = Image.fromqpixmap(source)
36
        
37
    '''
38
        @history    2018.05.18  Jeongwoo    When Parameter [rect] is None, return whole image
39
    '''
40
    def getPyImageOnRect(self, rect = None):
41
        if rect is not None:
42
            return self.source.copy().crop((rect.left(), rect.top(), rect.right(), rect.bottom()))
43
        else:
44
            return self.source.copy()
45

    
46
    def getQImageOnRect(self, rect = None):
47
        image = ImageQt(self.getPyImageOnRect(rect))
48
        return image.convertToFormat(QImage.Format_RGBA8888)
49

    
50
class Config:
51
    def __init__(self, section, key, value):
52
        self.section = section
53
        self.key = key
54
        self.value = value
55

    
56
class NominalPipeSize:
57
    def __init__(self, code, metric, inch, inchStr, metricStr):
58
        self.code = code
59
        self.metric = metric
60
        self.inch = inch
61
        self.inchStr = inchStr
62
        self.metricStr = metricStr
63
        self.sizeUnit = 'Metric'
64

    
65
    '''
66
        @brief  return size value string
67
        @author humkyung
68
        @date   2018.04.24
69
    '''
70
    def sizeValue(self):
71
        return self.inchStr if 'Inch' == self.sizeUnit else self.metricStr
72

    
73
'''
74
    @brief  Pipe color class
75
'''
76
class Color:
77
    def __init__(self, index, red, green, blue):
78
        self.index = index
79
        self.red = red
80
        self.green = green
81
        self.blue = blue
82

    
83
'''
84
    @brief      MessageType
85
    @author     humkyung 
86
    @date       2018.07.31
87
'''
88
class MessageType(Enum):
89
    Normal = 1
90
    Error = 2
91

    
92
class AppDocData(SingletonInstane):
93
    def __init__(self):
94
        self._imgFilePath = None
95
        self.imgName = None
96
        self.imgWidth = 0
97
        self.imgHeight = 0
98
        self._OCRData = None
99
        self._imgSrc = None
100

    
101
        self._areas = []
102
        self.equipments = []
103
        self.lineNos = []
104
        self.lines = []
105
        self.texts = []
106
        self.symbols = []
107
        self.unknowns = []
108
        self.allItems = []
109
        self._colors = None
110
        self._lineNoProperties = None
111
        self._lineTypes = None
112
        self._lineTypeConfigs = None
113
        self._activeDrawing = None
114
        self._hmbTable = None
115
        self._titleBlockProperties = None
116
        self.needReOpening = None
117

    
118

    
119
    def clearItemList(self):
120
        '''
121
            @brief      clear item list
122
            @author     euisung
123
            @date       2018.11.28
124
        '''
125
        self.equipments.clear()
126
        self.symbols.clear()
127
        self.lineNos.clear()
128
        self.texts.clear()
129
        self.lines.clear()
130
        self.unknowns.clear()
131
        self.allItems.clear()
132

    
133
    '''
134
        @brief      clear
135
        @author     humkyung
136
        @date       2018.09.06
137
    '''
138
    def clear(self):
139
        self._imgFilePath = None
140
        self.imgName = None
141
        self.imgWidth = 0
142
        self.imgHeight = 0
143
        self._imgSrc = None
144

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

    
160
    '''
161
        @brief      Get drawing file list
162
        @author     euisung
163
        @date       2018.09.28
164
    '''
165
    def getDrawingFileList(self):
166
        try:
167
            project = AppDocData.instance().getCurrentProject()
168
            path = project.getDrawingFilePath()
169
            drawingFileList = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
170
            drawingFileList.sort()
171
        except Exception as ex:
172
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
173

    
174
        return drawingFileList
175

    
176
    '''
177
        @brief      Get Training file list
178
        @author     euisung
179
        @date       2018.10.16
180
    '''
181
    def getTrainingFileList(self):
182
        try:
183
            project = AppDocData.instance().getCurrentProject()
184
            path = project.getTrainingFilePath()
185
            drawingFileList = os.listdir(path)
186
            drawingFileList.sort()
187
        except Exception as ex:
188
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
189

    
190
        return drawingFileList
191

    
192
    '''
193
        @brief      Get DB file path in ProgramData
194
        @author     Jeongwoo
195
        @date       2018.06.27
196
        @history    2018.06.29  Jeongwoo    Change method to get template db path
197
    '''
198
    def getTemplateDbPath(self):
199
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
200
        templateDbPath = os.path.join(path, 'Template.db')
201
        return templateDbPath
202

    
203
    def getAppDbPath(self):
204
        """
205
        @brief      Get application DB file path in ProgramData
206
        @author     humkyung
207
        @date       2018.10.01
208
        """
209

    
210
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
211
        app_database = os.path.join(path, 'App.db')
212
        return app_database 
213

    
214
    '''
215
        @brief  getter of colors 
216
        @author humkyung
217
        @date   2018.06.18
218
    '''
219
    @property
220
    def colors(self):
221
        if self._colors is None:
222
            self._colors = []
223
            try:
224
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath() , 'ITI_PID.db')
225

    
226
                conn = sqlite3.connect(dbPath)
227
                cursor = conn.cursor()
228
                sql = 'SELECT UID,RED,GREEN,BLUE FROM Colors'
229
                cursor.execute(sql)
230
                rows = cursor.fetchall()
231
                for row in rows:
232
                    self._colors.append(Color(int(row[0]), int(row[1]), int(row[2]), int(row[3])))
233
            # Catch the exception
234
            except Exception as ex:
235
                # Roll back any change if something goes wrong
236
                conn.rollback()
237

    
238
                from App import App 
239
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
240
                App.mainWnd().addMessage.emit(MessageType.Error, message)
241
            finally:
242
                conn.close()
243

    
244
        return self._colors
245

    
246
    '''
247
        @brief  setter of colors
248
        @author humkyung
249
        @date   2018.06.18
250
    '''
251
    @colors.setter
252
    def colors(self, value):
253
        self._colors = value
254

    
255
    '''
256
        @brief      set image file path
257
        @author     humkyung
258
        @date       2018.07.30
259
    '''
260
    def setImgFilePath(self, path):
261
        self._imgFilePath = path
262
        self.imgName = os.path.splitext(os.path.basename(self._imgFilePath))[0]
263

    
264
    '''
265
        @brief      getter of imgSrc
266
        @author     humkyung
267
        @date       2018.07.30
268
    '''
269
    @property
270
    def imgSrc(self):
271
        import cv2
272

    
273
        if self._imgSrc is None and self._imgFilePath is not None and os.path.isfile(self._imgFilePath):
274
            self._imgSrc = cv2.cvtColor(cv2.imread(self._imgFilePath), cv2.COLOR_BGR2GRAY)
275
            #blur = cv2.GaussianBlur(self._imgSrc , (5,5),0)
276
            self._imgSrc = cv2.threshold(self._imgSrc, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
277
        
278
        return self._imgSrc
279

    
280
    '''
281
        @brief      setter of imgSrc
282
        @author     humkyung
283
        @date       2018.07.30
284
    '''
285
    @imgSrc.setter
286
    def imgSrc(self, value):
287
        self._imgSrc = value
288

    
289
    '''
290
        @brief      reset imgSrc
291
        @author     humkyung
292
        @date       2018.07.30
293
    '''
294
    def resetImgSrc(self):
295
        self._imgSrc = None
296

    
297
    '''
298
        @brief  getter of line type configs
299
        @author humkyung
300
        @date   2018.06.28
301
    '''
302
    @property
303
    def lineTypeConfigs(self):
304
        from PyQt5.QtCore import Qt
305

    
306
        if self._lineTypeConfigs is None:
307
            self._lineTypeConfigs = []
308

    
309
            styleMap = [('SolidLine', Qt.SolidLine), ('DashLine', Qt.DashLine), ('DotLine', Qt.DotLine), ('DashDotLine', Qt.DashDotLine), 
310
                ('DashDotDotLine', Qt.DashDotDotLine), ('CustomDashLine', Qt.CustomDashLine)]
311

    
312
            configs = self.getConfigs('LineTypes')
313
            for config in configs:
314
                width, _style = config.value.split(',')
315
                matches = [param for param in styleMap if param[0] == _style]
316
                style = matches[0][1] if matches else Qt.SolidLine
317
                self._lineTypeConfigs.append((config.key, int(width), style))
318
        
319
        return self._lineTypeConfigs
320

    
321
    '''
322
        @brief  setter of line type configs
323
        @author humkyung
324
        @date   2018.06.28
325
    '''
326
    @lineTypeConfigs.setter
327
    def lineTypeConfigs(self, value):
328
        self._lineTypeConfigs = value
329

    
330
    '''
331
        @brief      getter of hmb table
332
        @author     humkyung
333
        @date       2018.07.16
334
    '''
335
    @property
336
    def hmbTable(self):
337
        from HMBTable import HMBTable
338

    
339
        if self._hmbTable is None:
340
            self._hmbTable = HMBTable()
341
            self._hmbTable.loadData()
342
        
343
        return self._hmbTable
344

    
345
    '''
346
        @brief      setter of hmb table
347
        @author     humkyung
348
        @date       2018.07.16
349
    '''
350
    @hmbTable.setter
351
    def hmbTable(self, value):
352
        self._hmbTable = value
353

    
354
    '''
355
        @brief  get line type config of given line type
356
        @author humkyung
357
        @date   2018.06.28
358
    '''
359
    def getLineTypeConfig(self, lineType):
360
        from PyQt5.QtCore import Qt
361

    
362
        matches = [config for config in self.lineTypeConfigs if config[0] == lineType]
363
        return matches[0] if matches else (lineType, 5, Qt.SolidLine)        
364

    
365
    def setCurrentPidSource(self, image):
366
        self.imgWidth, self.imgHeight = image.size
367

    
368
        self.currentPidSource = Source(image)
369

    
370
    def getCurrentPidSource(self):
371
        return self.currentPidSource
372

    
373
    '''
374
        @brief      Check if Exist data or not, Moved from SG_DbHelper
375
        @author     Jeongwoo
376
        @date       2018.05.03
377
    '''
378
    def isExistData(self, fieldName, data):
379
        rows = None
380
        try:
381
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
382

    
383
            conn = sqlite3.connect(dbPath)
384
            cursor = conn.cursor()
385
            sql = ""
386
            if isinstance(data, str):
387
                sql = "SELECT * FROM Symbol WHERE " + fieldName + " = '"+ data +"'"
388
            else:
389
                sql = "SELECT * FROM Symbol WHERE " + fieldName + " = "+ str(data) +""
390
            cursor.execute(sql)
391
            rows = cursor.fetchall()
392
        # Catch the exception
393
        except Exception as ex:
394
            # Roll back any change if something goes wrong
395
            conn.rollback()
396
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
397
        finally:
398
            conn.close()
399
            if rows is not None and len(rows) > 0:
400
                return True
401
            else:
402
                return False
403

    
404
    '''
405
        @brief      Check if exist file name or not, Moved from SG_DbHelper
406
        @author     Jeongwoo
407
        @date       2018.05.03
408
    '''
409
    def isExistFileName(self, name):
410
        rows = None
411
        try:
412
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
413
            conn = sqlite3.connect(dbPath)
414
            cursor = conn.cursor()
415
            sql = "SELECT * FROM Symbol WHERE name = '"+ name +"'"
416
            cursor.execute(sql)
417
            rows = cursor.fetchall()
418
        # Catch the exception
419
        except Exception as ex:
420
            # Roll back any change if something goes wrong
421
            conn.rollback()
422
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
423
        finally:
424
            conn.close()
425
            if rows is not None and len(rows) > 0:
426
                return True
427
            else:
428
                return False
429

    
430
    '''
431
        @brief      Insert new symbol into Symbol Table, Moved from SG_DbHelper
432
        @author     Jeongwoo
433
        @date       2018.05.03
434
    '''
435
    def insertSymbol(self, symbol):
436
        isAdded = False
437
        try:
438
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
439
            conn = sqlite3.connect(dbPath)
440
            
441
            INSERT_SYMBOL_SQL = '''
442
                INSERT INTO Symbol(name, type, threshold, minMatchPoint, isDetectOrigin, rotationCount, ocrOption, isContainChild, originalPoint, connectionPoint, baseSymbol, additionalSymbol, isExceptDetect, hasInstrumentLabel) 
443
                VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
444
            '''
445

    
446
            cursor = conn.cursor()
447
            query = ( symbol.getName(), symbol.getType(), symbol.getThreshold()
448
                           , symbol.getMinMatchCount(), symbol.getIsDetectOnOrigin(), symbol.getRotationCount()
449
                           , symbol.getOcrOption(), symbol.getIsContainChild()
450
                           , symbol.getOriginalPoint(), symbol.getConnectionPoint()
451
                           , symbol.getBaseSymbol(), symbol.getAdditionalSymbol(), symbol.getIsExceptDetect(), symbol.getHasInstrumentLabel())
452
            cursor.execute(INSERT_SYMBOL_SQL, query)
453
            conn.commit()
454
            isAdded = True
455
        # Catch the exception
456
        except Exception as ex:
457
            # Roll back any change if something goes wrong
458
            conn.rollback()
459
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
460
        finally:
461
            conn.close()
462
            return (isAdded, symbol.getType(), symbol.getName(), symbol.getPath())
463

    
464
    '''
465
        @brief      Update symbol in Symbol Table, Moved from SG_DbHelper
466
        @author     Jeongwoo
467
        @date       2018.05.03
468
    '''
469
    def updateSymbol(self, symbol):
470
        isUpdated = False
471
        try:
472
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
473
            conn = sqlite3.connect(dbPath)
474
            
475
            UPDATE_SYMBOL_SQL = '''
476
                UPDATE Symbol
477
                SET
478
                    name = ?, type = ?, threshold = ?, minMatchPoint = ?, isDetectOrigin = ?,
479
                    rotationCount = ?, ocrOption = ?, isContainChild = ?, originalPoint = ?, connectionPoint = ?,
480
                    baseSymbol = ?, additionalSymbol = ?, isExceptDetect = ?, hasInstrumentLabel = ?
481
                WHERE uid = ?
482
            '''
483
            
484
            cursor = conn.cursor()
485
            query = (symbol.getName(), symbol.getType(), symbol.getThreshold()
486
                           , symbol.getMinMatchCount(), symbol.getIsDetectOnOrigin(), symbol.getRotationCount()
487
                           , symbol.getOcrOption(), symbol.getIsContainChild()
488
                           , symbol.getOriginalPoint(), symbol.getConnectionPoint()
489
                           , symbol.getBaseSymbol(), symbol.getAdditionalSymbol(), symbol.getIsExceptDetect(), symbol.getHasInstrumentLabel(), symbol.getUid())
490
            cursor.execute(UPDATE_SYMBOL_SQL, query)
491
            conn.commit()
492
            isUpdated = True
493
        # Catch the exception
494
        except Exception as ex:
495
            # Roll back any change if something goes wrong
496
            conn.rollback()
497
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
498
        finally:
499
            conn.close()
500
            return (isUpdated, symbol.getType(), symbol.getName(), symbol.getPath())
501

    
502
    '''
503
        @brief      Get Detecting Target Symbol List (Field 'isExceptDetect' == False(0))
504
        @author     Jeongwoo
505
        @date       18.04.24
506
        @history    humkyung 2018.06.28 select symbol order by threshold descending
507
    '''
508
    def getTargetSymbolList(self):
509
        targetSymbolList = []
510

    
511
        try:
512
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
513

    
514
            conn = sqlite3.connect(dbPath)
515
            cursor = conn.cursor()
516
            sql = 'SELECT * FROM Symbol WHERE isExceptDetect = 0 order by width * height desc'
517
            try:
518
                cursor.execute(sql)
519
                rows = cursor.fetchall()
520
                for row in rows:
521
                    sym = symbol.SymbolBase(row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11], row[12], row[13], row[14], row[0]) ## uid is last item
522
                    targetSymbolList.append(sym)
523
            except Exception as ex:
524
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
525
        finally:
526
            conn.close()
527

    
528
        return targetSymbolList
529

    
530
    '''
531
        @brief  build application database
532
        @author humkyung
533
        @date   2018.04.20
534
    '''
535
    def buildAppDatabase(self):
536
        try:
537
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
538
            appDatabaseFilePath = os.path.join(path, 'App.db')
539

    
540
            # Creates or opens a file called mydb with a SQLite3 DB
541
            conn = sqlite3.connect(appDatabaseFilePath)
542
            # Get a cursor object
543
            cursor = conn.cursor()
544

    
545
            sqlFiles = ['App.Configuration.sql', 'App.Styles.sql']
546
            for sqlFile in sqlFiles:
547
                filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', sqlFile)
548
                try:
549
                    file = QFile(filePath)
550
                    file.open(QFile.ReadOnly)
551
                    sql = file.readAll()
552
                    sql = str(sql, encoding='utf8')
553
                    cursor.executescript(sql)
554
                finally:
555
                    file.close()
556
            conn.commit()
557
        # Catch the exception
558
        except Exception as ex:
559
            # Roll back any change if something goes wrong
560
            conn.rollback()
561
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
562
        finally:
563
            # Close the db connection
564
            conn.close()
565

    
566
    '''
567
        @brief  load app style
568
        @author humkyung
569
        @date   2018.04.20
570
    '''
571
    def loadAppStyle(self):
572
        style = 'Fusion'
573

    
574
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
575
        if not os.path.exists(path): os.makedirs(path)
576

    
577
        self.buildAppDatabase()
578
        try:
579
            appDatabaseFilePath = os.path.join(path, 'App.db')
580
            # Creates or opens a file called mydb with a SQLite3 DB
581
            conn = sqlite3.connect(appDatabaseFilePath)
582
            # Get a cursor object
583
            cursor = conn.cursor()
584

    
585
            sql = "select Value from Configuration where Section='App' and Key='Style'" 
586
            cursor.execute(sql)
587
            rows = cursor.fetchall()
588
            style = rows[0][0] if 1 == len(rows) else 'Fusion'
589
        # Catch the exception
590
        except Exception as ex:
591
            # Roll back any change if something goes wrong
592
            conn.rollback()
593
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
594
        finally:
595
            # Close the db connection
596
            conn.close()
597

    
598
        return style
599

    
600
    '''
601
        @brief  load app styles and then return a list
602
        @author humkyung
603
        @date   2018.04.20
604
    '''
605
    def loadAppStyles(self):
606
        styles = []
607

    
608
        try:
609
            self.buildAppDatabase()
610

    
611
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
612
            appDatabaseFilePath = os.path.join(path, 'App.db')
613

    
614
            # Creates or opens a file called mydb with a SQLite3 DB
615
            conn = sqlite3.connect(appDatabaseFilePath)
616
            # Get a cursor object
617
            cursor = conn.cursor()
618

    
619
            sql = 'select UID,Value from Styles'
620
            cursor.execute(sql)
621
            rows = cursor.fetchall()
622
            for row in rows: styles.append(row[1])
623
            if 0 == len(rows): rows.append('fusion')
624
        # Catch the exception
625
        except Exception as ex:
626
            # Roll back any change if something goes wrong
627
            conn.rollback()
628
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
629
        finally:
630
            # Close the db connection
631
            conn.close()
632

    
633
        return styles
634

    
635
    '''
636
        @brief  Set current Project
637
        @history    2018.06.27  Jeongwoo    If DB file is not, copy DB file from ProgramData
638
    '''
639
    def setCurrentProject(self, project):
640
        self.project = project
641
        self.makeChildDir()
642
        try:
643
            # Creates or opens a file called mydb with a SQLite3 DB
644
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath() , "ITI_PID.db")
645
            
646
            if not os.path.isfile(dbPath):
647
                templatePath = self.getTemplateDbPath()
648
                templateFile = QFile(templatePath)
649
                templateFile.copy(dbPath)
650
            else:
651
                try:
652
                    conn = sqlite3.connect(dbPath)
653
                    # Get a cursor object
654
                    cursor = conn.cursor()
655

    
656
                    fileNames = os.listdir(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts'))
657
                    for fileName in fileNames:
658
                        if fileName.endswith(".sql") and (1 == len(os.path.splitext(fileName)[0].split('.'))):
659
                            try:
660
                                file = QFile(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', fileName))
661
                                file.open(QFile.ReadOnly)
662
                                sql = file.readAll()
663
                                sql = str(sql, encoding='utf8')
664
                                cursor.executescript(sql)
665
                            finally:
666
                                file.close()
667
                    conn.commit()
668
                except Exception as ex:
669
                    print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
670
                finally:
671
                    conn.close()
672
        # Catch the exception
673
        except Exception as ex:
674
            # Roll back any change if something goes wrong
675
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
676
        finally:
677
            pass
678

    
679
    '''
680
        @brief      Make Directory
681
        @author     Jeongwoo
682
        @date       18.05.08
683
        @history    humkyung 2018.06.19 make 'Tile' directory
684
                    humkyung 2018.07.09 make drawing folder if not exists
685
                    euisung 2018.09.28 make training folder if not exists
686
    '''
687
    def makeChildDir(self):
688
        project = AppDocData.instance().getCurrentProject()
689
        dbDir = project.getDbFilePath()
690
        if not os.path.exists(dbDir):
691
            os.makedirs(dbDir)
692
        imgDir = project.getImageFilePath()
693
        if not os.path.exists(imgDir):
694
            os.makedirs(imgDir)
695
        svgDir = project.getSvgFilePath()
696
        if not os.path.exists(svgDir):
697
            os.makedirs(svgDir)
698
        outputDir = project.getOutputPath()
699
        if not os.path.exists(outputDir):
700
            os.makedirs(outputDir)
701
        tempDir = project.getTempPath()
702
        if not os.path.exists(tempDir):
703
            os.makedirs(tempDir)
704
        drawingPath = project.getDrawingFilePath()
705
        if not os.path.exists(drawingPath):
706
            os.makedirs(drawingPath)
707
        trainingPath = project.getTrainingFilePath()
708
        if not os.path.exists(trainingPath):
709
            os.makedirs(trainingPath)
710
        
711
        path = os.path.join(tempDir, 'Tile')
712
        if not os.path.exists(path):
713
            os.makedirs(path)
714

    
715
    '''
716
        @brief  Get current Project
717
    '''
718
    def getCurrentProject(self):
719
        return self.project
720

    
721
    '''
722
        @brief      return project database path
723
        @history    humkyung 2018.04.19 return Project.db in Program Data folder instead of PROJECT_DB_PATH variable
724
    '''
725
    def getPrjDatabasePath(self):
726
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
727
        if not os.path.exists(path): os.makedirs(path)
728

    
729
        prjDatabaseFilePath = os.path.join(path, 'Project.db')
730
        try:
731
            # Creates or opens a file called mydb with a SQLite3 DB
732
            conn = sqlite3.connect(prjDatabaseFilePath)
733
            # Get a cursor object
734
            cursor = conn.cursor()
735

    
736
            filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', 'Project.Projects.sql')
737
            try:
738
                file = QFile(filePath)
739
                file.open(QFile.ReadOnly)
740
                sql = file.readAll()
741
                sql = str(sql, encoding='utf8')
742
                cursor.executescript(sql)
743
            finally:
744
                file.close()
745
            conn.commit()
746
        # Catch the exception
747
        except Exception as ex:
748
            # Roll back any change if something goes wrong
749
            conn.rollback()
750
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
751
        finally:
752
            # Close the db connection
753
            conn.close()
754
        
755
        return prjDatabaseFilePath
756

    
757
    def updateTitleBlockProperties(self, titleBlockProps):
758
        '''
759
            @brief  update title block properties
760
            @author euisung
761
            @date   2018.11.09
762
        '''
763
        try:
764
            originTitleBlockProps = self.getTitleBlockProperties()
765
            deletedTitleBlockProps = []
766
            for originTitleBlockProp in originTitleBlockProps:
767
                for titleBlockProp in titleBlockProps:
768
                    # uid compare for determine delete props
769
                    if originTitleBlockProp[0] == titleBlockProp[0]:
770
                        break
771
                deletedTitleBlockProps.append(originTitleBlockProp[0])
772
            
773
            # Creates or opens a file called mydb with a SQLite3 DB
774
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
775
            conn = sqlite3.connect(dbPath)
776
            # Get a cursor object
777
            cursor = conn.cursor()
778

    
779
            for deletedTitleBlockProp in deletedTitleBlockProps:
780
                sql = "delete from TitleBlockProperties where UID='{}'".format(deletedTitleBlockProp)
781
                cursor.execute(sql)
782

    
783
            for titleBlockProp in titleBlockProps:
784
                sql = "insert or replace into TitleBlockProperties values(?,?,?)"
785
                param = (titleBlockProp[0], titleBlockProp[1], titleBlockProp[2]) # uid, name, area
786
                cursor.execute(sql, param)
787
            conn.commit()
788
        # Catch the exception
789
        except Exception as ex:
790
            # Roll back any change if something goes wrong
791
            conn.rollback()
792
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
793
        finally:
794
            # Close the db connection
795
            conn.close()
796

    
797
        self._titleBlockProperties = None
798
    
799
    def getTitleBlockProperties(self):
800
        '''
801
            @brief  return title block properties
802
            @author euisung
803
            @date   2018.11.09
804
        '''
805
        res = None
806
        if self._titleBlockProperties is None:
807
            try:
808
                self._titleBlockProperties = []
809

    
810
                # Creates or opens a file called mydb with a SQLite3 DB
811
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
812
                db = sqlite3.connect(dbPath)
813
                # Get a cursor object
814
                cursor = db.cursor()
815

    
816
                sql = "select UID, Name, AREA from TitleBlockProperties" 
817
                cursor.execute(sql)
818
                rows = cursor.fetchall()
819
                for row in rows:
820
                    attr = []
821
                    attr.append(row[0]) # uid
822
                    attr.append(row[1]) # name
823
                    attr.append(row[2]) # area
824
                    self._titleBlockProperties.append(attr)
825
                
826
                res = self._titleBlockProperties
827
            # Catch the exception
828
            except Exception as ex:
829
                # Roll back any change if something goes wrong
830
                db.rollback()
831
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
832
            finally:
833
                # Close the db connection
834
                db.close()
835
        else:
836
            res = self._titleBlockProperties
837

    
838
        return res
839

    
840
    '''
841
        @brief  return line properties
842
        @author humkyung
843
        @date   2018.04.09
844
    '''
845
    def getLineProperties(self):
846
        from SymbolAttr import SymbolAttr
847

    
848
        res = None
849
        if self._lineNoProperties is None:
850
            try:
851
                self._lineNoProperties = []
852

    
853
                # Creates or opens a file called mydb with a SQLite3 DB
854
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
855
                db = sqlite3.connect(dbPath)
856
                # Get a cursor object
857
                cursor = db.cursor()
858

    
859
                sql = "select UID, Name, DisplayName, Type, LimitNumber, [index] from LineProperties order by [index]" 
860
                cursor.execute(sql)
861
                rows = cursor.fetchall()
862
                for row in rows:
863
                    attr = SymbolAttr()
864
                    attr.UID = row[0]
865
                    attr.Attribute = row[1]
866
                    attr.DisplayAttribute = row[2]
867
                    attr.AttributeType = row[3]
868
                    attr.Length = row[4]
869
                    self._lineNoProperties.append(attr)
870
                
871
                res = self._lineNoProperties
872
            # Catch the exception
873
            except Exception as ex:
874
                # Roll back any change if something goes wrong
875
                db.rollback()
876
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
877
            finally:
878
                # Close the db connection
879
                db.close()
880
        else:
881
            res = self._lineNoProperties
882

    
883
        return res
884

    
885
    '''
886
        @brief  return line properties
887
        @author humkyung
888
        @date   2018.04.09
889
    '''
890
    def getLinePropertiesByUID(self, UID):
891
        from SymbolAttr import SymbolAttr
892

    
893
        res = []
894
        try:
895
            # Creates or opens a file called mydb with a SQLite3 DB
896
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
897
            db = sqlite3.connect(dbPath)
898
            # Get a cursor object
899
            cursor = db.cursor()
900

    
901
            sql = "select UID, Name, DisplayName, Type, LimitNumber, [index] from LineProperties where uid = '{}'".format(UID)
902
            cursor.execute(sql)
903
            rows = cursor.fetchall()
904
            for row in rows:
905
                attr = SymbolAttr()
906
                attr.UID = row[0]
907
                attr.Attribute = row[1]
908
                attr.DisplayAttribute = row[2]
909
                attr.AttributeType = row[3]
910
                attr.Length = row[4]
911
                res.append(attr)
912
        # Catch the exception
913
        except Exception as ex:
914
            # Roll back any change if something goes wrong
915
            db.rollback()
916
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
917
        finally:
918
            # Close the db connection
919
            db.close()
920

    
921
        return res
922

    
923
    '''
924
        @brief  return line types 
925
        @author humkyung
926
        @date   2018.06.27
927
    '''
928
    def getLineTypes(self):
929
        res = []
930
        try:
931
            # Creates or opens a file called mydb with a SQLite3 DB
932
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
933
            db = sqlite3.connect(dbPath)
934
            # Get a cursor object
935
            cursor = db.cursor()
936

    
937
            sql = "select Name from LineTypes order by Name" 
938
            cursor.execute(sql)
939
            rows = cursor.fetchall()
940
            for row in rows:
941
                res.append(row[0])
942
        # Catch the exception
943
        except Exception as ex:
944
            # Roll back any change if something goes wrong
945
            db.rollback()
946
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
947
        finally:
948
            # Close the db connection
949
            db.close()
950

    
951
        return res
952

    
953
    '''
954
        @brief      Insert New Project Info
955
        @author     Jeongwoo
956
        @date       2018.04.06
957
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
958
    '''
959
    def insertProjectInfo(self, dir):
960
        try:
961
            prjDatabaseFilePath = self.getPrjDatabasePath()
962
            conn = sqlite3.connect(prjDatabaseFilePath)
963
            folderName = dir.split('/')[-1]
964
            if folderName:
965
                nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
966
                sql = "INSERT INTO Projects(Name, Path, CreatedDate, UpdatedDate) VALUES('" + folderName + "', '" + dir + "', '" + nowDate + "', '" + nowDate + "')"
967
                cur = conn.cursor()
968
                cur.execute(sql)
969
                conn.commit()
970
            else:
971
                print("Empty folder name")
972
        except Exception as ex:
973
            # Roll back any change if something goes wrong
974
            conn.rollback()
975
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
976
        finally:
977
            conn.close()
978

    
979
    '''
980
        @brief      Update Project UpdatedDate Field
981
        @author     Jeongwoo
982
        @date       2018.04.06
983
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
984
    '''
985
    def updateProjectUpdatedDate(self, id):
986
        try:
987
            prjDatabaseFilePath = self.getPrjDatabasePath()
988
            conn = sqlite3.connect(prjDatabaseFilePath)
989
            nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
990
            sql = '''
991
                UPDATE Projects
992
                SET UpdatedDate = ?
993
                WHERE Id = ?
994
            '''
995
            cur = conn.cursor()
996
            cur.execute(sql, (nowDate, id))
997
            conn.commit()
998
        except Exception as ex:
999
            # Roll back any change if something goes wrong
1000
            conn.rollback()
1001
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1002
        finally:
1003
            conn.close()
1004

    
1005
    '''
1006
        @brief  get project list from database
1007
        @history    humkyung 2018.04.18 add only project which's project exists
1008
    '''
1009
    def getProjectList(self):
1010
        from Project import Project
1011

    
1012
        projectList = []
1013

    
1014
        try:
1015
            conn = sqlite3.connect(self.getPrjDatabasePath())
1016
            cursor = conn.cursor()
1017
            sql = 'SELECT id,name,path,createddate,updateddate  FROM Projects ORDER BY UpdatedDate DESC'
1018
            try:
1019
                cursor.execute(sql)
1020
                rows = cursor.fetchall()
1021
                for row in rows:
1022
                    if os.path.isdir(row[2]):   # check if folder exists
1023
                        projectList.append(Project(row[0], row[1], row[2], row[3], row[4]))
1024
            except Exception as ex:
1025
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1026
        finally:
1027
            conn.close()
1028

    
1029
        return projectList
1030

    
1031
    '''
1032
        @brief  get sliding window size
1033
        @author humkyung
1034
    '''
1035
    def getSlidingWindowSize(self):
1036
        res = [10,10]
1037
        try:
1038
            configs = self.getConfigs('Sliding Window')
1039
            for config in configs:
1040
                if config.key == 'Width':
1041
                    res[0] = int(config.value)
1042
                elif config.key == 'Height':
1043
                    res[1] = int(config.value)
1044
        # Catch the exception
1045
        except Exception as ex:
1046
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1047
        
1048
        return res
1049

    
1050
    '''
1051
        @brief  get line no configuration
1052
        @author humkyung
1053
        @date   2018.04.16
1054
    '''
1055
    def getLineNoConfiguration(self):
1056
        res = None
1057
        try:
1058
            # Creates or opens a file called mydb with a SQLite3 DB
1059
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1060
            conn = sqlite3.connect(dbPath)
1061
            # Get a cursor object
1062
            cursor = conn.cursor()
1063

    
1064
            delimiter = None
1065
            sql = "select * from configuration where section='Line No' and key='Delimiter"
1066
            cursor.execute(sql)
1067
            rows = cursor.fetchall()
1068
            if len(rows) == 1:
1069
                delimiter = rows[0][2]
1070

    
1071
            if delimiter is not None:
1072
                sql = "select * from configuration where section='Line No' and key='Configuration'"
1073
                cursor.execute(sql)
1074
                rows = cursor.fetchall()
1075
                if len(rows) == 1:
1076
                    res = rows[0][2].split(delimiter)
1077
        # Catch the exception
1078
        except Exception as ex:
1079
            # Roll back any change if something goes wrong
1080
            conn.rollback()
1081
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1082
        finally:
1083
            # Close the db connection
1084
            conn.close()
1085
        
1086
        return res
1087

    
1088
    '''
1089
        @brief  get area list
1090
        @author humkyung
1091
        @history    euisung     2018.11.20 (0,0),(0,0) process add
1092
    '''
1093
    def getAreaList(self):
1094
        from Area import Area
1095

    
1096
        if len(self._areas) == 0:
1097
            try:
1098
                # Creates or opens a file called mydb with a SQLite3 DB
1099
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1100
                conn = sqlite3.connect(dbPath)
1101
                # Get a cursor object
1102
                cursor = conn.cursor()
1103

    
1104
                sql = "select * from configuration where section='Area'"
1105
                cursor.execute(sql)
1106
                rows = cursor.fetchall()
1107
                for row in rows:
1108
                    name = row[1]
1109
                    area = Area(name)
1110
                    area.parse(row[2])
1111
                    self._areas.append(area)
1112
            # Catch the exception
1113
            except Exception as ex:
1114
                # Roll back any change if something goes wrong
1115
                conn.rollback()
1116
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1117
            finally:
1118
                # Close the db connection
1119
                conn.close()
1120
        
1121
        return self._areas 
1122

    
1123
    '''
1124
        @brief  get area of given name
1125
        @author humkyung
1126
        @date   2018.04.07
1127
    '''
1128
    def getArea(self, name):
1129
        areas = self.getAreaList()
1130
        matches = [area for area in areas if area.name==name]
1131
        if 1 == len(matches) and matches[0].height is not 0 and matches[0].width is not 0:
1132
            return matches[0]
1133

    
1134
        return None
1135

    
1136
    '''
1137
        @brief  get configurations
1138
        @author humkyung
1139
        @date   2018.04.16
1140
        @history kyouho 2018.07.09 change query method
1141
    '''
1142
    def getConfigs(self, section, key=None):
1143
        res = []
1144

    
1145
        try:
1146
            # Creates or opens a file called mydb with a SQLite3 DB
1147
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1148
            conn = sqlite3.connect(dbPath)
1149
            # Get a cursor object
1150
            cursor = conn.cursor()
1151

    
1152
            if key is not None:
1153
                sql = "select * from configuration where section=? and key=?"
1154
                param = (section, key)
1155
            else:
1156
                sql = "select * from configuration where section=?"
1157
                param = (section,)
1158

    
1159
            cursor.execute(sql, param)
1160
            rows = cursor.fetchall()
1161
            for row in rows:
1162
                res.append(Config(row[0], row[1], row[2]))
1163
        # Catch the exception
1164
        except Exception as ex:
1165
            # Roll back any change if something goes wrong
1166
            conn.rollback()
1167
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1168
        finally:
1169
            # Close the db connection
1170
            conn.close()
1171

    
1172
        return res
1173

    
1174
    def getAppConfigs(self, section, key=None):
1175
        """
1176
            @brief  get application configurations
1177
            @author humkyung
1178
            @date   2018.11.01
1179
        """
1180

    
1181
        res = []
1182

    
1183
        try:
1184
            # Creates or opens a file called mydb with a SQLite3 DB
1185
            dbPath = self.getAppDbPath()
1186
            conn = sqlite3.connect(dbPath)
1187
            # Get a cursor object
1188
            cursor = conn.cursor()
1189

    
1190
            if key is not None:
1191
                sql = "select * from configuration where section=? and key=?"
1192
                param = (section, key)
1193
            else:
1194
                sql = "select * from configuration where section=?"
1195
                param = (section,)
1196

    
1197
            cursor.execute(sql, param)
1198
            rows = cursor.fetchall()
1199
            for row in rows:
1200
                res.append(Config(row[0], row[1], row[2]))
1201
        # Catch the exception
1202
        except Exception as ex:
1203
            # Roll back any change if something goes wrong
1204
            conn.rollback()
1205
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1206
        finally:
1207
            # Close the db connection
1208
            conn.close()
1209

    
1210
        return res
1211

    
1212
    '''
1213
        @brief      save configurations
1214
        @author     humkyung
1215
        @date       2018.04.16
1216
        @history    humkyung 2018.07.03 replace ' with " if value has '
1217
                    kyouho 2018.07.09 change query method
1218
    '''
1219
    def saveConfigs(self, configs):
1220
        try:
1221
            # Creates or opens a file called mydb with a SQLite3 DB
1222
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
1223
            conn = sqlite3.connect(dbPath)
1224
            # Get a cursor object
1225
            cursor = conn.cursor()
1226

    
1227
            for config in configs:
1228
                value = config.value
1229
                if type(value) is str and "'" in value:
1230
                    value = value.replace("'", "''")
1231

    
1232
                sql = "insert or replace into configuration values(?,?,?)"
1233
                param = (config.section, config.key, value)
1234

    
1235
                cursor.execute(sql, param)
1236
            conn.commit()
1237
        # Catch the exception
1238
        except Exception as ex:
1239
            # Roll back any change if something goes wrong
1240
            conn.rollback()
1241
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1242
        finally:
1243
            # Close the db connection
1244
            conn.close()
1245

    
1246
    def saveAppConfigs(self, configs):
1247
        """
1248
        @brief      save application configurations
1249
        @author     humkyung
1250
        @date       2018.10.01
1251
        """
1252

    
1253
        try:
1254
            # Creates or opens a file called mydb with a SQLite3 DB
1255
            dbPath = self.getAppDbPath()
1256
            conn = sqlite3.connect(dbPath)
1257
            # Get a cursor object
1258
            cursor = conn.cursor()
1259

    
1260
            for config in configs:
1261
                value = config.value
1262
                if type(value) is str and "'" in value:
1263
                    value = value.replace("'", "''")
1264

    
1265
                sql = "insert or replace into configuration values(?,?,?)"
1266
                param = (config.section, config.key, value)
1267

    
1268
                cursor.execute(sql, param)
1269
            conn.commit()
1270
        # Catch the exception
1271
        except Exception as ex:
1272
            # Roll back any change if something goes wrong
1273
            conn.rollback()
1274
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1275
        finally:
1276
            # Close the db connection
1277
            conn.close()
1278

    
1279
    '''
1280
        @brief  delete configurations
1281
        @author humkyung
1282
        @date   2018.06.29
1283
    '''
1284
    def deleteConfigs(self, section, key=None):
1285
        try:
1286
            # Creates or opens a file called mydb with a SQLite3 DB
1287
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
1288
            conn = sqlite3.connect(dbPath)
1289
            # Get a cursor object
1290
            cursor = conn.cursor()
1291

    
1292
            if key is not None:
1293
                sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
1294
            else:
1295
                sql = "delete from configuration where section='{}'".format(section)
1296
            cursor.execute(sql)
1297

    
1298
            conn.commit()
1299
        # Catch the exception
1300
        except Exception as ex:
1301
            # Roll back any change if something goes wrong
1302
            conn.rollback()
1303
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1304
        finally:
1305
            # Close the db connection
1306
            conn.close()
1307

    
1308
    def deleteAppConfigs(self, section, key=None):
1309
        """
1310
        @brief  delete application configurations
1311
        @author humkyung
1312
        @date   2018.11.01
1313
        """
1314

    
1315
        try:
1316
            # Creates or opens a file called mydb with a SQLite3 DB
1317
            dbPath = self.getAppDbPath()
1318
            conn = sqlite3.connect(dbPath)
1319
            # Get a cursor object
1320
            cursor = conn.cursor()
1321

    
1322
            if key is not None:
1323
                sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
1324
            else:
1325
                sql = "delete from configuration where section='{}'".format(section)
1326
            cursor.execute(sql)
1327

    
1328
            conn.commit()
1329
        # Catch the exception
1330
        except Exception as ex:
1331
            # Roll back any change if something goes wrong
1332
            conn.rollback()
1333
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1334
        finally:
1335
            # Close the db connection
1336
            conn.close()
1337

    
1338
    '''
1339
        @brief      set area list
1340
        @history    humkyung 2018.05.18 round area coordinate and dimension before saving
1341
        @history    euisung  2018.11.20 add self._area reset process
1342
    '''
1343
    def setAreaList(self, areas):
1344
        for area in areas:
1345
            matches = [x for x in self._areas if x.name==area.name]
1346
            if 1 == len(matches):
1347
                matches[0].x = area.x
1348
                matches[0].y = area.y
1349
                matches[0].width = area.width
1350
                matches[0].height = area.height
1351
            elif 0 == len(matches):
1352
                self._areas.append(area)
1353

    
1354
        try:
1355
            # Creates or opens a file called mydb with a SQLite3 DB
1356
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
1357
            conn = sqlite3.connect(dbPath)
1358
            # Get a cursor object
1359
            cursor = conn.cursor()
1360

    
1361
            for area in self._areas:
1362
                sql = "insert or replace into configuration values('Area','{}','({},{}),({},{})')".format(area.name, round(area.x), round(area.y), round(area.width), round(area.height))
1363
                cursor.execute(sql)
1364

    
1365
            conn.commit()
1366
        # Catch the exception
1367
        except Exception as ex:
1368
            # Roll back any change if something goes wrong
1369
            conn.rollback()
1370
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1371
        finally:
1372
            # Close the db connection
1373
            self._areas = []
1374
            conn.close()
1375
            
1376
    '''
1377
        @brief  get symbol name list
1378
    '''
1379
    def getSymbolNameList(self):
1380
        symbolNametList = []
1381

    
1382
        try:
1383
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
1384

    
1385
            conn = sqlite3.connect(dbPath)
1386
            cursor = conn.cursor()
1387
            sql = 'SELECT * FROM SymbolName'
1388
            try:
1389
                cursor.execute(sql)
1390
                rows = cursor.fetchall()
1391
                for row in rows:
1392
                    symbolNametList.append(row[2]) # Name String
1393
            except Exception as ex:
1394
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1395
        finally:
1396
            conn.close()
1397

    
1398
        return symbolNametList
1399

    
1400
    '''
1401
        @brief      get symbol name list by symbol Type
1402
        @author     Jeongwoo
1403
        @date       18.04.06
1404
        @history    .
1405
    '''
1406
    def getSymbolNameListByType(self, type):
1407
        symbolNametList = []
1408

    
1409
        try:
1410
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
1411

    
1412
            conn = sqlite3.connect(dbPath)
1413
            cursor = conn.cursor()
1414
            sql = ''
1415
            if type is not None:
1416
                sql = 'SELECT * FROM SymbolName WHERE type = "' + type + '"'
1417
                try:
1418
                    cursor.execute(sql)
1419
                    rows = cursor.fetchall()
1420
                    for row in rows:
1421
                        symbolNametList.append(row[2]) # Name String
1422
                except Exception as ex:
1423
                    print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1424
        finally:
1425
            conn.close()
1426

    
1427
        return symbolNametList
1428

    
1429
    '''
1430
        @brief  delete added symbol data
1431
    '''
1432
    def deleteSymbol(self, fileName):
1433
        ret = False
1434
        try:
1435
            dbPath = self.getCurrentProject().getPath() + "/db/ITI_PID.db"
1436
            conn = sqlite3.connect(dbPath)
1437
            cursor = conn.cursor()
1438
            sql = "DELETE FROM Symbol WHERE name = ?"
1439
            try:
1440
                cursor.execute(sql, (fileName,))
1441
                conn.commit()
1442
                ret = True
1443
            except Exception as ex:
1444
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1445
                ret = False
1446
        finally:
1447
            conn.close()
1448
            return (ret, fileName)
1449
        
1450
    '''
1451
        @brief  get symbol name
1452
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1453
    '''
1454
    def getSymbolByQuery(self, fieldName, param):
1455
        ret = None
1456

    
1457
        try:
1458
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
1459
            conn = sqlite3.connect(dbPath)
1460
            cursor = conn.cursor()
1461
            sql = 'SELECT * FROM Symbol WHERE ' + fieldName + ' = "' + param + '"'
1462
            try:
1463
                cursor.execute(sql)
1464
                rows = cursor.fetchall()
1465
                if rows is not None and len(rows) > 0:
1466
                    symbolTuple = rows[0]
1467
                    ret = symbol.SymbolBase(symbolTuple[1], symbolTuple[2], symbolTuple[3]
1468
                                            , symbolTuple[4], symbolTuple[5], symbolTuple[6], symbolTuple[7], symbolTuple[8]
1469
                                            , symbolTuple[9], symbolTuple[10], symbolTuple[11], symbolTuple[12], symbolTuple[13], symbolTuple[14], symbolTuple[0]) ## uid is last item
1470
                    #ret = symbol.SymbolBase(symbolTuple[1], symbolTuple[2], symbolTuple[3], symbolTuple[4]
1471
                    #                        , symbolTuple[5], symbolTuple[6], symbolTuple[7], symbolTuple[8], symbolTuple[9]
1472
                    #                        , symbolTuple[10], symbolTuple[11], symbolTuple[12], symbolTuple[13], symbolTuple[14], symbolTuple[0]) ## uid is last item
1473
            except Exception as ex:
1474
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1475
        finally:
1476
            conn.close()
1477

    
1478
        return ret
1479

    
1480
    '''
1481
        @brief  get symbol name list
1482
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1483
    '''
1484
    def getSymbolListByQuery(self, fieldName=None, param=None):
1485
        ret = []
1486

    
1487
        try:
1488
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1489
            conn = sqlite3.connect(dbPath)
1490
            cursor = conn.cursor()
1491
            if fieldName is not None and param is not None:
1492
                sql = 'SELECT * FROM Symbol WHERE ' + fieldName + ' = "' + param + '"'
1493
            else:
1494
                sql = 'SELECT * FROM Symbol'
1495
            try:
1496
                cursor.execute(sql)
1497
                rows = cursor.fetchall()
1498
                if rows is not None and len(rows) > 0:
1499
                    for symbolTuple in rows:
1500
                        sym = symbol.SymbolBase(symbolTuple[1], symbolTuple[2], symbolTuple[3], symbolTuple[4]
1501
                                                , symbolTuple[5], symbolTuple[6], symbolTuple[7], symbolTuple[8], symbolTuple[9]
1502
                                                , symbolTuple[10], symbolTuple[11], symbolTuple[12], symbolTuple[13], symbolTuple[14], symbolTuple[0]) ## uid is last item
1503
                        ret.append(sym)
1504
            except Exception as ex:
1505
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1506
        finally:
1507
            conn.close()
1508

    
1509
        return ret
1510

    
1511
    '''
1512
        @brief      get NominalDiameter
1513
        @author     humkyung
1514
        @date       2018.04.20
1515
        @history    humkyung 2018.04.24 read MetricStr column and set size unit
1516
                    kyouho 2018.07.04 forCheckLineNumber get only inch or metric
1517
                    kyouho 2018.07.16 edit query order by code
1518
    '''
1519
    def getNomialPipeSizeData(self, forCheckLineNumber = False, orderStr = "CODE"):
1520
        res = []
1521
        try:
1522
            configs = self.getConfigs('Line No', 'Size Unit')
1523
            sizeUnit = configs[0].value if 1 == len(configs) else 'Metric'
1524

    
1525
            # Creates or opens a file called mydb with a SQLite3 DB
1526
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1527
            conn = sqlite3.connect(dbPath)
1528
            # Get a cursor object
1529
            cursor = conn.cursor()
1530

    
1531
            sql = "select Code,Metric,Inch,InchStr,MetricStr from NominalDiameter ORDER BY {} ASC".format(orderStr)
1532
            cursor.execute(sql)
1533
            rows = cursor.fetchall()
1534
            for row in rows:
1535
                pipeSize = NominalPipeSize(row[0], float(row[1]) if row[1] is not None else None, float(row[2]) if row[2] is not None else None, row[3], row[4])
1536
                pipeSize.sizeUnit = sizeUnit
1537
                if forCheckLineNumber:
1538
                    if sizeUnit == 'Inch' and pipeSize.inchStr:
1539
                        res.append(pipeSize.inchStr)
1540
                    elif sizeUnit == 'Metric' and pipeSize.metricStr:
1541
                        res.append(pipeSize.metricStr)
1542
                else:
1543
                    res.append(pipeSize)
1544
                
1545
        # Catch the exception
1546
        except Exception as ex:
1547
            # Roll back any change if something goes wrong
1548
            conn.rollback()
1549
            
1550
            from App import App 
1551
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1552
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1553
        finally:
1554
            # Close the db connection
1555
            conn.close()
1556

    
1557
        return res
1558

    
1559
    '''
1560
        @brief      insert NominalDiameter table
1561
        @author     kyouho
1562
        @date       2018.07.16
1563
    '''
1564
    def insertNomialPipeSize(self, pipeSizes):
1565
        try:
1566
            # Creates or opens a file called mydb with a SQLite3 DB
1567
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1568
            conn = sqlite3.connect(dbPath)
1569
            # Get a cursor object
1570
            cursor = conn.cursor()
1571
            sql = "INSERT INTO NominalDiameter(Code, Metric, Inch, InchStr, MetricStr) VALUES(?,?,?,?,?)"
1572
            for pipeSize in pipeSizes:
1573
                param = (pipeSize.code, pipeSize.metric, pipeSize.inch, pipeSize.inchStr, pipeSize.metricStr)
1574
                cursor.execute(sql, param)
1575
            conn.commit()
1576
            # Catch the exception
1577
        except Exception as ex:
1578
            # Roll back any change if something goes wrong
1579
            conn.rollback()
1580
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1581
        finally:
1582
            # Close the db connection
1583
            conn.close()
1584

    
1585

    
1586
    '''
1587
        @brief      delete NominalDiameter table
1588
        @author     kyouho
1589
        @date       2018.07.16
1590
    '''
1591
    def deleteNomialPipeSize(self):
1592
        try:
1593
            dbPath = os.path.join(self.getCurrentProject().getPath(), 'db', 'ITI_PID.db')
1594
            conn = sqlite3.connect(dbPath)
1595
            cursor = conn.cursor()
1596
            sql = "DELETE FROM NominalDiameter"
1597
            try:
1598
                cursor.execute(sql)
1599
                conn.commit()
1600
            except Exception as ex:
1601
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1602
        finally:
1603
            conn.close()
1604

    
1605
    '''
1606
        @brief      convert inch to metric
1607
        @author     kyouho
1608
        @date       2018.07.09
1609
    '''
1610
    def convertInchToMetric(self, inch):
1611
        result = ''
1612
        try:
1613
            # Creates or opens a file called mydb with a SQLite3 DB
1614
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1615
            conn = sqlite3.connect(dbPath)
1616
            # Get a cursor object
1617
            cursor = conn.cursor()
1618
            
1619
            sql = "select MetricStr from NominalDiameter WHERE InchStr = ?"
1620
            param = (inch,)
1621
            cursor.execute(sql, param)
1622
            rows = cursor.fetchall()
1623

    
1624
            if rows:
1625
                result = rows[0][0]
1626
            # Catch the exception
1627
        except Exception as ex:
1628
            # Roll back any change if something goes wrong
1629
            conn.rollback()
1630
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1631
        finally:
1632
            # Close the db connection
1633
            conn.close()
1634

    
1635
        return result
1636

    
1637
    '''
1638
        @brief      get Color MaxUID
1639
        @author     kyouho
1640
        @date       2018.07.03
1641
    '''
1642
    def getMaxColorUID(self):
1643
        result = 0
1644

    
1645
        try:
1646
            # Creates or opens a file called mydb with a SQLite3 DB
1647
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1648
            conn = sqlite3.connect(dbPath)
1649
            # Get a cursor object
1650
            cursor = conn.cursor()
1651

    
1652
            sql = "select MAX(UID) from Colors"
1653
            cursor.execute(sql)
1654
            rows = cursor.fetchall()
1655

    
1656
            result = rows[0][0]
1657
            # Catch the exception
1658
        except Exception as ex:
1659
            # Roll back any change if something goes wrong
1660
            conn.rollback()
1661
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1662
        finally:
1663
            # Close the db connection
1664
            conn.close()
1665

    
1666
        return result
1667

    
1668
    '''
1669
        @brief      insert Color property
1670
        @author     kyouho
1671
        @date       2018.07.09
1672
    '''
1673
    def setPropertyColor(self, _color):
1674
        try:
1675
            # Creates or opens a file called mydb with a SQLite3 DB
1676
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1677
            conn = sqlite3.connect(dbPath)
1678
            # Get a cursor object
1679
            cursor = conn.cursor()
1680
            sql = "INSERT INTO Colors(UID, RED, GREEN, BLUE, PROPERTY, VALUE) VALUES(?,?,?,?,?,?)"
1681
            param = (_color.index, _color.red, _color.green, _color.blue, _color._property, _color.value)
1682
            cursor.execute(sql, param)
1683
            conn.commit()
1684
            # Catch the exception
1685
        except Exception as ex:
1686
            # Roll back any change if something goes wrong
1687
            conn.rollback()
1688
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1689
        finally:
1690
            # Close the db connection
1691
            conn.close()
1692

    
1693
    '''
1694
        @brief      delete Color property
1695
        @author     kyouho
1696
        @date       2018.07.09
1697
    '''
1698
    def deletePropertyColor(self, property):
1699
        try:
1700
            # Creates or opens a file called mydb with a SQLite3 DB
1701
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1702
            conn = sqlite3.connect(dbPath)
1703
            # Get a cursor object
1704
            cursor = conn.cursor()
1705

    
1706
            sql = "DELETE FROM Colors WHERE PROPERTY = '{}'".format(property)
1707
            cursor.execute(sql)
1708
            conn.commit()
1709
            # Catch the exception
1710
        except Exception as ex:
1711
            # Roll back any change if something goes wrong
1712
            conn.rollback()
1713
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1714
        finally:
1715
            # Close the db connection
1716
            conn.close()
1717

    
1718
    '''
1719
        @brief      get Fluid Code
1720
        @author     kyouho
1721
        @date       2018.07.03
1722
        @history    kyouho 2018.07.04 kyouho 2018.07.04 forCheckLineNumber get only code
1723
    '''
1724
    def getFluidCodeData(self, forCheckLineNumber = False):
1725
        from FluidCodeData import FluidCodeData
1726
        result = []
1727

    
1728
        try:
1729
            # Creates or opens a file called mydb with a SQLite3 DB
1730
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1731
            conn = sqlite3.connect(dbPath)
1732
            # Get a cursor object
1733
            cursor = conn.cursor()
1734

    
1735
            sql = 'select uid, code, description from FluidCode order by length(code) DESC'
1736
            cursor.execute(sql)
1737
            rows = cursor.fetchall()
1738
            for row in rows:
1739
                data = FluidCodeData(row[0], row[1], row[2])
1740
                if forCheckLineNumber:
1741
                    result.append(data.code)
1742
                else:
1743
                    result.append(data)
1744
            # Catch the exception
1745
        except Exception as ex:
1746
            # Roll back any change if something goes wrong
1747
            conn.rollback()
1748
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1749
        finally:
1750
            # Close the db connection
1751
            conn.close()
1752

    
1753
        return result
1754

    
1755
    '''
1756
        @brief      get Symbol Attribute
1757
        @author     kyouho
1758
        @date       2018.07.18
1759
    '''
1760
    def checkAttribute(self, attr):
1761
        try:
1762
            # Creates or opens a file called mydb with a SQLite3 DB
1763
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1764
            conn = sqlite3.connect(dbPath)
1765
            # Get a cursor object
1766
            cursor = conn.cursor()
1767

    
1768
            sql = 'select UID from SymbolAttribute where UID = ?'
1769
            param = (attr,)
1770
            cursor.execute(sql, param)
1771
            rows = cursor.fetchall()
1772
            if len(rows):
1773
                return True
1774
            else:
1775
                return False
1776
            # Catch the exception
1777
        except Exception as ex:
1778
            # Roll back any change if something goes wrong
1779
            conn.rollback()
1780
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1781
        finally:
1782
            # Close the db connection
1783
            conn.close()
1784

    
1785
        return False
1786

    
1787
    '''
1788
        @brief      get Symbol Attribute
1789
        @author     kyouho
1790
        @date       2018.07.18
1791
        @history    humkyung 2018.10.13 load expression
1792
    '''
1793
    def getSymbolAttribute(self, _type):
1794
        from SymbolAttr import SymbolAttr
1795

    
1796
        result = []
1797

    
1798
        try:
1799
            # Creates or opens a file called mydb with a SQLite3 DB
1800
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1801
            conn = sqlite3.connect(dbPath)
1802
            # Get a cursor object
1803
            cursor = conn.cursor()
1804

    
1805
            sql = 'select a.UID, a.Attribute, a.DisplayAttribute, a.AttributeType, a.[AttrAt], a.[Expression], a.[index] from SymbolAttribute a inner join SymbolType t on a.SymbolType = t.id and t.type = ? order by a.[index]'
1806
            param = (_type,)
1807
            cursor.execute(sql, param)
1808
            rows = cursor.fetchall()
1809
            for row in rows:
1810
                attr = SymbolAttr()
1811
                attr.UID = row[0]
1812
                attr.Attribute = row[1]
1813
                attr.DisplayAttribute = row[2]
1814
                attr.AttributeType = row[3]
1815
                attr.AttrAt = row[4]
1816
                attr.Expression = row[5]
1817
                result.append(attr)
1818
            # Catch the exception
1819
        except Exception as ex:
1820
            from App import App 
1821

    
1822
            # Roll back any change if something goes wrong
1823
            conn.rollback()
1824

    
1825
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1826
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1827
        finally:
1828
            # Close the db connection
1829
            conn.close()
1830

    
1831
        return result
1832

    
1833
    '''
1834
        @brief      get Symbol Attribute by UID
1835
        @author     kyouho
1836
        @date       2018.08.17
1837
        @history    humkyung 2018.10.13 load expression
1838
    '''
1839
    def getSymbolAttributeByUID(self, UID):
1840
        from SymbolAttr import SymbolAttr
1841

    
1842
        res = None
1843

    
1844
        try:
1845
            # Creates or opens a file called mydb with a SQLite3 DB
1846
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1847
            conn = sqlite3.connect(dbPath)
1848
            # Get a cursor object
1849
            cursor = conn.cursor()
1850

    
1851
            sql = 'select Attribute, DisplayAttribute, AttributeType, AttrAt, Expression from SymbolAttribute where uid = "{}"'.format(UID)
1852
            cursor.execute(sql)
1853
            rows = cursor.fetchall()
1854
            if len(rows):
1855
                res = SymbolAttr()
1856
                res.UID = UID
1857
                res.Attribute = rows[0][0]
1858
                res.DisplayAttribute = rows[0][1]
1859
                res.AttributeType = rows[0][2]
1860
                res.AttrAt = rows[0][3]
1861
                res.Expression = rows[0][4]
1862
            # Catch the exception
1863
        except Exception as ex:
1864
            from App import App
1865

    
1866
            # Roll back any change if something goes wrong
1867
            conn.rollback()
1868

    
1869
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1870
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1871
        finally:
1872
            # Close the db connection
1873
            conn.close()
1874

    
1875
        return res
1876

    
1877
    '''
1878
        @brief      save symbol attributes
1879
        @author     humkyung
1880
        @date       2018.08.14
1881
        @history    humkyung 2018.10.13 save expression
1882
    '''
1883
    def saveSymbolAttributes(self, type, attrs):
1884
        try:
1885
            # Creates or opens a file called mydb with a SQLite3 DB
1886
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1887
            conn = sqlite3.connect(dbPath)
1888
            # Get a cursor object
1889
            cursor = conn.cursor()
1890

    
1891
            sql = 'delete from SymbolAttribute where SymbolType = ?'
1892
            param = (type,)
1893
            cursor.execute(sql, param)
1894

    
1895
            for attr in attrs:
1896
                sql = 'insert into SymbolAttribute(UID, SymbolType, Attribute, DisplayAttribute, AttributeType, AttrAt, Expression, [index]) values(?, ?, ?, ?, ?, ?, ?, ?)'
1897
                attr.insert(1, type)
1898
                param = tuple(attr)
1899
                cursor.execute(sql, param)
1900

    
1901
            conn.commit()
1902
            # Catch the exception
1903
        except Exception as ex:
1904
            # Roll back any change if something goes wrong
1905
            conn.rollback()
1906
            
1907
            from App import App 
1908
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1909
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1910
        finally:
1911
            # Close the db connection
1912
            conn.close()
1913

    
1914
    '''
1915
        @brief      save symbol attributes
1916
        @author     humkyung
1917
        @date       2018.08.14
1918
    '''
1919
    def saveLineAttributes(self, attrs):
1920
        try:
1921
            # Creates or opens a file called mydb with a SQLite3 DB
1922
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1923
            conn = sqlite3.connect(dbPath)
1924
            # Get a cursor object
1925
            cursor = conn.cursor()
1926

    
1927
            sql = 'delete from LineProperties'
1928
            cursor.execute(sql)
1929

    
1930
            for attr in attrs:
1931
                sql = 'insert into LineProperties(UID, Name, DisplayName, Type, LimitNumber, [index]) values(?, ?, ?, ?, ?, ?)'
1932
                param = tuple(attr)
1933
                cursor.execute(sql, param)
1934

    
1935
            conn.commit()
1936

    
1937
            self._lineNoProperties = None
1938
            # Catch the exception
1939
        except Exception as ex:
1940
            # Roll back any change if something goes wrong
1941
            conn.rollback()
1942
            
1943
            from App import App 
1944
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1945
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1946
        finally:
1947
            # Close the db connection
1948
            conn.close()
1949

    
1950
    '''
1951
        @brief      get symbol type id
1952
        @author     kyouho
1953
        @date       2018.08.17
1954
    '''
1955
    def getSymbolTypeId(self, symbolType):
1956
        result = []
1957

    
1958
        try:
1959
            # Creates or opens a file called mydb with a SQLite3 DB
1960
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1961
            conn = sqlite3.connect(dbPath)
1962
            # Get a cursor object
1963
            cursor = conn.cursor()
1964

    
1965
            sql = 'select id from SymbolType where type = ?'
1966
            param = (symbolType,)
1967
            cursor.execute(sql, param)
1968
            rows = cursor.fetchall()
1969
            
1970
            if len(rows):
1971
                result = rows[0][0]
1972
            else:
1973
                result = -1
1974
            # Catch the exception
1975
        except Exception as ex:
1976
            # Roll back any change if something goes wrong
1977
            conn.rollback()
1978
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1979
        finally:
1980
            # Close the db connection
1981
            conn.close()
1982

    
1983
        return result
1984

    
1985
    '''
1986
        @brief      get Code Table Data
1987
        @author     kyouho
1988
        @date       2018.07.10
1989
    '''
1990
    def getCodeTable(self, property, forCheckLineNumber = False):
1991
        result = []
1992
        try:
1993
            # Creates or opens a file called mydb with a SQLite3 DB
1994
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1995
            conn = sqlite3.connect(dbPath)
1996
            # Get a cursor object
1997
            cursor = conn.cursor()
1998

    
1999
            if property.upper().replace(' ','') == "NOMINALDIAMETER" and forCheckLineNumber:
2000
                sql = 'select InchStr, MetricStr from [{}] order by Metric ASC'.format(property)
2001
                cursor.execute(sql)
2002
                rows = cursor.fetchall()
2003
                for index in range(2):
2004
                    for row in rows:
2005
                        if row[index] != '' and result.count(row[index].replace("'", '"')) == 0:
2006
                            result.append(row[index].replace("'", '"'))
2007
            else:
2008
                sql = 'select uid, code, description, Allowables from [{}] order by length(code) DESC'.format(property)
2009
                cursor.execute(sql)
2010
                rows = cursor.fetchall()
2011
                for row in rows:
2012
                    if forCheckLineNumber:
2013
                        data = row[1]
2014
                    else:
2015
                        data = (row[0], row[1], row[2], row[3])
2016
                    result.append(data)
2017
            # Catch the exception
2018
        except Exception as ex:
2019
            # Roll back any change if something goes wrong
2020
            conn.rollback()
2021
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2022
        finally:
2023
            # Close the db connection
2024
            conn.close()
2025

    
2026
        return result
2027

    
2028
    '''
2029
        @brief      Set Common Code Data
2030
        @author     kyouho
2031
        @date       2018.07.12
2032
    '''
2033
    def saveCommonCodeData(self, tableName, datas):
2034
        try:
2035
            # Creates or opens a file called mydb with a SQLite3 DB
2036
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2037
            conn = sqlite3.connect(dbPath)
2038
            # Get a cursor object
2039
            cursor = conn.cursor()
2040

    
2041
            for data in datas:
2042
                uid = data[0]
2043
                if not uid:
2044
                    sql = "insert or replace into {}(UID, CODE, DESCRIPTION, ALLOWABLES) values(lower(hex(randomblob(16))), ?, ?, ?)".format(tableName)
2045
                    param = (data[1], data[2], data[3])
2046
                else:
2047
                    sql = "update {} SET CODE=?, DESCRIPTION=?, ALLOWABLES=? WHERE UID = ?".format(tableName)
2048
                    param = (data[1], data[2], data[3], data[0])
2049
                cursor.execute(sql, param)
2050

    
2051
            conn.commit()
2052
        
2053
        # Catch the exception
2054
        except Exception as ex:
2055
            # Roll back any change if something goes wrong
2056
            conn.rollback()
2057
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2058
        finally:
2059
            # Close the db connection
2060
            conn.close()
2061

    
2062
    '''
2063
        @brief      Set Common Code Data
2064
        @author     kyouho
2065
        @date       2018.07.12
2066
    '''
2067
    def deleteCommonCodeData(self, datas):
2068
        try:
2069
            # Creates or opens a file called mydb with a SQLite3 DB
2070
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2071
            conn = sqlite3.connect(dbPath)
2072
            # Get a cursor object
2073
            cursor = conn.cursor()
2074

    
2075
            for data in datas:
2076
                uid = data[0]
2077
                tableName = data[1]
2078

    
2079
                if uid:
2080
                    sql = "delete from {} where UID = ?".format(tableName)
2081
                    param = (uid,)
2082
                    cursor.execute(sql, param)
2083

    
2084
                cursor.execute(sql, param)
2085

    
2086
            conn.commit()
2087
        
2088
        # Catch the exception
2089
        except Exception as ex:
2090
            # Roll back any change if something goes wrong
2091
            conn.rollback()
2092
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2093
        finally:
2094
            # Close the db connection
2095
            conn.close()
2096

    
2097
    '''
2098
        @brief      delete data list
2099
        @author     kyouho
2100
        @date       2018.08.16
2101
    '''
2102
    def deleteDataList(self, tableName, UID):
2103
        try:
2104
            # Creates or opens a file called mydb with a SQLite3 DB
2105
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2106
            conn = sqlite3.connect(dbPath)
2107
            # Get a cursor object
2108
            cursor = conn.cursor()
2109

    
2110
            sql = 'delete from {} where UID = {}'.format(tableName, UID)
2111
            
2112
            cursor.execute(sql)
2113

    
2114
            conn.commit()
2115

    
2116
        # Catch the exception
2117
        except Exception as ex:
2118
            # Roll back any change if something goes wrong
2119
            conn.rollback()
2120
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2121
        finally:
2122
            # Close the db connection
2123
            conn.close()
2124

    
2125
    '''
2126
        @brief      get line documentName list
2127
        @author     kyouho
2128
        @date       2018.08.13
2129
    '''
2130
    def getLineDocumentNameList(self):
2131
        result = []
2132

    
2133
        try:
2134
            # Creates or opens a file called mydb with a SQLite3 DB
2135
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2136
            conn = sqlite3.connect(dbPath)
2137
            # Get a cursor object
2138
            cursor = conn.cursor()
2139

    
2140
            sql = 'select DISTINCT(PNID_NO) from LINE_DATA_LIST'
2141

    
2142
            cursor.execute(sql)
2143
            rows = cursor.fetchall()
2144
            for row in rows:
2145
                result.append(row[0])
2146
        # Catch the exception
2147
        except Exception as ex:
2148
            # Roll back any change if something goes wrong
2149
            conn.rollback()
2150
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2151
        finally:
2152
            # Close the db connection
2153
            conn.close()
2154

    
2155
        return result
2156

    
2157
    '''
2158
        @brief      get line documentName list
2159
        @author     kyouho
2160
        @date       2018.08.14
2161
    '''
2162
    def getEquipDocumentNameList(self):
2163
        result = []
2164

    
2165
        try:
2166
            # Creates or opens a file called mydb with a SQLite3 DB
2167
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2168
            conn = sqlite3.connect(dbPath)
2169
            # Get a cursor object
2170
            cursor = conn.cursor()
2171

    
2172
            sql = 'select DISTINCT(PNID_NO) from EQUIPMENT_DATA_LIST'
2173

    
2174
            cursor.execute(sql)
2175
            rows = cursor.fetchall()
2176
            for row in rows:
2177
                result.append(row[0])
2178
        # Catch the exception
2179
        except Exception as ex:
2180
            # Roll back any change if something goes wrong
2181
            conn.rollback()
2182
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2183
        finally:
2184
            # Close the db connection
2185
            conn.close()
2186

    
2187
        return result
2188

    
2189

    
2190
    '''
2191
        @brief      get line data list
2192
        @author     kyouho
2193
        @date       2018.08.13
2194
    '''
2195
    def getLineDataList(self, docName = None):
2196
        result = []
2197

    
2198
        try:
2199
            # Creates or opens a file called mydb with a SQLite3 DB
2200
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2201
            conn = sqlite3.connect(dbPath)
2202
            # Get a cursor object
2203
            cursor = conn.cursor()
2204

    
2205
            sql = 'select 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 from LINE_DATA_LIST'
2206
            if docName is not None:
2207
                sql += " where PNID_NO = '{}'".format(docName)
2208

    
2209
            cursor.execute(sql)
2210
            #columnName = list(map(lambda x: x[0].upper(), cursor.description))
2211
            rows = cursor.fetchall()
2212
            for row in rows:
2213
                data = []
2214
                for index in range(len(cursor.description)):
2215
                    data.append(row[index])
2216
                result.append(data)
2217
        # Catch the exception
2218
        except Exception as ex:
2219
            # Roll back any change if something goes wrong
2220
            conn.rollback()
2221
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2222
        finally:
2223
            # Close the db connection
2224
            conn.close()
2225

    
2226
        return result
2227

    
2228
    '''
2229
        @brief      set line data list
2230
        @author     kyouho
2231
        @date       2018.08.13
2232
    '''
2233
    def setLineDataList(self, dataLists):
2234
        try:
2235
            # Creates or opens a file called mydb with a SQLite3 DB
2236
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2237
            conn = sqlite3.connect(dbPath)
2238
            # Get a cursor object
2239
            cursor = conn.cursor()
2240
            
2241
            for data in dataLists:
2242
                sql = "insert or replace 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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2243
                param = tuple(data)
2244
                cursor.execute(sql, param)
2245

    
2246
            conn.commit()
2247

    
2248
        # Catch the exception
2249
        except Exception as ex:
2250
            # Roll back any change if something goes wrong
2251
            conn.rollback()
2252
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2253
        finally:
2254
            # Close the db connection
2255
            conn.close()
2256

    
2257
    '''
2258
        @brief      delete line data list
2259
        @author     kyouho
2260
        @date       2018.08.13
2261
    '''
2262
    def deleteLineDataList(self, removeUID):
2263
        try:
2264
            # Creates or opens a file called mydb with a SQLite3 DB
2265
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2266
            conn = sqlite3.connect(dbPath)
2267
            # Get a cursor object
2268
            cursor = conn.cursor()
2269
            
2270
            for uid in removeUID:
2271
                sql = "delete from LINE_DATA_LIST where uid = '{}'".format(uid)
2272
                cursor.execute(sql)
2273

    
2274
            conn.commit()
2275

    
2276
        # Catch the exception
2277
        except Exception as ex:
2278
            # Roll back any change if something goes wrong
2279
            conn.rollback()
2280
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2281
        finally:
2282
            # Close the db connection
2283
            conn.close()
2284

    
2285
    '''
2286
        @brief      delete line data list
2287
        @author     kyouho
2288
        @date       2018.08.13
2289
    '''
2290
    def deleteLineDataList_LineNo(self, removeUID):
2291
        try:
2292
            # Creates or opens a file called mydb with a SQLite3 DB
2293
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2294
            conn = sqlite3.connect(dbPath)
2295
            # Get a cursor object
2296
            cursor = conn.cursor()
2297
            
2298
            for uid in removeUID:
2299
                sql = "delete from LINE_DATA_LIST where LINE_NO = ?"
2300
                param = (uid,)
2301
                cursor.execute(sql, param)
2302

    
2303
            conn.commit()
2304

    
2305
        # Catch the exception
2306
        except Exception as ex:
2307
            # Roll back any change if something goes wrong
2308
            conn.rollback()
2309
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2310
        finally:
2311
            # Close the db connection
2312
            conn.close()
2313

    
2314
    '''
2315
        @brief      delete equip data list
2316
        @author     kyouho
2317
        @date       2018.08.14
2318
    '''
2319
    def deleteEquipDataList(self, removeUID):
2320
        try:
2321
            # Creates or opens a file called mydb with a SQLite3 DB
2322
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2323
            conn = sqlite3.connect(dbPath)
2324
            # Get a cursor object
2325
            cursor = conn.cursor()
2326
            
2327
            for uid in removeUID:
2328
                sql = "delete from EQUIPMENT_DATA_LIST where uid = '{}'".format(uid)
2329
                cursor.execute(sql)
2330

    
2331
            conn.commit()
2332

    
2333
        # Catch the exception
2334
        except Exception as ex:
2335
            # Roll back any change if something goes wrong
2336
            conn.rollback()
2337
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2338
        finally:
2339
            # Close the db connection
2340
            conn.close()
2341

    
2342
    '''
2343
        @brief      delete inst data list
2344
        @author     kyouho
2345
        @date       2018.08.14
2346
    '''
2347
    def deleteInstDataList(self, removeUID):
2348
        try:
2349
            # Creates or opens a file called mydb with a SQLite3 DB
2350
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2351
            conn = sqlite3.connect(dbPath)
2352
            # Get a cursor object
2353
            cursor = conn.cursor()
2354
            
2355
            for uid in removeUID:
2356
                sql = "delete from INSTRUMENT_DATA_LIST where uid = '{}'".format(uid)
2357
                cursor.execute(sql)
2358

    
2359
            conn.commit()
2360

    
2361
        # Catch the exception
2362
        except Exception as ex:
2363
            # Roll back any change if something goes wrong
2364
            conn.rollback()
2365
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2366
        finally:
2367
            # Close the db connection
2368
            conn.close()
2369

    
2370
    '''
2371
        @brief      delete note data list
2372
        @author     kyouho
2373
        @date       2018.10.10
2374
    '''
2375
    def deleteNoteDataList(self, removeUID):
2376
        try:
2377
            # Creates or opens a file called mydb with a SQLite3 DB
2378
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2379
            conn = sqlite3.connect(dbPath)
2380
            # Get a cursor object
2381
            cursor = conn.cursor()
2382
            
2383
            for uid in removeUID:
2384
                sql = "delete from NOTE_DATA_LIST where uid = '{}'".format(uid)
2385
                cursor.execute(sql)
2386

    
2387
            conn.commit()
2388

    
2389
        # Catch the exception
2390
        except Exception as ex:
2391
            # Roll back any change if something goes wrong
2392
            conn.rollback()
2393
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2394
        finally:
2395
            # Close the db connection
2396
            conn.close()
2397

    
2398
    '''
2399
        @brief      get equipment data list
2400
        @author     humkyung
2401
        @date       2018.05.03
2402
    '''
2403
    def getEquipmentDataList(self, docName = None):
2404
        result = []
2405
        try:
2406
            # Creates or opens a file called mydb with a SQLite3 DB
2407
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2408
            conn = sqlite3.connect(dbPath)
2409
            # Get a cursor object
2410
            cursor = conn.cursor()
2411

    
2412
            sql = 'select 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 from EQUIPMENT_DATA_LIST'
2413
            if docName is not None:
2414
                sql += " where PNID_NO = '{}'".format(docName)
2415

    
2416
            cursor.execute(sql)
2417
            rows = cursor.fetchall()
2418
            for row in rows:
2419
                data = []
2420
                for index in range(len(cursor.description)): 
2421
                    data.append(row[index])
2422
                result.append(data)
2423
        # Catch the exception
2424
        except Exception as ex:
2425
            from App import App 
2426

    
2427
            # Roll back any change if something goes wrong
2428
            conn.rollback()
2429
            
2430
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2431
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2432
        finally:
2433
            # Close the db connection
2434
            conn.close()
2435

    
2436
        return result
2437

    
2438
    def get_valve_data_list(self, docName = None):
2439
        """
2440
        @brief      get valve data list
2441
        @author     humkyung
2442
        @date       2018.10.11
2443
        """
2444

    
2445
        result = []
2446
        try:
2447
            # Creates or opens a file called mydb with a SQLite3 DB
2448
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2449
            conn = sqlite3.connect(dbPath)
2450
            # Get a cursor object
2451
            cursor = conn.cursor()
2452

    
2453
            sql = 'select UID, ITEM_NO, PNID_NO from VALVE_DATA_LIST'
2454
            if docName is not None:
2455
                sql += " where PNID_NO = '{}'".format(docName)
2456

    
2457
            cursor.execute(sql)
2458
            rows = cursor.fetchall()
2459
            for row in rows:
2460
                data = []
2461
                for index in range(len(cursor.description)): 
2462
                    data.append(row[index])
2463
                result.append(data)
2464
        # Catch the exception
2465
        except Exception as ex:
2466
            from App import App 
2467

    
2468
            # Roll back any change if something goes wrong
2469
            conn.rollback()
2470
            
2471
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2472
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2473
        finally:
2474
            # Close the db connection
2475
            conn.close()
2476

    
2477
        return result
2478

    
2479
    '''
2480
        @brief      get instrument data list
2481
        @author     kyouho
2482
        @date       2018.08.14
2483
    '''
2484
    def getInstrumentDataList(self, docName = None):
2485
        result = []
2486
        try:
2487
            # Creates or opens a file called mydb with a SQLite3 DB
2488
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2489
            conn = sqlite3.connect(dbPath)
2490
            # Get a cursor object
2491
            cursor = conn.cursor()
2492

    
2493
            sql = 'select UID, ITEM_NO, SERVICE, FLOW_RATE, PRESSURE, TEMPERATURE, TYPE, RANGE, NOR_LEVEL_MM, NOR_LEVEL_PERCENT, DEL_PRESS, SHUT_OFF, LOCATION, PNID_NO, REV from INSTRUMENT_DATA_LIST'
2494
            if docName is not None:
2495
                sql += " where PNID_NO = '{}'".format(docName)
2496

    
2497
            cursor.execute(sql)
2498
            rows = cursor.fetchall()
2499
            for row in rows:
2500
                data = []
2501
                for index in range(len(cursor.description)): 
2502
                    data.append(row[index])
2503
                result.append(data)
2504
        # Catch the exception
2505
        except Exception as ex:
2506
            # Roll back any change if something goes wrong
2507
            conn.rollback()
2508
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2509
        finally:
2510
            # Close the db connection
2511
            conn.close()
2512

    
2513
        return result
2514

    
2515
    '''
2516
        @brief      get Note data list
2517
        @author     kyouho
2518
        @date       2018.10.10
2519
    '''
2520
    def getNoteDataList(self, docName = None):
2521
        result = []
2522
        try:
2523
            # Creates or opens a file called mydb with a SQLite3 DB
2524
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2525
            conn = sqlite3.connect(dbPath)
2526
            # Get a cursor object
2527
            cursor = conn.cursor()
2528

    
2529
            sql = 'select UID, NOTE_NO, DESCRIPTION, PNID_NO from NOTE_DATA_LIST'
2530
            if docName is not None:
2531
                sql += " where PNID_NO = '{}'".format(docName)
2532

    
2533
            cursor.execute(sql)
2534
            rows = cursor.fetchall()
2535
            for row in rows:
2536
                data = []
2537
                for index in range(len(cursor.description)): 
2538
                    data.append(row[index])
2539
                result.append(data)
2540
        # Catch the exception
2541
        except Exception as ex:
2542
            # Roll back any change if something goes wrong
2543
            conn.rollback()
2544
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2545
        finally:
2546
            # Close the db connection
2547
            conn.close()
2548

    
2549
        return result
2550

    
2551
    def saveToDatabase(self, items):
2552
        """
2553
        save given items to database
2554
        """
2555
        try:
2556
            # Creates or opens a file called mydb with a SQLite3 DB
2557
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2558
            conn = sqlite3.connect(dbPath)
2559
            # Get a cursor object
2560
            cursor = conn.cursor()
2561

    
2562
            for item in items:
2563
                sql = item.toSql()
2564
                if type(sql) is list:
2565
                    for item in sql:
2566
                        if item is not None and 2 == len(item):
2567
                            cursor.execute(item[0], item[1])
2568
                else:
2569
                    if sql is not None and 2 == len(sql):
2570
                        cursor.execute(sql[0], sql[1])
2571

    
2572
            conn.commit()
2573
        # Catch the exception
2574
        except Exception as ex:
2575
            # Roll back any change if something goes wrong
2576
            conn.rollback()
2577
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2578
        finally:
2579
            # Close the db connection
2580
            conn.close()
2581

    
2582
    '''
2583
        @brief      set equipment data list
2584
        @author     humkyung
2585
        @date       2018.05.03
2586
    '''
2587
    def setEquipmentDataList(self, dataList):
2588
        try:
2589
            # Creates or opens a file called mydb with a SQLite3 DB
2590
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2591
            conn = sqlite3.connect(dbPath)
2592
            # Get a cursor object
2593
            cursor = conn.cursor()
2594

    
2595
            for data in dataList:
2596
                sql = "insert or replace 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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2597
                param = tuple(data)
2598
                cursor.execute(sql, param)
2599
            conn.commit()
2600
        # Catch the exception
2601
        except Exception as ex:
2602
            # Roll back any change if something goes wrong
2603
            conn.rollback()
2604
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2605
        finally:
2606
            # Close the db connection
2607
            conn.close()
2608

    
2609
    '''
2610
        @brief      set instrumnet data list
2611
        @author     kyoyho
2612
        @date       2018.08.14
2613
    '''
2614
    def setInstrumentDataList(self, dataList):
2615
        try:
2616
            # Creates or opens a file called mydb with a SQLite3 DB
2617
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2618
            conn = sqlite3.connect(dbPath)
2619
            # Get a cursor object
2620
            cursor = conn.cursor()
2621

    
2622
            for data in dataList:
2623
                sql = "insert or replace 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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2624
                param = tuple(data)
2625
                cursor.execute(sql, param)
2626
            conn.commit()
2627

    
2628
        # Catch the exception
2629
        except Exception as ex:
2630
            # Roll back any change if something goes wrong
2631
            conn.rollback()
2632
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2633
        finally:
2634
            # Close the db connection
2635
            conn.close()
2636

    
2637
    '''
2638
        @brief      set Note data list
2639
        @author     kyoyho
2640
        @date       2018.10.10
2641
    '''
2642
    def setNoteDataList(self, dataList):
2643
        try:
2644
            # Creates or opens a file called mydb with a SQLite3 DB
2645
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2646
            conn = sqlite3.connect(dbPath)
2647
            # Get a cursor object
2648
            cursor = conn.cursor()
2649

    
2650
            for data in dataList:
2651
                sql = "insert or replace into NOTE_DATA_LIST(UID, NOTE_NO, DESCRIPTION, PNID_NO) values(?, ?, ?, ?)"
2652
                param = tuple(data)
2653
                cursor.execute(sql, param)
2654
            conn.commit()
2655

    
2656
        # Catch the exception
2657
        except Exception as ex:
2658
            # Roll back any change if something goes wrong
2659
            conn.rollback()
2660
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2661
        finally:
2662
            # Close the db connection
2663
            conn.close()
2664

    
2665
    def getDrawings(self):
2666
        """
2667
        @brief      get drawings
2668
        @author     humkyung
2669
        @date       2018.11.03
2670
        """
2671

    
2672
        res = []
2673
        try:
2674
            # Creates or opens a file called mydb with a SQLite3 DB
2675
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2676
            conn = sqlite3.connect(dbPath)
2677
            # Get a cursor object
2678
            cursor = conn.cursor()
2679

    
2680
            sql = 'select UID,[NAME],[DATETIME] from Drawings'
2681
            cursor.execute(sql)
2682
            rows = cursor.fetchall()
2683
            for row in rows:
2684
                res.append([row[0], row[1], row[2]])
2685

    
2686
        # Catch the exception
2687
        except Exception as ex:
2688
            # Roll back any change if something goes wrong
2689
            conn.rollback()
2690
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2691
        finally:
2692
            # Close the db connection
2693
            conn.close()
2694

    
2695
        return res
2696

    
2697
    def saveDrawings(self, drawings):
2698
        """
2699
        @brief      save drawings
2700
        @author     humkyung
2701
        @date       2018.11.03
2702
        """
2703

    
2704
        try:
2705
            # Creates or opens a file called mydb with a SQLite3 DB
2706
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2707
            conn = sqlite3.connect(dbPath)
2708
            # Get a cursor object
2709
            cursor = conn.cursor()
2710

    
2711
            for drawing in drawings:
2712
                if not drawing[0]:
2713
                    sql = 'insert or replace into Drawings(UID, [NAME], [DATETIME]) values(lower(hex(randomblob(16))), ?, ?)'
2714
                    param = tuple([drawing[1], ''])
2715
                else:
2716
                    sql = 'insert or replace into Drawings(UID, [NAME], [DATETIME]) values(?, ?, ?)'
2717
                    param = tuple(drawing)
2718

    
2719
                cursor.execute(sql, param)
2720
            conn.commit()
2721

    
2722
        # Catch the exception
2723
        except Exception as ex:
2724
            # Roll back any change if something goes wrong
2725
            conn.rollback()
2726
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2727
        finally:
2728
            # Close the db connection
2729
            conn.close()
2730

    
2731
    '''
2732
        @brief  get IsOriginDetect ComboBox Items
2733
    '''
2734
    def getIsOriginDetectComboBoxItems(self):
2735
        return [("원본 도면", 0), ("텍스트 제거 도면", 1)]
2736

    
2737
    '''
2738
        @brief  get IsOriginDetect ComboBox Items
2739
    '''
2740
    def getOcrOptionComboBoxItems(self):
2741
        return [("OCR 미적용", 0), ("일반 심볼", 1), ("Instrument 계통", 2)]
2742
    
2743
    '''
2744
        @brief      Return Symbol Type Items
2745
        @author     Jeongwoo
2746
        @date       18.04.20
2747
        @history    18.05.08    Jeongwoo type index changed
2748
    '''
2749
    def getSymbolTypeList(self):
2750
        symbolTypeList = []
2751

    
2752
        try:
2753
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2754

    
2755
            conn = sqlite3.connect(dbPath)
2756
            cursor = conn.cursor()
2757
            sql = 'SELECT * FROM SymbolType ORDER BY type ASC'
2758
            try:
2759
                cursor.execute(sql)
2760
                rows = cursor.fetchall()
2761
                for row in rows:
2762
                    symbolTypeList.append((row[0], row[1], row[2])) # UID, category, type
2763
            except Exception as ex:
2764
                from App import App
2765

    
2766
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2767
                App.mainWin().addMessage(MessageType.Error, message)
2768
        finally:
2769
            conn.close()
2770

    
2771
        return symbolTypeList
2772

    
2773
    '''
2774
        @brief      Get Symbol Category by Symbol Type
2775
        @author     Jeongwoo
2776
        @date       2018.05.09
2777
    '''
2778
    def getSymbolCategoryByType(self, type):
2779
        category = None
2780
        try:
2781
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
2782
            conn = sqlite3.connect(dbPath)
2783
            cursor = conn.cursor()
2784
            sql = 'SELECT category FROM SymbolType WHERE type = "' + type + '"'
2785
            cursor.execute(sql)
2786
            rows = cursor.fetchall()
2787
            if rows is not None and len(rows) > 0:
2788
                category = rows[0][0]
2789
        except Exception as ex:
2790
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2791
        finally:
2792
            conn.close()
2793

    
2794
        return category
2795

    
2796
    '''
2797
        @brief      Check Symbol Type is included in 'Equipment' Category
2798
        @author     Jeongwoo
2799
        @date       2018.05.09
2800
    '''
2801
    def isEquipmentType(self, type):
2802
        category = self.getSymbolCategoryByType(type)
2803
        return (category is not None and category == 'Equipment')
2804

    
2805
    '''
2806
        @brief      Return Symbol Type Items with "None"
2807
        @author     Jeongwoo
2808
        @date       18.04.06
2809
        @history    Seperate SymbolTypeList and "None"
2810
    '''
2811
    def getSymbolTypeComboBoxItems(self):
2812
        symbolTypeList = self.getSymbolTypeList()
2813
        symbolTypeList.insert(0, ('None', 'None', 'None'))
2814

    
2815
        return symbolTypeList
2816

    
2817
    '''
2818
        @brief  get Base Symbol ComboBox Items
2819
    '''
2820
    def getBaseSymbolComboBoxItems(self, type = None):
2821
        bsymbolNameList = self.getSymbolNameListByType(type)
2822
        bsymbolNameList.sort()
2823
        bsymbolNameList.insert(0, "None")
2824
        return bsymbolNameList
2825

    
2826
    '''
2827
        @brief  get Additional Symbol ComboBox Items
2828
    '''
2829
    def getAdditionalSymbolComboBoxItems(self):
2830
        asymbolNameList = self.getSymbolNameList()
2831
        asymbolNameList.sort()
2832
        asymbolNameList.insert(0, "None")
2833
        return asymbolNameList
2834

    
2835
    '''
2836
        @brief  get Additional Symbol's default direction ComboBox Items
2837
    '''
2838
    def getDefaultSymbolDirectionComboBoxItems(self):
2839
        return [("UP", 0), ("DOWN", 2), ("LEFT", 3), ("RIGHT", 1)]
2840
    
2841
    '''
2842
        @brief  getter of activeDrawing
2843
        @author humkyung
2844
        @date   2018.07.07
2845
    '''
2846
    @property
2847
    def activeDrawing(self):
2848
        return self._activeDrawing
2849

    
2850
    '''
2851
        @brief  setter of activeDrawing
2852
        @author humkyung
2853
        @date   2018.07.07
2854
    '''
2855
    @activeDrawing.setter
2856
    def activeDrawing(self, value):
2857
        self._activeDrawing = value
2858

    
2859
    '''
2860
        @brief      delete data list before save
2861
        @author     euisung
2862
        @date       2018.11.05
2863
    '''
2864
    def deleteDataListBeforeSave(self):
2865
        try:
2866
            # Creates or opens a file called mydb with a SQLite3 DB
2867
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2868
            conn = sqlite3.connect(dbPath)
2869
            # Get a cursor object
2870
            cursor = conn.cursor()
2871
            pidNo = self.activeDrawing.name
2872
            sql = "delete from LINE_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2873
            cursor.execute(sql)
2874
            sql = "delete from EQUIPMENT_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2875
            cursor.execute(sql)
2876
            sql = "delete from VALVE_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2877
            cursor.execute(sql)
2878
            sql = "delete from INSTRUMENT_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2879
            cursor.execute(sql)
2880
            sql = "delete from NOTE_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2881
            cursor.execute(sql)
2882
            sql = "delete from TitleBlockValues where Drawings_UID = '{}'".format(pidNo)
2883
            cursor.execute(sql)
2884

    
2885
            conn.commit()
2886

    
2887
        # Catch the exception
2888
        except Exception as ex:
2889
            # Roll back any change if something goes wrong
2890
            conn.rollback()
2891
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2892
        finally:
2893
            # Close the db connection
2894
            conn.close()
2895

    
2896
    def getColNames(self, table):
2897
        """
2898
        return column names of given table
2899
        """
2900
        res = None
2901
        try:
2902
            # Creates or opens a file called mydb with a SQLite3 DB
2903
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2904
            conn = sqlite3.connect(dbPath)
2905
            cursor = conn.execute('select * from {}'.format(table))
2906
            res = [col_name[0] for col_name in cursor.description]
2907
        # Catch the exception
2908
        except Exception as ex:
2909
            # Roll back any change if something goes wrong
2910
            conn.rollback()
2911
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2912
        finally:
2913
            # Close the db connection
2914
            conn.close()
2915

    
2916
        return res
2917

    
2918
    '''
2919
        @brief  getter of OCRData
2920
        @author humkyung
2921
        @date   2018.11.19
2922
    '''
2923
    @property
2924
    def OCRData(self):
2925
        if self._OCRData is None:
2926
            configs = self.getConfigs('Text Recognition', 'OCR Data')
2927
            self._OCRData = configs[0].value if 1 == len(configs) else 'eng'
2928

    
2929
        return self._OCRData
2930

    
2931
    '''
2932
        @brief  setter of OCRData
2933
        @author humkyung
2934
        @date   2018.11.19
2935
    '''
2936
    @OCRData.setter
2937
    def OCRData(self, value):
2938
        self._OCRData = value
클립보드 이미지 추가 (최대 크기: 500 MB)