프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / DTI_PID / AppDocData.py @ 4ad6dd88

이력 | 보기 | 이력해설 | 다운로드 (110 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.tracerLineNos = []
110
        self.lineIndicators = []
111
        self._colors = None
112
        self._lineNoProperties = None
113
        self._lineTypes = None
114
        self._lineTypeConfigs = None
115
        self._activeDrawing = None
116
        self._hmbTable = None
117
        self._titleBlockProperties = None
118
        self.needReOpening = None
119

    
120

    
121
    def clearItemList(self, trim):
122
        '''
123
            @brief      clear item list
124
            @author     euisung
125
            @date       2018.11.28
126
        '''
127
        self.equipments.clear()
128
        self.symbols.clear()
129
        self.lineNos.clear()
130
        self.texts.clear()
131
        self.lines.clear()
132
        self.unknowns.clear()
133
        self.allItems.clear()
134
        self.lineIndicators.clear()
135
        if trim:
136
            self.tracerLineNos.clear()
137

    
138
    '''
139
        @brief      clear
140
        @author     humkyung
141
        @date       2018.09.06
142
    '''
143
    def clear(self):
144
        self._imgFilePath = None
145
        self.imgName = None
146
        self.imgWidth = 0
147
        self.imgHeight = 0
148
        self._imgSrc = None
149

    
150
        self._areas.clear()
151
        self.equipments.clear()
152
        self.lineNos.clear()
153
        self.lines.clear()
154
        self.texts.clear()
155
        self.symbols.clear()
156
        self.unknowns.clear()
157
        self.allItems.clear()
158
        self.tracerLineNos.clear()
159
        self.lineIndicators.clear()
160
        self._colors = None
161
        self._lineNoProperties = None
162
        self._lineTypes = None
163
        self._lineTypeConfigs = None
164
        self._activeDrawing = None
165
        self._hmbTable = None
166
        self._titleBlockProperties = None
167

    
168
    '''
169
        @brief      Get drawing file list
170
        @author     euisung
171
        @date       2018.09.28
172
    '''
173
    def getDrawingFileList(self):
174
        try:
175
            project = AppDocData.instance().getCurrentProject()
176
            path = project.getDrawingFilePath()
177
            drawingFileList = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f)) and (os.path.splitext(f)[0] == '.png' or os.path.splitext(f)[0] == '.jpg')]
178
            drawingFileList.sort()
179
        except Exception as ex:
180
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
181

    
182
        return drawingFileList
183

    
184
    '''
185
        @brief      Get Training file list
186
        @author     euisung
187
        @date       2018.10.16
188
    '''
189
    def getTrainingFileList(self):
190
        try:
191
            project = AppDocData.instance().getCurrentProject()
192
            path = project.getTrainingFilePath()
193
            drawingFileList = os.listdir(path)
194
            drawingFileList.sort()
195
        except Exception as ex:
196
            from App import App 
197
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
198
            App.mainWnd().addMessage.emit(MessageType.Error, message)
199

    
200
        return drawingFileList
201

    
202
    '''
203
        @brief      Get DB file path in ProgramData
204
        @author     Jeongwoo
205
        @date       2018.06.27
206
        @history    2018.06.29  Jeongwoo    Change method to get template db path
207
    '''
208
    def getTemplateDbPath(self):
209
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
210
        templateDbPath = os.path.join(path, 'Template.db')
211
        return templateDbPath
212

    
213
    def getAppDbPath(self):
214
        """
215
        @brief      Get application DB file path in ProgramData
216
        @author     humkyung
217
        @date       2018.10.01
218
        """
219

    
220
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
221
        app_database = os.path.join(path, 'App.db')
222
        return app_database 
223

    
224
    '''
225
        @brief  getter of colors 
226
        @author humkyung
227
        @date   2018.06.18
228
    '''
229
    @property
230
    def colors(self):
231
        if self._colors is None:
232
            self._colors = []
233
            try:
234
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath() , 'ITI_PID.db')
235

    
236
                conn = sqlite3.connect(dbPath)
237
                cursor = conn.cursor()
238
                sql = 'SELECT UID,RED,GREEN,BLUE FROM Colors'
239
                cursor.execute(sql)
240
                rows = cursor.fetchall()
241
                for row in rows:
242
                    self._colors.append(Color(int(row[0]), int(row[1]), int(row[2]), int(row[3])))
243
            # Catch the exception
244
            except Exception as ex:
245
                # Roll back any change if something goes wrong
246
                conn.rollback()
247

    
248
                from App import App 
249
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
250
                App.mainWnd().addMessage.emit(MessageType.Error, message)
251
            finally:
252
                conn.close()
253

    
254
        return self._colors
255

    
256
    '''
257
        @brief  setter of colors
258
        @author humkyung
259
        @date   2018.06.18
260
    '''
261
    @colors.setter
262
    def colors(self, value):
263
        self._colors = value
264

    
265
    '''
266
        @brief      set image file path
267
        @author     humkyung
268
        @date       2018.07.30
269
    '''
270
    def setImgFilePath(self, path):
271
        self._imgFilePath = path
272
        self.imgName = os.path.splitext(os.path.basename(self._imgFilePath))[0]
273

    
274
    '''
275
        @brief      getter of imgSrc
276
        @author     humkyung
277
        @date       2018.07.30
278
    '''
279
    @property
280
    def imgSrc(self):
281
        import cv2
282

    
283
        if self._imgSrc is None and self._imgFilePath is not None and os.path.isfile(self._imgFilePath):
284
            self._imgSrc = cv2.cvtColor(cv2.imread(self._imgFilePath), cv2.COLOR_BGR2GRAY)
285
            #blur = cv2.GaussianBlur(self._imgSrc , (5,5),0)
286
            self._imgSrc = cv2.threshold(self._imgSrc, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
287
        
288
        return self._imgSrc
289

    
290
    '''
291
        @brief      setter of imgSrc
292
        @author     humkyung
293
        @date       2018.07.30
294
    '''
295
    @imgSrc.setter
296
    def imgSrc(self, value):
297
        self._imgSrc = value
298

    
299
    '''
300
        @brief      reset imgSrc
301
        @author     humkyung
302
        @date       2018.07.30
303
    '''
304
    def resetImgSrc(self):
305
        self._imgSrc = None
306

    
307
    '''
308
        @brief  getter of line type configs
309
        @author humkyung
310
        @date   2018.06.28
311
    '''
312
    @property
313
    def lineTypeConfigs(self):
314
        from PyQt5.QtCore import Qt
315

    
316
        if self._lineTypeConfigs is None:
317
            self._lineTypeConfigs = []
318

    
319
            styleMap = [('SolidLine', Qt.SolidLine), ('DashLine', Qt.DashLine), ('DotLine', Qt.DotLine), ('DashDotLine', Qt.DashDotLine), 
320
                ('DashDotDotLine', Qt.DashDotDotLine), ('CustomDashLine', Qt.CustomDashLine)]
321

    
322
            configs = self.getConfigs('LineTypes')
323
            for config in configs:
324
                width, _style = config.value.split(',')
325
                matches = [param for param in styleMap if param[0] == _style]
326
                style = matches[0][1] if matches else Qt.SolidLine
327
                self._lineTypeConfigs.append((config.key, int(width), style))
328
        
329
        return self._lineTypeConfigs
330

    
331
    '''
332
        @brief  setter of line type configs
333
        @author humkyung
334
        @date   2018.06.28
335
    '''
336
    @lineTypeConfigs.setter
337
    def lineTypeConfigs(self, value):
338
        self._lineTypeConfigs = value
339

    
340
    '''
341
        @brief      getter of hmb table
342
        @author     humkyung
343
        @date       2018.07.16
344
    '''
345
    @property
346
    def hmbTable(self):
347
        from HMBTable import HMBTable
348

    
349
        if self._hmbTable is None:
350
            self._hmbTable = HMBTable()
351
            self._hmbTable.loadData()
352
        
353
        return self._hmbTable
354

    
355
    '''
356
        @brief      setter of hmb table
357
        @author     humkyung
358
        @date       2018.07.16
359
    '''
360
    @hmbTable.setter
361
    def hmbTable(self, value):
362
        self._hmbTable = value
363

    
364
    '''
365
        @brief  get line type config of given line type
366
        @author humkyung
367
        @date   2018.06.28
368
    '''
369
    def getLineTypeConfig(self, lineType):
370
        from PyQt5.QtCore import Qt
371

    
372
        matches = [config for config in self.lineTypeConfigs if config[0] == lineType]
373
        return matches[0] if matches else (lineType, 5, Qt.SolidLine)        
374

    
375
    def setCurrentPidSource(self, image):
376
        self.imgWidth, self.imgHeight = image.size
377

    
378
        self.currentPidSource = Source(image)
379

    
380
    def getCurrentPidSource(self):
381
        return self.currentPidSource
382

    
383
    '''
384
        @brief      Check if Exist data or not, Moved from SG_DbHelper
385
        @author     Jeongwoo
386
        @date       2018.05.03
387
    '''
388
    def isExistData(self, fieldName, data):
389
        rows = None
390
        try:
391
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
392

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

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

    
440
    '''
441
        @brief      Insert new symbol into Symbol Table, Moved from SG_DbHelper
442
        @author     Jeongwoo
443
        @date       2018.05.03
444
    '''
445
    def insertSymbol(self, symbol):
446
        isAdded = False
447
        try:
448
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
449
            conn = sqlite3.connect(dbPath)
450
            
451
            INSERT_SYMBOL_SQL = '''
452
                INSERT INTO Symbol(name, type, threshold, minMatchPoint, isDetectOrigin, rotationCount, ocrOption, isContainChild, originalPoint, connectionPoint, baseSymbol, additionalSymbol, isExceptDetect, hasInstrumentLabel, width, height) 
453
                VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
454
            '''
455

    
456
            cursor = conn.cursor()
457
            query = ( symbol.getName(), symbol.getType(), symbol.getThreshold()
458
                           , symbol.getMinMatchCount(), symbol.getIsDetectOnOrigin(), symbol.getRotationCount()
459
                           , symbol.getOcrOption(), symbol.getIsContainChild()
460
                           , symbol.getOriginalPoint(), symbol.getConnectionPoint()
461
                           , symbol.getBaseSymbol(), symbol.getAdditionalSymbol(), symbol.getIsExceptDetect(), symbol.getHasInstrumentLabel()
462
                           , symbol.width, symbol.height)
463
            cursor.execute(INSERT_SYMBOL_SQL, query)
464
            conn.commit()
465
            isAdded = True
466
        # Catch the exception
467
        except Exception as ex:
468
            # Roll back any change if something goes wrong
469
            conn.rollback()
470
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
471
        finally:
472
            conn.close()
473
            return (isAdded, symbol.getType(), symbol.getName(), symbol.getPath())
474

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

    
513
    '''
514
        @brief      Get Detecting Target Symbol List (Field 'isExceptDetect' == False(0))
515
        @author     Jeongwoo
516
        @date       18.04.24
517
        @history    humkyung 2018.06.28 select symbol order by threshold descending
518
    '''
519
    def getTargetSymbolList(self):
520
        targetSymbolList = []
521

    
522
        try:
523
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
524

    
525
            conn = sqlite3.connect(dbPath)
526
            cursor = conn.cursor()
527
            sql = 'SELECT * FROM Symbol WHERE isExceptDetect = 0 order by width * height desc'
528
            try:
529
                cursor.execute(sql)
530
                rows = cursor.fetchall()
531
                for row in rows:
532
                    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
533
                    targetSymbolList.append(sym)
534
            except Exception as ex:
535
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
536
        finally:
537
            conn.close()
538

    
539
        return targetSymbolList
540

    
541
    '''
542
        @brief  build application database
543
        @author humkyung
544
        @date   2018.04.20
545
    '''
546
    def buildAppDatabase(self):
547
        try:
548
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
549
            appDatabaseFilePath = os.path.join(path, 'App.db')
550

    
551
            # Creates or opens a file called mydb with a SQLite3 DB
552
            conn = sqlite3.connect(appDatabaseFilePath)
553
            # Get a cursor object
554
            cursor = conn.cursor()
555

    
556
            sqlFiles = ['App.Configuration.sql', 'App.Styles.sql']
557
            for sqlFile in sqlFiles:
558
                filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', sqlFile)
559
                try:
560
                    file = QFile(filePath)
561
                    file.open(QFile.ReadOnly)
562
                    sql = file.readAll()
563
                    sql = str(sql, encoding='utf8')
564
                    cursor.executescript(sql)
565
                finally:
566
                    file.close()
567
            conn.commit()
568
        # Catch the exception
569
        except Exception as ex:
570
            # Roll back any change if something goes wrong
571
            conn.rollback()
572
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
573
        finally:
574
            # Close the db connection
575
            conn.close()
576

    
577
    '''
578
        @brief  load app style
579
        @author humkyung
580
        @date   2018.04.20
581
    '''
582
    def loadAppStyle(self):
583
        style = 'Fusion'
584

    
585
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
586
        if not os.path.exists(path): os.makedirs(path)
587

    
588
        self.buildAppDatabase()
589
        try:
590
            appDatabaseFilePath = os.path.join(path, 'App.db')
591
            # Creates or opens a file called mydb with a SQLite3 DB
592
            conn = sqlite3.connect(appDatabaseFilePath)
593
            # Get a cursor object
594
            cursor = conn.cursor()
595

    
596
            sql = "select Value from Configuration where Section='App' and Key='Style'" 
597
            cursor.execute(sql)
598
            rows = cursor.fetchall()
599
            style = rows[0][0] if 1 == len(rows) else 'Fusion'
600
        # Catch the exception
601
        except Exception as ex:
602
            # Roll back any change if something goes wrong
603
            conn.rollback()
604
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
605
        finally:
606
            # Close the db connection
607
            conn.close()
608

    
609
        return style
610

    
611
    '''
612
        @brief  load app styles and then return a list
613
        @author humkyung
614
        @date   2018.04.20
615
    '''
616
    def loadAppStyles(self):
617
        styles = []
618

    
619
        try:
620
            self.buildAppDatabase()
621

    
622
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
623
            appDatabaseFilePath = os.path.join(path, 'App.db')
624

    
625
            # Creates or opens a file called mydb with a SQLite3 DB
626
            conn = sqlite3.connect(appDatabaseFilePath)
627
            # Get a cursor object
628
            cursor = conn.cursor()
629

    
630
            sql = 'select UID,Value from Styles'
631
            cursor.execute(sql)
632
            rows = cursor.fetchall()
633
            for row in rows: styles.append(row[1])
634
            if 0 == len(rows): rows.append('fusion')
635
        # Catch the exception
636
        except Exception as ex:
637
            # Roll back any change if something goes wrong
638
            conn.rollback()
639
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
640
        finally:
641
            # Close the db connection
642
            conn.close()
643

    
644
        return styles
645

    
646
    '''
647
        @brief  Set current Project
648
        @history    2018.06.27  Jeongwoo    If DB file is not, copy DB file from ProgramData
649
    '''
650
    def setCurrentProject(self, project):
651
        self.project = project
652
        self.makeChildDir()
653
        try:
654
            # Creates or opens a file called mydb with a SQLite3 DB
655
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath() , "ITI_PID.db")
656
            
657
            if not os.path.isfile(dbPath):
658
                templatePath = self.getTemplateDbPath()
659
                templateFile = QFile(templatePath)
660
                templateFile.copy(dbPath)
661
            else:
662
                try:
663
                    conn = sqlite3.connect(dbPath)
664
                    # Get a cursor object
665
                    cursor = conn.cursor()
666

    
667
                    fileNames = os.listdir(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts'))
668
                    for fileName in fileNames:
669
                        if fileName.endswith(".sql") and (1 == len(os.path.splitext(fileName)[0].split('.'))):
670
                            try:
671
                                file = QFile(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', fileName))
672
                                file.open(QFile.ReadOnly)
673
                                sql = file.readAll()
674
                                sql = str(sql, encoding='utf8')
675
                                cursor.executescript(sql)
676
                            finally:
677
                                file.close()
678
                    conn.commit()
679
                except Exception as ex:
680
                    print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
681
                finally:
682
                    conn.close()
683
        # Catch the exception
684
        except Exception as ex:
685
            # Roll back any change if something goes wrong
686
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
687
        finally:
688
            pass
689

    
690
    '''
691
        @brief      Make Directory
692
        @author     Jeongwoo
693
        @date       18.05.08
694
        @history    humkyung 2018.06.19 make 'Tile' directory
695
                    humkyung 2018.07.09 make drawing folder if not exists
696
                    euisung 2018.09.28 make training folder if not exists
697
    '''
698
    def makeChildDir(self):
699
        project = AppDocData.instance().getCurrentProject()
700
        dbDir = project.getDbFilePath()
701
        if not os.path.exists(dbDir):
702
            os.makedirs(dbDir)
703
        imgDir = project.getImageFilePath()
704
        if not os.path.exists(imgDir):
705
            os.makedirs(imgDir)
706
        svgDir = project.getSvgFilePath()
707
        if not os.path.exists(svgDir):
708
            os.makedirs(svgDir)
709
        outputDir = project.getOutputPath()
710
        if not os.path.exists(outputDir):
711
            os.makedirs(outputDir)
712
        tempDir = project.getTempPath()
713
        if not os.path.exists(tempDir):
714
            os.makedirs(tempDir)
715
        drawingPath = project.getDrawingFilePath()
716
        if not os.path.exists(drawingPath):
717
            os.makedirs(drawingPath)
718
        trainingPath = project.getTrainingFilePath()
719
        if not os.path.exists(trainingPath):
720
            os.makedirs(trainingPath)
721
        
722
        path = os.path.join(tempDir, 'Tile')
723
        if not os.path.exists(path):
724
            os.makedirs(path)
725

    
726
    '''
727
        @brief  Get current Project
728
    '''
729
    def getCurrentProject(self):
730
        return self.project
731

    
732
    '''
733
        @brief      return project database path
734
        @history    humkyung 2018.04.19 return Project.db in Program Data folder instead of PROJECT_DB_PATH variable
735
    '''
736
    def getPrjDatabasePath(self):
737
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
738
        if not os.path.exists(path): os.makedirs(path)
739

    
740
        prjDatabaseFilePath = os.path.join(path, 'Project.db')
741
        try:
742
            # Creates or opens a file called mydb with a SQLite3 DB
743
            conn = sqlite3.connect(prjDatabaseFilePath)
744
            # Get a cursor object
745
            cursor = conn.cursor()
746

    
747
            filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', 'Project.Projects.sql')
748
            try:
749
                file = QFile(filePath)
750
                file.open(QFile.ReadOnly)
751
                sql = file.readAll()
752
                sql = str(sql, encoding='utf8')
753
                cursor.executescript(sql)
754
            finally:
755
                file.close()
756
            conn.commit()
757
        # Catch the exception
758
        except Exception as ex:
759
            # Roll back any change if something goes wrong
760
            conn.rollback()
761
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
762
        finally:
763
            # Close the db connection
764
            conn.close()
765
        
766
        return prjDatabaseFilePath
767

    
768
    def updateTitleBlockProperties(self, titleBlockProps):
769
        '''
770
            @brief  update title block properties
771
            @author euisung
772
            @date   2018.11.09
773
        '''
774
        try:
775
            for titleBlockProp in titleBlockProps:
776
                titleBlockProp[1] = self.imgName + '!@!' + titleBlockProp[1]
777
            originTitleBlockProps = self.getTitleBlockProperties()
778
            deletedTitleBlockProps = []
779
            for originTitleBlockProp in originTitleBlockProps:
780
                for titleBlockProp in titleBlockProps:
781
                    # uid compare for determine delete props
782
                    if originTitleBlockProp[0] == titleBlockProp[0]:
783
                        break
784
                deletedTitleBlockProps.append(originTitleBlockProp[0])
785
            
786
            # Creates or opens a file called mydb with a SQLite3 DB
787
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
788
            conn = sqlite3.connect(dbPath)
789
            # Get a cursor object
790
            cursor = conn.cursor()
791

    
792
            for deletedTitleBlockProp in deletedTitleBlockProps:
793
                sql = "delete from TitleBlockProperties where UID='{}'".format(deletedTitleBlockProp)
794
                cursor.execute(sql)
795

    
796
            for titleBlockProp in titleBlockProps:
797
                sql = "insert or replace into TitleBlockProperties values(?,?,?)"
798
                param = (titleBlockProp[0], titleBlockProp[1], titleBlockProp[2]) # uid, name, area
799
                cursor.execute(sql, param)
800
            conn.commit()
801
        # Catch the exception
802
        except Exception as ex:
803
            # Roll back any change if something goes wrong
804
            conn.rollback()
805
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
806
        finally:
807
            # Close the db connection
808
            conn.close()
809

    
810
        self._titleBlockProperties = None
811
    
812
    def getTitleBlockProperties(self):
813
        '''
814
            @brief  return title block properties
815
            @author euisung
816
            @date   2018.11.09
817
        '''
818
        res = None
819
        if True:#self._titleBlockProperties is None:
820
            try:
821
                self._titleBlockProperties = []
822

    
823
                # Creates or opens a file called mydb with a SQLite3 DB
824
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
825
                db = sqlite3.connect(dbPath)
826
                # Get a cursor object
827
                cursor = db.cursor()
828

    
829
                sql = "select UID, Name, AREA from TitleBlockProperties" 
830
                cursor.execute(sql)
831
                rows = cursor.fetchall()
832
                for row in rows:
833
                    if row[1].split('!@!')[0] != self.imgName:
834
                        continue
835
                    else:
836
                        attr = []
837
                        attr.append(row[0]) # uid
838
                        attr.append(row[1].split('!@!')[1]) # name
839
                        attr.append(row[2]) # area
840
                        self._titleBlockProperties.append(attr)
841
                
842
                res = self._titleBlockProperties
843
            # Catch the exception
844
            except Exception as ex:
845
                # Roll back any change if something goes wrong
846
                db.rollback()
847
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
848
            finally:
849
                # Close the db connection
850
                db.close()
851
        else:
852
            res = self._titleBlockProperties
853

    
854
        return res
855

    
856
    '''
857
        @brief  return line properties
858
        @author humkyung
859
        @date   2018.04.09
860
    '''
861
    def getLineProperties(self):
862
        from SymbolAttr import SymbolAttr
863

    
864
        res = None
865
        if self._lineNoProperties is None:
866
            try:
867
                self._lineNoProperties = []
868

    
869
                # Creates or opens a file called mydb with a SQLite3 DB
870
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
871
                db = sqlite3.connect(dbPath)
872
                # Get a cursor object
873
                cursor = db.cursor()
874

    
875
                sql = "select UID, Name, DisplayName, Type, LimitNumber, [index] from LineProperties order by [index]" 
876
                cursor.execute(sql)
877
                rows = cursor.fetchall()
878
                for row in rows:
879
                    attr = SymbolAttr()
880
                    attr.UID = row[0]
881
                    attr.Attribute = row[1]
882
                    attr.DisplayAttribute = row[2]
883
                    attr.AttributeType = row[3]
884
                    attr.Length = row[4]
885
                    self._lineNoProperties.append(attr)
886
                
887
                res = self._lineNoProperties
888
            # Catch the exception
889
            except Exception as ex:
890
                # Roll back any change if something goes wrong
891
                db.rollback()
892
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
893
            finally:
894
                # Close the db connection
895
                db.close()
896
        else:
897
            res = self._lineNoProperties
898

    
899
        return res
900

    
901
    '''
902
        @brief  return line properties
903
        @author humkyung
904
        @date   2018.04.09
905
    '''
906
    def getLinePropertiesByUID(self, UID):
907
        from SymbolAttr import SymbolAttr
908

    
909
        res = []
910
        try:
911
            # Creates or opens a file called mydb with a SQLite3 DB
912
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
913
            db = sqlite3.connect(dbPath)
914
            # Get a cursor object
915
            cursor = db.cursor()
916

    
917
            sql = "select UID, Name, DisplayName, Type, LimitNumber, [index] from LineProperties where uid = '{}'".format(UID)
918
            cursor.execute(sql)
919
            rows = cursor.fetchall()
920
            for row in rows:
921
                attr = SymbolAttr()
922
                attr.UID = row[0]
923
                attr.Attribute = row[1]
924
                attr.DisplayAttribute = row[2]
925
                attr.AttributeType = row[3]
926
                attr.Length = row[4]
927
                res.append(attr)
928
        # Catch the exception
929
        except Exception as ex:
930
            # Roll back any change if something goes wrong
931
            db.rollback()
932
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
933
        finally:
934
            # Close the db connection
935
            db.close()
936

    
937
        return res
938

    
939
    '''
940
        @brief  return line types 
941
        @author humkyung
942
        @date   2018.06.27
943
    '''
944
    def getLineTypes(self):
945
        res = []
946
        try:
947
            # Creates or opens a file called mydb with a SQLite3 DB
948
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
949
            db = sqlite3.connect(dbPath)
950
            # Get a cursor object
951
            cursor = db.cursor()
952

    
953
            sql = "select Name from LineTypes order by Name" 
954
            cursor.execute(sql)
955
            rows = cursor.fetchall()
956
            for row in rows:
957
                res.append(row[0])
958
        # Catch the exception
959
        except Exception as ex:
960
            # Roll back any change if something goes wrong
961
            db.rollback()
962
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
963
        finally:
964
            # Close the db connection
965
            db.close()
966

    
967
        return res
968

    
969
    '''
970
        @brief      Insert New Project Info
971
        @author     Jeongwoo
972
        @date       2018.04.06
973
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
974
    '''
975
    def insertProjectInfo(self, dir):
976
        try:
977
            prjDatabaseFilePath = self.getPrjDatabasePath()
978
            conn = sqlite3.connect(prjDatabaseFilePath)
979
            folderName = dir.split('/')[-1]
980
            if folderName:
981
                nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
982
                sql = "INSERT INTO Projects(Name, Path, CreatedDate, UpdatedDate) VALUES('" + folderName + "', '" + dir + "', '" + nowDate + "', '" + nowDate + "')"
983
                cur = conn.cursor()
984
                cur.execute(sql)
985
                conn.commit()
986
            else:
987
                print("Empty folder name")
988
        except Exception as ex:
989
            # Roll back any change if something goes wrong
990
            conn.rollback()
991
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
992
        finally:
993
            conn.close()
994

    
995
    '''
996
        @brief      Update Project UpdatedDate Field
997
        @author     Jeongwoo
998
        @date       2018.04.06
999
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
1000
    '''
1001
    def updateProjectUpdatedDate(self, id):
1002
        try:
1003
            prjDatabaseFilePath = self.getPrjDatabasePath()
1004
            conn = sqlite3.connect(prjDatabaseFilePath)
1005
            nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
1006
            sql = '''
1007
                UPDATE Projects
1008
                SET UpdatedDate = ?
1009
                WHERE Id = ?
1010
            '''
1011
            cur = conn.cursor()
1012
            cur.execute(sql, (nowDate, id))
1013
            conn.commit()
1014
        except Exception as ex:
1015
            # Roll back any change if something goes wrong
1016
            conn.rollback()
1017
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1018
        finally:
1019
            conn.close()
1020

    
1021
    '''
1022
        @brief  get project list from database
1023
        @history    humkyung 2018.04.18 add only project which's project exists
1024
    '''
1025
    def getProjectList(self):
1026
        from Project import Project
1027

    
1028
        projectList = []
1029

    
1030
        try:
1031
            conn = sqlite3.connect(self.getPrjDatabasePath())
1032
            cursor = conn.cursor()
1033
            sql = 'SELECT id,name,path,createddate,updateddate  FROM Projects ORDER BY UpdatedDate DESC'
1034
            try:
1035
                cursor.execute(sql)
1036
                rows = cursor.fetchall()
1037
                for row in rows:
1038
                    if os.path.isdir(row[2]):   # check if folder exists
1039
                        projectList.append(Project(row[0], row[1], row[2], row[3], row[4]))
1040
            except Exception as ex:
1041
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1042
        finally:
1043
            conn.close()
1044

    
1045
        return projectList
1046

    
1047
    '''
1048
        @brief  get sliding window size
1049
        @author humkyung
1050
    '''
1051
    def getSlidingWindowSize(self):
1052
        res = [10,10]
1053
        try:
1054
            configs = self.getConfigs('Sliding Window')
1055
            for config in configs:
1056
                if config.key == 'Width':
1057
                    res[0] = int(config.value)
1058
                elif config.key == 'Height':
1059
                    res[1] = int(config.value)
1060
        # Catch the exception
1061
        except Exception as ex:
1062
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1063
        
1064
        return res
1065

    
1066
    '''
1067
        @brief  get line no configuration
1068
        @author humkyung
1069
        @date   2018.04.16
1070
    '''
1071
    def getLineNoConfiguration(self):
1072
        res = None
1073
        try:
1074
            # Creates or opens a file called mydb with a SQLite3 DB
1075
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1076
            conn = sqlite3.connect(dbPath)
1077
            # Get a cursor object
1078
            cursor = conn.cursor()
1079

    
1080
            delimiter = None
1081
            sql = "select * from configuration where section='Line No' and key='Delimiter"
1082
            cursor.execute(sql)
1083
            rows = cursor.fetchall()
1084
            if len(rows) == 1:
1085
                delimiter = rows[0][2]
1086

    
1087
            if delimiter is not None:
1088
                sql = "select * from configuration where section='Line No' and key='Configuration'"
1089
                cursor.execute(sql)
1090
                rows = cursor.fetchall()
1091
                if len(rows) == 1:
1092
                    res = rows[0][2].split(delimiter)
1093
        # Catch the exception
1094
        except Exception as ex:
1095
            # Roll back any change if something goes wrong
1096
            conn.rollback()
1097
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1098
        finally:
1099
            # Close the db connection
1100
            conn.close()
1101
        
1102
        return res
1103

    
1104
    '''
1105
        @brief  get area list
1106
        @author humkyung
1107
        @history    euisung     2018.11.20 (0,0),(0,0) process add
1108
    '''
1109
    def getAreaList(self):
1110
        from Area import Area
1111

    
1112
        if len(self._areas) == 0:
1113
            try:
1114
                # Creates or opens a file called mydb with a SQLite3 DB
1115
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1116
                conn = sqlite3.connect(dbPath)
1117
                # Get a cursor object
1118
                cursor = conn.cursor()
1119

    
1120
                sql = "select * from configuration where section='Area'"
1121
                cursor.execute(sql)
1122
                rows = cursor.fetchall()
1123
                for row in rows:
1124
                    name = row[1]
1125
                    area = Area(name)
1126
                    area.parse(row[2])
1127
                    self._areas.append(area)
1128
            # Catch the exception
1129
            except Exception as ex:
1130
                # Roll back any change if something goes wrong
1131
                conn.rollback()
1132
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1133
            finally:
1134
                # Close the db connection
1135
                conn.close()
1136
        
1137
        return self._areas 
1138

    
1139
    '''
1140
        @brief  get area of given name
1141
        @author humkyung
1142
        @date   2018.04.07
1143
    '''
1144
    def getArea(self, name):
1145
        areas = self.getAreaList()
1146
        matches = [area for area in areas if area.name==name]
1147
        if 1 == len(matches) and matches[0].height is not 0 and matches[0].width is not 0:
1148
            return matches[0]
1149

    
1150
        return None
1151

    
1152
    '''
1153
        @brief  get configurations
1154
        @author humkyung
1155
        @date   2018.04.16
1156
        @history kyouho 2018.07.09 change query method
1157
    '''
1158
    def getConfigs(self, section, key=None):
1159
        res = []
1160

    
1161
        try:
1162
            # Creates or opens a file called mydb with a SQLite3 DB
1163
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1164
            conn = sqlite3.connect(dbPath)
1165
            # Get a cursor object
1166
            cursor = conn.cursor()
1167

    
1168
            if key is not None:
1169
                sql = "select * from configuration where section=? and key=?"
1170
                param = (section, key)
1171
            else:
1172
                sql = "select * from configuration where section=?"
1173
                param = (section,)
1174

    
1175
            cursor.execute(sql, param)
1176
            rows = cursor.fetchall()
1177
            for row in rows:
1178
                res.append(Config(row[0], row[1], row[2]))
1179
        # Catch the exception
1180
        except Exception as ex:
1181
            # Roll back any change if something goes wrong
1182
            conn.rollback()
1183
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1184
        finally:
1185
            # Close the db connection
1186
            conn.close()
1187

    
1188
        return res
1189

    
1190
    def getAppConfigs(self, section, key=None):
1191
        """
1192
            @brief  get application configurations
1193
            @author humkyung
1194
            @date   2018.11.01
1195
        """
1196

    
1197
        res = []
1198

    
1199
        try:
1200
            # Creates or opens a file called mydb with a SQLite3 DB
1201
            dbPath = self.getAppDbPath()
1202
            conn = sqlite3.connect(dbPath)
1203
            # Get a cursor object
1204
            cursor = conn.cursor()
1205

    
1206
            if key is not None:
1207
                sql = "select * from configuration where section=? and key=?"
1208
                param = (section, key)
1209
            else:
1210
                sql = "select * from configuration where section=?"
1211
                param = (section,)
1212

    
1213
            cursor.execute(sql, param)
1214
            rows = cursor.fetchall()
1215
            for row in rows:
1216
                res.append(Config(row[0], row[1], row[2]))
1217
        # Catch the exception
1218
        except Exception as ex:
1219
            # Roll back any change if something goes wrong
1220
            conn.rollback()
1221
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1222
        finally:
1223
            # Close the db connection
1224
            conn.close()
1225

    
1226
        return res
1227

    
1228
    '''
1229
        @brief      save configurations
1230
        @author     humkyung
1231
        @date       2018.04.16
1232
        @history    humkyung 2018.07.03 replace ' with " if value has '
1233
                    kyouho 2018.07.09 change query method
1234
    '''
1235
    def saveConfigs(self, configs):
1236
        try:
1237
            # Creates or opens a file called mydb with a SQLite3 DB
1238
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
1239
            conn = sqlite3.connect(dbPath)
1240
            # Get a cursor object
1241
            cursor = conn.cursor()
1242

    
1243
            for config in configs:
1244
                value = config.value
1245
                if type(value) is str and "'" in value:
1246
                    value = value.replace("'", "''")
1247

    
1248
                sql = "insert or replace into configuration values(?,?,?)"
1249
                param = (config.section, config.key, value)
1250

    
1251
                cursor.execute(sql, param)
1252
            conn.commit()
1253
        # Catch the exception
1254
        except Exception as ex:
1255
            # Roll back any change if something goes wrong
1256
            conn.rollback()
1257
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1258
        finally:
1259
            # Close the db connection
1260
            conn.close()
1261

    
1262
    def saveAppConfigs(self, configs):
1263
        """
1264
        @brief      save application configurations
1265
        @author     humkyung
1266
        @date       2018.10.01
1267
        """
1268

    
1269
        try:
1270
            # Creates or opens a file called mydb with a SQLite3 DB
1271
            dbPath = self.getAppDbPath()
1272
            conn = sqlite3.connect(dbPath)
1273
            # Get a cursor object
1274
            cursor = conn.cursor()
1275

    
1276
            for config in configs:
1277
                value = config.value
1278
                if type(value) is str and "'" in value:
1279
                    value = value.replace("'", "''")
1280

    
1281
                sql = "insert or replace into configuration values(?,?,?)"
1282
                param = (config.section, config.key, value)
1283

    
1284
                cursor.execute(sql, param)
1285
            conn.commit()
1286
        # Catch the exception
1287
        except Exception as ex:
1288
            # Roll back any change if something goes wrong
1289
            conn.rollback()
1290
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1291
        finally:
1292
            # Close the db connection
1293
            conn.close()
1294

    
1295
    '''
1296
        @brief  delete configurations
1297
        @author humkyung
1298
        @date   2018.06.29
1299
    '''
1300
    def deleteConfigs(self, section, key=None):
1301
        try:
1302
            # Creates or opens a file called mydb with a SQLite3 DB
1303
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
1304
            conn = sqlite3.connect(dbPath)
1305
            # Get a cursor object
1306
            cursor = conn.cursor()
1307

    
1308
            if key is not None:
1309
                sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
1310
            else:
1311
                sql = "delete from configuration where section='{}'".format(section)
1312
            cursor.execute(sql)
1313

    
1314
            conn.commit()
1315
        # Catch the exception
1316
        except Exception as ex:
1317
            # Roll back any change if something goes wrong
1318
            conn.rollback()
1319
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1320
        finally:
1321
            # Close the db connection
1322
            conn.close()
1323

    
1324
    def deleteAppConfigs(self, section, key=None):
1325
        """
1326
        @brief  delete application configurations
1327
        @author humkyung
1328
        @date   2018.11.01
1329
        """
1330

    
1331
        try:
1332
            # Creates or opens a file called mydb with a SQLite3 DB
1333
            dbPath = self.getAppDbPath()
1334
            conn = sqlite3.connect(dbPath)
1335
            # Get a cursor object
1336
            cursor = conn.cursor()
1337

    
1338
            if key is not None:
1339
                sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
1340
            else:
1341
                sql = "delete from configuration where section='{}'".format(section)
1342
            cursor.execute(sql)
1343

    
1344
            conn.commit()
1345
        # Catch the exception
1346
        except Exception as ex:
1347
            # Roll back any change if something goes wrong
1348
            conn.rollback()
1349
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1350
        finally:
1351
            # Close the db connection
1352
            conn.close()
1353

    
1354
    '''
1355
        @brief      set area list
1356
        @history    humkyung 2018.05.18 round area coordinate and dimension before saving
1357
        @history    euisung  2018.11.20 add self._area reset process
1358
    '''
1359
    def setAreaList(self, areas):
1360
        for area in areas:
1361
            matches = [x for x in self._areas if x.name==area.name]
1362
            if 1 == len(matches):
1363
                matches[0].x = area.x
1364
                matches[0].y = area.y
1365
                matches[0].width = area.width
1366
                matches[0].height = area.height
1367
            elif 0 == len(matches):
1368
                self._areas.append(area)
1369

    
1370
        try:
1371
            # Creates or opens a file called mydb with a SQLite3 DB
1372
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
1373
            conn = sqlite3.connect(dbPath)
1374
            # Get a cursor object
1375
            cursor = conn.cursor()
1376

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

    
1381
            conn.commit()
1382
        # Catch the exception
1383
        except Exception as ex:
1384
            # Roll back any change if something goes wrong
1385
            conn.rollback()
1386
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1387
        finally:
1388
            # Close the db connection
1389
            self._areas = []
1390
            conn.close()
1391
            
1392
    '''
1393
        @brief  get symbol name list
1394
    '''
1395
    def getSymbolNameList(self):
1396
        symbolNametList = []
1397

    
1398
        try:
1399
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
1400

    
1401
            conn = sqlite3.connect(dbPath)
1402
            cursor = conn.cursor()
1403
            sql = 'SELECT * FROM SymbolName'
1404
            try:
1405
                cursor.execute(sql)
1406
                rows = cursor.fetchall()
1407
                for row in rows:
1408
                    symbolNametList.append(row[2]) # Name String
1409
            except Exception as ex:
1410
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1411
        finally:
1412
            conn.close()
1413

    
1414
        return symbolNametList
1415

    
1416
    '''
1417
        @brief      get symbol name list by symbol Type
1418
        @author     Jeongwoo
1419
        @date       18.04.06
1420
        @history    .
1421
    '''
1422
    def getSymbolNameListByType(self, type):
1423
        symbolNametList = []
1424

    
1425
        try:
1426
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
1427

    
1428
            conn = sqlite3.connect(dbPath)
1429
            cursor = conn.cursor()
1430
            sql = ''
1431
            if type is not None:
1432
                sql = 'SELECT * FROM SymbolName WHERE type = "' + type + '"'
1433
                try:
1434
                    cursor.execute(sql)
1435
                    rows = cursor.fetchall()
1436
                    for row in rows:
1437
                        symbolNametList.append(row[2]) # Name String
1438
                except Exception as ex:
1439
                    print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1440
        finally:
1441
            conn.close()
1442

    
1443
        return symbolNametList
1444

    
1445
    '''
1446
        @brief  delete added symbol data
1447
    '''
1448
    def deleteSymbol(self, fileName):
1449
        ret = False
1450
        try:
1451
            dbPath = self.getCurrentProject().getPath() + "/db/ITI_PID.db"
1452
            conn = sqlite3.connect(dbPath)
1453
            cursor = conn.cursor()
1454
            sql = "DELETE FROM Symbol WHERE name = ?"
1455
            try:
1456
                cursor.execute(sql, (fileName,))
1457
                conn.commit()
1458
                ret = True
1459
            except Exception as ex:
1460
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1461
                ret = False
1462
        finally:
1463
            conn.close()
1464
            return (ret, fileName)
1465
        
1466
    '''
1467
        @brief  get symbol name
1468
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1469
    '''
1470
    def getSymbolByQuery(self, fieldName, param):
1471
        ret = None
1472

    
1473
        try:
1474
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1475
            conn = sqlite3.connect(dbPath)
1476
            cursor = conn.cursor()
1477
            sql = 'SELECT * FROM Symbol WHERE ' + fieldName + ' = "' + param + '"'
1478
            try:
1479
                cursor.execute(sql)
1480
                rows = cursor.fetchall()
1481
                if rows is not None and len(rows) > 0:
1482
                    symbolTuple = rows[0]
1483
                    ret = symbol.SymbolBase(symbolTuple[1], symbolTuple[2], symbolTuple[3]
1484
                                            , symbolTuple[4], symbolTuple[5], symbolTuple[6], symbolTuple[7], symbolTuple[8]
1485
                                            , symbolTuple[9], symbolTuple[10], symbolTuple[11], symbolTuple[12], symbolTuple[13], symbolTuple[14], symbolTuple[0]) ## uid is last item
1486
                    #ret = symbol.SymbolBase(symbolTuple[1], symbolTuple[2], symbolTuple[3], symbolTuple[4]
1487
                    #                        , symbolTuple[5], symbolTuple[6], symbolTuple[7], symbolTuple[8], symbolTuple[9]
1488
                    #                        , symbolTuple[10], symbolTuple[11], symbolTuple[12], symbolTuple[13], symbolTuple[14], symbolTuple[0]) ## uid is last item
1489
            except Exception as ex:
1490
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1491
        finally:
1492
            conn.close()
1493

    
1494
        return ret
1495

    
1496
    '''
1497
        @brief  get symbol name list
1498
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1499
    '''
1500
    def getSymbolListByQuery(self, fieldName=None, param=None):
1501
        ret = []
1502

    
1503
        try:
1504
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1505
            conn = sqlite3.connect(dbPath)
1506
            cursor = conn.cursor()
1507
            if fieldName is not None and param is not None:
1508
                sql = 'SELECT * FROM Symbol WHERE ' + fieldName + ' = "' + param + '"'
1509
            else:
1510
                sql = 'SELECT * FROM Symbol'
1511
            try:
1512
                cursor.execute(sql)
1513
                rows = cursor.fetchall()
1514
                if rows is not None and len(rows) > 0:
1515
                    for symbolTuple in rows:
1516
                        sym = symbol.SymbolBase(symbolTuple[1], symbolTuple[2], symbolTuple[3], symbolTuple[4]
1517
                                                , symbolTuple[5], symbolTuple[6], symbolTuple[7], symbolTuple[8], symbolTuple[9]
1518
                                                , symbolTuple[10], symbolTuple[11], symbolTuple[12], symbolTuple[13], symbolTuple[14], symbolTuple[0]) ## uid is last item
1519
                        ret.append(sym)
1520
            except Exception as ex:
1521
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1522
        finally:
1523
            conn.close()
1524

    
1525
        return ret
1526

    
1527
    '''
1528
        @brief      get NominalDiameter
1529
        @author     humkyung
1530
        @date       2018.04.20
1531
        @history    humkyung 2018.04.24 read MetricStr column and set size unit
1532
                    kyouho 2018.07.04 forCheckLineNumber get only inch or metric
1533
                    kyouho 2018.07.16 edit query order by code
1534
    '''
1535
    def getNomialPipeSizeData(self, forCheckLineNumber = False, orderStr = "CODE"):
1536
        res = []
1537
        try:
1538
            configs = self.getConfigs('Line No', 'Size Unit')
1539
            sizeUnit = configs[0].value if 1 == len(configs) else 'Metric'
1540

    
1541
            # Creates or opens a file called mydb with a SQLite3 DB
1542
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1543
            conn = sqlite3.connect(dbPath)
1544
            # Get a cursor object
1545
            cursor = conn.cursor()
1546

    
1547
            sql = "select Code,Metric,Inch,InchStr,MetricStr from NominalDiameter ORDER BY {} ASC".format(orderStr)
1548
            cursor.execute(sql)
1549
            rows = cursor.fetchall()
1550
            for row in rows:
1551
                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])
1552
                pipeSize.sizeUnit = sizeUnit
1553
                if forCheckLineNumber:
1554
                    if sizeUnit == 'Inch' and pipeSize.inchStr:
1555
                        res.append(pipeSize.inchStr)
1556
                    elif sizeUnit == 'Metric' and pipeSize.metricStr:
1557
                        res.append(pipeSize.metricStr)
1558
                else:
1559
                    res.append(pipeSize)
1560
                
1561
        # Catch the exception
1562
        except Exception as ex:
1563
            # Roll back any change if something goes wrong
1564
            conn.rollback()
1565
            
1566
            from App import App 
1567
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1568
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1569
        finally:
1570
            # Close the db connection
1571
            conn.close()
1572

    
1573
        return res
1574

    
1575
    '''
1576
        @brief      insert NominalDiameter table
1577
        @author     kyouho
1578
        @date       2018.07.16
1579
    '''
1580
    def insertNomialPipeSize(self, pipeSizes):
1581
        try:
1582
            # Creates or opens a file called mydb with a SQLite3 DB
1583
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1584
            conn = sqlite3.connect(dbPath)
1585
            # Get a cursor object
1586
            cursor = conn.cursor()
1587
            sql = "INSERT INTO NominalDiameter(Code, Metric, Inch, InchStr, MetricStr) VALUES(?,?,?,?,?)"
1588
            for pipeSize in pipeSizes:
1589
                param = (pipeSize.code, pipeSize.metric, pipeSize.inch, pipeSize.inchStr, pipeSize.metricStr)
1590
                cursor.execute(sql, param)
1591
            conn.commit()
1592
            # Catch the exception
1593
        except Exception as ex:
1594
            # Roll back any change if something goes wrong
1595
            conn.rollback()
1596
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1597
        finally:
1598
            # Close the db connection
1599
            conn.close()
1600

    
1601

    
1602
    '''
1603
        @brief      delete NominalDiameter table
1604
        @author     kyouho
1605
        @date       2018.07.16
1606
    '''
1607
    def deleteNomialPipeSize(self):
1608
        try:
1609
            dbPath = os.path.join(self.getCurrentProject().getPath(), 'db', 'ITI_PID.db')
1610
            conn = sqlite3.connect(dbPath)
1611
            cursor = conn.cursor()
1612
            sql = "DELETE FROM NominalDiameter"
1613
            try:
1614
                cursor.execute(sql)
1615
                conn.commit()
1616
            except Exception as ex:
1617
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1618
        finally:
1619
            conn.close()
1620

    
1621
    '''
1622
        @brief      convert inch to metric
1623
        @author     kyouho
1624
        @date       2018.07.09
1625
    '''
1626
    def convertInchToMetric(self, inch):
1627
        result = ''
1628
        try:
1629
            # Creates or opens a file called mydb with a SQLite3 DB
1630
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1631
            conn = sqlite3.connect(dbPath)
1632
            # Get a cursor object
1633
            cursor = conn.cursor()
1634
            
1635
            sql = "select MetricStr from NominalDiameter WHERE InchStr = ?"
1636
            param = (inch,)
1637
            cursor.execute(sql, param)
1638
            rows = cursor.fetchall()
1639

    
1640
            if rows:
1641
                result = rows[0][0]
1642
            # Catch the exception
1643
        except Exception as ex:
1644
            # Roll back any change if something goes wrong
1645
            conn.rollback()
1646
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1647
        finally:
1648
            # Close the db connection
1649
            conn.close()
1650

    
1651
        return result
1652

    
1653
    '''
1654
        @brief      get Color MaxUID
1655
        @author     kyouho
1656
        @date       2018.07.03
1657
    '''
1658
    def getMaxColorUID(self):
1659
        result = 0
1660

    
1661
        try:
1662
            # Creates or opens a file called mydb with a SQLite3 DB
1663
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1664
            conn = sqlite3.connect(dbPath)
1665
            # Get a cursor object
1666
            cursor = conn.cursor()
1667

    
1668
            sql = "select MAX(UID) from Colors"
1669
            cursor.execute(sql)
1670
            rows = cursor.fetchall()
1671

    
1672
            result = rows[0][0]
1673
            # Catch the exception
1674
        except Exception as ex:
1675
            # Roll back any change if something goes wrong
1676
            conn.rollback()
1677
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1678
        finally:
1679
            # Close the db connection
1680
            conn.close()
1681

    
1682
        return result
1683

    
1684
    '''
1685
        @brief      insert Color property
1686
        @author     kyouho
1687
        @date       2018.07.09
1688
    '''
1689
    def setPropertyColor(self, _color):
1690
        try:
1691
            # Creates or opens a file called mydb with a SQLite3 DB
1692
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1693
            conn = sqlite3.connect(dbPath)
1694
            # Get a cursor object
1695
            cursor = conn.cursor()
1696
            sql = "INSERT INTO Colors(UID, RED, GREEN, BLUE, PROPERTY, VALUE) VALUES(?,?,?,?,?,?)"
1697
            param = (_color.index, _color.red, _color.green, _color.blue, _color._property, _color.value)
1698
            cursor.execute(sql, param)
1699
            conn.commit()
1700
            # Catch the exception
1701
        except Exception as ex:
1702
            # Roll back any change if something goes wrong
1703
            conn.rollback()
1704
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1705
        finally:
1706
            # Close the db connection
1707
            conn.close()
1708

    
1709
    '''
1710
        @brief      delete Color property
1711
        @author     kyouho
1712
        @date       2018.07.09
1713
    '''
1714
    def deletePropertyColor(self, property):
1715
        try:
1716
            # Creates or opens a file called mydb with a SQLite3 DB
1717
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1718
            conn = sqlite3.connect(dbPath)
1719
            # Get a cursor object
1720
            cursor = conn.cursor()
1721

    
1722
            sql = "DELETE FROM Colors WHERE PROPERTY = '{}'".format(property)
1723
            cursor.execute(sql)
1724
            conn.commit()
1725
            # Catch the exception
1726
        except Exception as ex:
1727
            # Roll back any change if something goes wrong
1728
            conn.rollback()
1729
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1730
        finally:
1731
            # Close the db connection
1732
            conn.close()
1733

    
1734
    '''
1735
        @brief      get Fluid Code
1736
        @author     kyouho
1737
        @date       2018.07.03
1738
        @history    kyouho 2018.07.04 kyouho 2018.07.04 forCheckLineNumber get only code
1739
    '''
1740
    def getFluidCodeData(self, forCheckLineNumber = False):
1741
        from FluidCodeData import FluidCodeData
1742
        result = []
1743

    
1744
        try:
1745
            # Creates or opens a file called mydb with a SQLite3 DB
1746
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1747
            conn = sqlite3.connect(dbPath)
1748
            # Get a cursor object
1749
            cursor = conn.cursor()
1750

    
1751
            sql = 'select uid, code, description from FluidCode order by length(code) DESC'
1752
            cursor.execute(sql)
1753
            rows = cursor.fetchall()
1754
            for row in rows:
1755
                data = FluidCodeData(row[0], row[1], row[2])
1756
                if forCheckLineNumber:
1757
                    result.append(data.code)
1758
                else:
1759
                    result.append(data)
1760
            # Catch the exception
1761
        except Exception as ex:
1762
            # Roll back any change if something goes wrong
1763
            conn.rollback()
1764
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1765
        finally:
1766
            # Close the db connection
1767
            conn.close()
1768

    
1769
        return result
1770

    
1771
    '''
1772
        @brief      get Symbol Attribute
1773
        @author     kyouho
1774
        @date       2018.07.18
1775
    '''
1776
    def checkAttribute(self, attr):
1777
        try:
1778
            # Creates or opens a file called mydb with a SQLite3 DB
1779
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1780
            conn = sqlite3.connect(dbPath)
1781
            # Get a cursor object
1782
            cursor = conn.cursor()
1783

    
1784
            sql = 'select UID from SymbolAttribute where UID = ?'
1785
            param = (attr,)
1786
            cursor.execute(sql, param)
1787
            rows = cursor.fetchall()
1788
            if len(rows):
1789
                return True
1790
            else:
1791
                return False
1792
            # Catch the exception
1793
        except Exception as ex:
1794
            # Roll back any change if something goes wrong
1795
            conn.rollback()
1796
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1797
        finally:
1798
            # Close the db connection
1799
            conn.close()
1800

    
1801
        return False
1802

    
1803
    '''
1804
        @brief      get Symbol Attribute
1805
        @author     kyouho
1806
        @date       2018.07.18
1807
        @history    humkyung 2018.10.13 load expression
1808
    '''
1809
    def getSymbolAttribute(self, _type):
1810
        from SymbolAttr import SymbolAttr
1811

    
1812
        result = []
1813

    
1814
        try:
1815
            # Creates or opens a file called mydb with a SQLite3 DB
1816
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1817
            conn = sqlite3.connect(dbPath)
1818
            # Get a cursor object
1819
            cursor = conn.cursor()
1820

    
1821
            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]'
1822
            param = (_type,)
1823
            cursor.execute(sql, param)
1824
            rows = cursor.fetchall()
1825
            for row in rows:
1826
                attr = SymbolAttr()
1827
                attr.UID = row[0]
1828
                attr.Attribute = row[1]
1829
                attr.DisplayAttribute = row[2]
1830
                attr.AttributeType = row[3]
1831
                attr.AttrAt = row[4]
1832
                attr.Expression = row[5]
1833
                result.append(attr)
1834
            # Catch the exception
1835
        except Exception as ex:
1836
            from App import App 
1837

    
1838
            # Roll back any change if something goes wrong
1839
            conn.rollback()
1840

    
1841
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1842
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1843
        finally:
1844
            # Close the db connection
1845
            conn.close()
1846

    
1847
        return result
1848

    
1849
    '''
1850
        @brief      get Symbol Attribute by UID
1851
        @author     kyouho
1852
        @date       2018.08.17
1853
        @history    humkyung 2018.10.13 load expression
1854
    '''
1855
    def getSymbolAttributeByUID(self, UID):
1856
        from SymbolAttr import SymbolAttr
1857

    
1858
        res = None
1859

    
1860
        try:
1861
            # Creates or opens a file called mydb with a SQLite3 DB
1862
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1863
            conn = sqlite3.connect(dbPath)
1864
            # Get a cursor object
1865
            cursor = conn.cursor()
1866

    
1867
            sql = 'select Attribute, DisplayAttribute, AttributeType, AttrAt, Expression from SymbolAttribute where uid = "{}"'.format(UID)
1868
            cursor.execute(sql)
1869
            rows = cursor.fetchall()
1870
            if len(rows):
1871
                res = SymbolAttr()
1872
                res.UID = UID
1873
                res.Attribute = rows[0][0]
1874
                res.DisplayAttribute = rows[0][1]
1875
                res.AttributeType = rows[0][2]
1876
                res.AttrAt = rows[0][3]
1877
                res.Expression = rows[0][4]
1878
            # Catch the exception
1879
        except Exception as ex:
1880
            from App import App
1881

    
1882
            # Roll back any change if something goes wrong
1883
            conn.rollback()
1884

    
1885
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1886
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1887
        finally:
1888
            # Close the db connection
1889
            conn.close()
1890

    
1891
        return res
1892

    
1893
    '''
1894
        @brief      save symbol attributes
1895
        @author     humkyung
1896
        @date       2018.08.14
1897
        @history    humkyung 2018.10.13 save expression
1898
    '''
1899
    def saveSymbolAttributes(self, type, attrs):
1900
        try:
1901
            # Creates or opens a file called mydb with a SQLite3 DB
1902
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1903
            conn = sqlite3.connect(dbPath)
1904
            # Get a cursor object
1905
            cursor = conn.cursor()
1906

    
1907
            sql = 'delete from SymbolAttribute where SymbolType = ?'
1908
            param = (type,)
1909
            cursor.execute(sql, param)
1910

    
1911
            for attr in attrs:
1912
                sql = 'insert into SymbolAttribute(UID, SymbolType, Attribute, DisplayAttribute, AttributeType, AttrAt, Expression, [index]) values(?, ?, ?, ?, ?, ?, ?, ?)'
1913
                attr.insert(1, type)
1914
                param = tuple(attr)
1915
                cursor.execute(sql, param)
1916

    
1917
            conn.commit()
1918
            # Catch the exception
1919
        except Exception as ex:
1920
            # Roll back any change if something goes wrong
1921
            conn.rollback()
1922
            
1923
            from App import App 
1924
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1925
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1926
        finally:
1927
            # Close the db connection
1928
            conn.close()
1929

    
1930
    '''
1931
        @brief      save symbol attributes
1932
        @author     humkyung
1933
        @date       2018.08.14
1934
    '''
1935
    def saveLineAttributes(self, attrs):
1936
        try:
1937
            # Creates or opens a file called mydb with a SQLite3 DB
1938
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1939
            conn = sqlite3.connect(dbPath)
1940
            # Get a cursor object
1941
            cursor = conn.cursor()
1942

    
1943
            sql = 'delete from LineProperties'
1944
            cursor.execute(sql)
1945

    
1946
            for attr in attrs:
1947
                sql = 'insert into LineProperties(UID, Name, DisplayName, Type, LimitNumber, [index]) values(?, ?, ?, ?, ?, ?)'
1948
                param = tuple(attr)
1949
                cursor.execute(sql, param)
1950

    
1951
            conn.commit()
1952

    
1953
            self._lineNoProperties = None
1954
            # Catch the exception
1955
        except Exception as ex:
1956
            # Roll back any change if something goes wrong
1957
            conn.rollback()
1958
            
1959
            from App import App 
1960
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1961
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1962
        finally:
1963
            # Close the db connection
1964
            conn.close()
1965

    
1966
    '''
1967
        @brief      get symbol type id
1968
        @author     kyouho
1969
        @date       2018.08.17
1970
    '''
1971
    def getSymbolTypeId(self, symbolType):
1972
        result = []
1973

    
1974
        try:
1975
            # Creates or opens a file called mydb with a SQLite3 DB
1976
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1977
            conn = sqlite3.connect(dbPath)
1978
            # Get a cursor object
1979
            cursor = conn.cursor()
1980

    
1981
            sql = 'select id from SymbolType where type = ?'
1982
            param = (symbolType,)
1983
            cursor.execute(sql, param)
1984
            rows = cursor.fetchall()
1985
            
1986
            if len(rows):
1987
                result = rows[0][0]
1988
            else:
1989
                result = -1
1990
            # Catch the exception
1991
        except Exception as ex:
1992
            # Roll back any change if something goes wrong
1993
            conn.rollback()
1994
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1995
        finally:
1996
            # Close the db connection
1997
            conn.close()
1998

    
1999
        return result
2000

    
2001
    '''
2002
        @brief      get Code Table Data
2003
        @author     kyouho
2004
        @date       2018.07.10
2005
    '''
2006
    def getCodeTable(self, property, forCheckLineNumber = False):
2007
        result = []
2008
        try:
2009
            # Creates or opens a file called mydb with a SQLite3 DB
2010
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2011
            conn = sqlite3.connect(dbPath)
2012
            # Get a cursor object
2013
            cursor = conn.cursor()
2014

    
2015
            if property.upper().replace(' ','') == "NOMINALDIAMETER" and forCheckLineNumber:
2016
                sql = 'select InchStr, MetricStr from [{}] order by Metric ASC'.format(property)
2017
                cursor.execute(sql)
2018
                rows = cursor.fetchall()
2019
                for index in range(2):
2020
                    for row in rows:
2021
                        if row[index] != '' and result.count(row[index].replace("'", '"')) == 0:
2022
                            result.append(row[index].replace("'", '"'))
2023
            else:
2024
                sql = 'select uid, code, description, Allowables from [{}] order by length(code) DESC'.format(property)
2025
                cursor.execute(sql)
2026
                rows = cursor.fetchall()
2027
                for row in rows:
2028
                    if forCheckLineNumber:
2029
                        data = row[1]
2030
                    else:
2031
                        data = (row[0], row[1], row[2], row[3])
2032
                    result.append(data)
2033
            # Catch the exception
2034
        except Exception as ex:
2035
            # Roll back any change if something goes wrong
2036
            conn.rollback()
2037
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2038
        finally:
2039
            # Close the db connection
2040
            conn.close()
2041

    
2042
        return result
2043

    
2044
    '''
2045
        @brief      Set Common Code Data
2046
        @author     kyouho
2047
        @date       2018.07.12
2048
    '''
2049
    def saveCommonCodeData(self, tableName, datas):
2050
        try:
2051
            # Creates or opens a file called mydb with a SQLite3 DB
2052
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2053
            conn = sqlite3.connect(dbPath)
2054
            # Get a cursor object
2055
            cursor = conn.cursor()
2056

    
2057
            for data in datas:
2058
                uid = data[0]
2059
                if not uid:
2060
                    sql = "insert or replace into {}(UID, CODE, DESCRIPTION, ALLOWABLES) values(lower(hex(randomblob(16))), ?, ?, ?)".format(tableName)
2061
                    param = (data[1], data[2], data[3])
2062
                else:
2063
                    sql = "update {} SET CODE=?, DESCRIPTION=?, ALLOWABLES=? WHERE UID = ?".format(tableName)
2064
                    param = (data[1], data[2], data[3], data[0])
2065
                cursor.execute(sql, param)
2066

    
2067
            conn.commit()
2068
        
2069
        # Catch the exception
2070
        except Exception as ex:
2071
            # Roll back any change if something goes wrong
2072
            conn.rollback()
2073
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2074
        finally:
2075
            # Close the db connection
2076
            conn.close()
2077

    
2078
    '''
2079
        @brief      Set Common Code Data
2080
        @author     kyouho
2081
        @date       2018.07.12
2082
    '''
2083
    def deleteCommonCodeData(self, datas):
2084
        try:
2085
            # Creates or opens a file called mydb with a SQLite3 DB
2086
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2087
            conn = sqlite3.connect(dbPath)
2088
            # Get a cursor object
2089
            cursor = conn.cursor()
2090

    
2091
            for data in datas:
2092
                uid = data[0]
2093
                tableName = data[1]
2094

    
2095
                if uid:
2096
                    sql = "delete from {} where UID = ?".format(tableName)
2097
                    param = (uid,)
2098
                    cursor.execute(sql, param)
2099

    
2100
                cursor.execute(sql, param)
2101

    
2102
            conn.commit()
2103
        
2104
        # Catch the exception
2105
        except Exception as ex:
2106
            # Roll back any change if something goes wrong
2107
            conn.rollback()
2108
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2109
        finally:
2110
            # Close the db connection
2111
            conn.close()
2112

    
2113
    '''
2114
        @brief      delete data list
2115
        @author     kyouho
2116
        @date       2018.08.16
2117
    '''
2118
    def deleteDataList(self, tableName, UID):
2119
        try:
2120
            # Creates or opens a file called mydb with a SQLite3 DB
2121
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2122
            conn = sqlite3.connect(dbPath)
2123
            # Get a cursor object
2124
            cursor = conn.cursor()
2125

    
2126
            sql = 'delete from {} where UID = {}'.format(tableName, UID)
2127
            
2128
            cursor.execute(sql)
2129

    
2130
            conn.commit()
2131

    
2132
        # Catch the exception
2133
        except Exception as ex:
2134
            # Roll back any change if something goes wrong
2135
            conn.rollback()
2136
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2137
        finally:
2138
            # Close the db connection
2139
            conn.close()
2140

    
2141
    def getDocumentNameList(self):
2142
        '''
2143
            @brief      get documentName list
2144
            @author     euisung
2145
            @date       2018.12.11
2146
        '''
2147
        result = []
2148

    
2149
        try:
2150
            # Creates or opens a file called mydb with a SQLite3 DB
2151
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2152
            conn = sqlite3.connect(dbPath)
2153
            # Get a cursor object
2154
            cursor = conn.cursor()
2155

    
2156
            sql = 'select DISTINCT(PNID_NO) from LINE_DATA_LIST'
2157
            cursor.execute(sql)
2158
            sql = 'select DISTINCT(PNID_NO) from EQUIPMENT_DATA_LIST'
2159
            cursor.execute(sql)
2160
            sql = 'select DISTINCT(PNID_NO) from INSTRUMENT_DATA_LIST'
2161
            cursor.execute(sql)
2162
            sql = 'select DISTINCT(PNID_NO) from NOTE_DATA_LIST'
2163
            cursor.execute(sql)
2164
            sql = 'select DISTINCT(PNID_NO) from VALVE_DATA_LIST'
2165
            cursor.execute(sql)
2166

    
2167
            rows = cursor.fetchall()
2168
            for row in rows:
2169
                result.append(row[0])
2170

    
2171
            result = list(set(result))
2172
            result.sort()
2173
        # Catch the exception
2174
        except Exception as ex:
2175
            # Roll back any change if something goes wrong
2176
            conn.rollback()
2177
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2178
        finally:
2179
            # Close the db connection
2180
            conn.close()
2181

    
2182
        return result
2183

    
2184

    
2185
    '''
2186
        @brief      get line documentName list
2187
        @author     kyouho
2188
        @date       2018.08.13
2189
    '''
2190
    def getLineDocumentNameList(self):
2191
        result = []
2192

    
2193
        try:
2194
            # Creates or opens a file called mydb with a SQLite3 DB
2195
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2196
            conn = sqlite3.connect(dbPath)
2197
            # Get a cursor object
2198
            cursor = conn.cursor()
2199

    
2200
            sql = 'select DISTINCT(PNID_NO) from LINE_DATA_LIST'
2201

    
2202
            cursor.execute(sql)
2203
            rows = cursor.fetchall()
2204
            for row in rows:
2205
                result.append(row[0])
2206
        # Catch the exception
2207
        except Exception as ex:
2208
            # Roll back any change if something goes wrong
2209
            conn.rollback()
2210
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2211
        finally:
2212
            # Close the db connection
2213
            conn.close()
2214

    
2215
        return result
2216

    
2217
    '''
2218
        @brief      get line documentName list
2219
        @author     kyouho
2220
        @date       2018.08.14
2221
    '''
2222
    def getEquipDocumentNameList(self):
2223
        result = []
2224

    
2225
        try:
2226
            # Creates or opens a file called mydb with a SQLite3 DB
2227
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2228
            conn = sqlite3.connect(dbPath)
2229
            # Get a cursor object
2230
            cursor = conn.cursor()
2231

    
2232
            sql = 'select DISTINCT(PNID_NO) from EQUIPMENT_DATA_LIST'
2233

    
2234
            cursor.execute(sql)
2235
            rows = cursor.fetchall()
2236
            for row in rows:
2237
                result.append(row[0])
2238
        # Catch the exception
2239
        except Exception as ex:
2240
            # Roll back any change if something goes wrong
2241
            conn.rollback()
2242
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2243
        finally:
2244
            # Close the db connection
2245
            conn.close()
2246

    
2247
        return result
2248

    
2249

    
2250
    '''
2251
        @brief      get line data list
2252
        @author     kyouho
2253
        @date       2018.08.13
2254
    '''
2255
    def getLineDataList(self, docName = None):
2256
        result = []
2257

    
2258
        try:
2259
            # Creates or opens a file called mydb with a SQLite3 DB
2260
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2261
            conn = sqlite3.connect(dbPath)
2262
            # Get a cursor object
2263
            cursor = conn.cursor()
2264

    
2265
            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'
2266
            if docName is not None:
2267
                sql += " where PNID_NO = '{}'".format(docName)
2268

    
2269
            cursor.execute(sql)
2270
            #columnName = list(map(lambda x: x[0].upper(), cursor.description))
2271
            rows = cursor.fetchall()
2272
            for row in rows:
2273
                data = []
2274
                for index in range(len(cursor.description)):
2275
                    data.append(row[index])
2276
                result.append(data)
2277
        # Catch the exception
2278
        except Exception as ex:
2279
            # Roll back any change if something goes wrong
2280
            conn.rollback()
2281
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2282
        finally:
2283
            # Close the db connection
2284
            conn.close()
2285

    
2286
        return result
2287

    
2288
    '''
2289
        @brief      set line data list
2290
        @author     kyouho
2291
        @date       2018.08.13
2292
    '''
2293
    def setLineDataList(self, dataLists):
2294
        try:
2295
            # Creates or opens a file called mydb with a SQLite3 DB
2296
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2297
            conn = sqlite3.connect(dbPath)
2298
            # Get a cursor object
2299
            cursor = conn.cursor()
2300
            
2301
            for data in dataLists:
2302
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2303
                param = tuple(data)
2304
                cursor.execute(sql, param)
2305

    
2306
            conn.commit()
2307

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

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

    
2334
            conn.commit()
2335

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

    
2345
    '''
2346
        @brief      delete line data list
2347
        @author     kyouho
2348
        @date       2018.08.13
2349
    '''
2350
    def deleteLineDataList_LineNo(self, removeUID):
2351
        try:
2352
            # Creates or opens a file called mydb with a SQLite3 DB
2353
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2354
            conn = sqlite3.connect(dbPath)
2355
            # Get a cursor object
2356
            cursor = conn.cursor()
2357
            
2358
            for uid in removeUID:
2359
                sql = "delete from LINE_DATA_LIST where LINE_NO = ?"
2360
                param = (uid,)
2361
                cursor.execute(sql, param)
2362

    
2363
            conn.commit()
2364

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

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

    
2391
            conn.commit()
2392

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

    
2402
    '''
2403
        @brief      delete inst data list
2404
        @author     kyouho
2405
        @date       2018.08.14
2406
    '''
2407
    def deleteInstDataList(self, removeUID):
2408
        try:
2409
            # Creates or opens a file called mydb with a SQLite3 DB
2410
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2411
            conn = sqlite3.connect(dbPath)
2412
            # Get a cursor object
2413
            cursor = conn.cursor()
2414
            
2415
            for uid in removeUID:
2416
                sql = "delete from INSTRUMENT_DATA_LIST where uid = '{}'".format(uid)
2417
                cursor.execute(sql)
2418

    
2419
            conn.commit()
2420

    
2421
        # Catch the exception
2422
        except Exception as ex:
2423
            # Roll back any change if something goes wrong
2424
            conn.rollback()
2425
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2426
        finally:
2427
            # Close the db connection
2428
            conn.close()
2429

    
2430
    '''
2431
        @brief      delete note data list
2432
        @author     kyouho
2433
        @date       2018.10.10
2434
    '''
2435
    def deleteNoteDataList(self, removeUID):
2436
        try:
2437
            # Creates or opens a file called mydb with a SQLite3 DB
2438
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2439
            conn = sqlite3.connect(dbPath)
2440
            # Get a cursor object
2441
            cursor = conn.cursor()
2442
            
2443
            for uid in removeUID:
2444
                sql = "delete from NOTE_DATA_LIST where uid = '{}'".format(uid)
2445
                cursor.execute(sql)
2446

    
2447
            conn.commit()
2448

    
2449
        # Catch the exception
2450
        except Exception as ex:
2451
            # Roll back any change if something goes wrong
2452
            conn.rollback()
2453
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2454
        finally:
2455
            # Close the db connection
2456
            conn.close()
2457

    
2458
    '''
2459
        @brief      get equipment data list
2460
        @author     humkyung
2461
        @date       2018.05.03
2462
    '''
2463
    def getEquipmentDataList(self, docName = None):
2464
        result = []
2465
        try:
2466
            # Creates or opens a file called mydb with a SQLite3 DB
2467
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2468
            conn = sqlite3.connect(dbPath)
2469
            # Get a cursor object
2470
            cursor = conn.cursor()
2471

    
2472
            sql = 'select a.*,C.Attribute,B.Value  from EQUIPMENT_DATA_LIST a left join Attributes B on a.UID=B.Symbol_UID ' \
2473
                                                                             'left join SymbolAttribute C on B.SymbolAttribute_UID=C.UID'
2474
            if docName is not None:
2475
                sql += " where PNID_NO = '{}'".format(docName)
2476

    
2477
            cursor.execute(sql)
2478
            col_names = [desc[0] for desc in cursor.description]    # get coloumn name
2479
            rows = cursor.fetchall()
2480
            for row in rows:
2481
                matches = [res for res in result if res['UID']==row[0]]
2482
                if matches:
2483
                    matches[0][row[len(row)-2]] = row[len(row)-1]
2484
                else:
2485
                    data = dict(zip(col_names[:-2], row[:-2]))
2486
                    if row[len(row)-2] is not None:
2487
                        data[row[len(row)-2]] = row[len(row)-1]
2488
                    result.append(data)
2489
        # Catch the exception
2490
        except Exception as ex:
2491
            from App import App 
2492

    
2493
            # Roll back any change if something goes wrong
2494
            conn.rollback()
2495
            
2496
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2497
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2498
        finally:
2499
            # Close the db connection
2500
            conn.close()
2501

    
2502
        return result
2503

    
2504
    def get_valve_data_list(self, docName = None):
2505
        """
2506
        @brief      get valve data list
2507
        @author     humkyung
2508
        @date       2018.10.11
2509
        """
2510

    
2511
        result = []
2512
        try:
2513
            # Creates or opens a file called mydb with a SQLite3 DB
2514
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2515
            conn = sqlite3.connect(dbPath)
2516
            # Get a cursor object
2517
            cursor = conn.cursor()
2518

    
2519
            sql = 'select a.UID,a.ITEM_NO,a.PNID_NO,c.Attribute,b.Value from VALVE_DATA_LIST a left join Attributes b on a.uid=b.symbol_uid ' \
2520
                  'left join SymbolAttribute c on b.SymbolAttribute_UID=c.UID'
2521
            if docName is not None:
2522
                sql += " where PNID_NO = '{}'".format(docName)
2523

    
2524
            cursor.execute(sql)
2525
            rows = cursor.fetchall()
2526
            for row in rows:
2527
                matches = [res for res in result if res['UID']==row[0]]
2528
                if matches:
2529
                    matches[0][row[3]] = row[4]
2530
                else:
2531
                    data = {'UID':row[0], 'ITEM_NO':row[1], 'PNID_NO':row[2]}
2532
                    data[row[3]] = row[4]
2533
                    result.append(data)
2534

    
2535
        # Catch the exception
2536
        except Exception as ex:
2537
            from App import App 
2538

    
2539
            # Roll back any change if something goes wrong
2540
            conn.rollback()
2541
            
2542
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2543
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2544
        finally:
2545
            # Close the db connection
2546
            conn.close()
2547

    
2548
        return result
2549

    
2550
    '''
2551
        @brief      get instrument data list
2552
        @author     kyouho
2553
        @date       2018.08.14
2554
    '''
2555
    def getInstrumentDataList(self, docName = None):
2556
        result = []
2557
        try:
2558
            # Creates or opens a file called mydb with a SQLite3 DB
2559
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2560
            conn = sqlite3.connect(dbPath)
2561
            # Get a cursor object
2562
            cursor = conn.cursor()
2563

    
2564
            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'
2565
            if docName is not None:
2566
                sql += " where PNID_NO = '{}'".format(docName)
2567

    
2568
            cursor.execute(sql)
2569
            rows = cursor.fetchall()
2570
            for row in rows:
2571
                data = []
2572
                for index in range(len(cursor.description)): 
2573
                    data.append(row[index])
2574
                result.append(data)
2575
        # Catch the exception
2576
        except Exception as ex:
2577
            # Roll back any change if something goes wrong
2578
            conn.rollback()
2579
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2580
        finally:
2581
            # Close the db connection
2582
            conn.close()
2583

    
2584
        return result
2585

    
2586
    '''
2587
        @brief      get Note data list
2588
        @author     kyouho
2589
        @date       2018.10.10
2590
    '''
2591
    def getNoteDataList(self, docName = None):
2592
        result = []
2593
        try:
2594
            # Creates or opens a file called mydb with a SQLite3 DB
2595
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2596
            conn = sqlite3.connect(dbPath)
2597
            # Get a cursor object
2598
            cursor = conn.cursor()
2599

    
2600
            sql = 'select UID, NOTE_NO, DESCRIPTION, PNID_NO from NOTE_DATA_LIST'
2601
            if docName is not None:
2602
                sql += " where PNID_NO = '{}'".format(docName)
2603

    
2604
            sql += ' ORDER BY NOTE_NO ASC'
2605
            cursor.execute(sql)
2606
            rows = cursor.fetchall()
2607
            for row in rows:
2608
                data = []
2609
                for index in range(len(cursor.description)): 
2610
                    data.append(row[index])
2611
                result.append(data)
2612
        # Catch the exception
2613
        except Exception as ex:
2614
            # Roll back any change if something goes wrong
2615
            conn.rollback()
2616
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2617
        finally:
2618
            # Close the db connection
2619
            conn.close()
2620

    
2621
        return result
2622

    
2623
    def saveToDatabase(self, items):
2624
        """
2625
        save given items to database
2626
        """
2627
        try:
2628
            # Creates or opens a file called mydb with a SQLite3 DB
2629
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2630
            conn = sqlite3.connect(dbPath)
2631
            # Get a cursor object
2632
            cursor = conn.cursor()
2633

    
2634
            for item in items:
2635
                sql = item.toSql()
2636
                if type(sql) is list:
2637
                    for item in sql:
2638
                        if item is not None and 2 == len(item):
2639
                            cursor.execute(item[0], item[1])
2640
                else:
2641
                    if sql is not None and 2 == len(sql):
2642
                        cursor.execute(sql[0], sql[1])
2643

    
2644
            conn.commit()
2645
        # Catch the exception
2646
        except Exception as ex:
2647
            from App import App
2648
            # Roll back any change if something goes wrong
2649
            conn.rollback()
2650

    
2651
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2652
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2653
        finally:
2654
            # Close the db connection
2655
            conn.close()
2656

    
2657
    '''
2658
        @brief      set equipment data list
2659
        @author     humkyung
2660
        @date       2018.05.03
2661
    '''
2662
    def setEquipmentDataList(self, dataList):
2663
        try:
2664
            # Creates or opens a file called mydb with a SQLite3 DB
2665
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2666
            conn = sqlite3.connect(dbPath)
2667
            # Get a cursor object
2668
            cursor = conn.cursor()
2669

    
2670
            for data in dataList:
2671
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2672
                param = tuple(data)
2673
                cursor.execute(sql, param)
2674
            conn.commit()
2675
        # Catch the exception
2676
        except Exception as ex:
2677
            # Roll back any change if something goes wrong
2678
            conn.rollback()
2679
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2680
        finally:
2681
            # Close the db connection
2682
            conn.close()
2683

    
2684
    '''
2685
        @brief      set instrumnet data list
2686
        @author     kyoyho
2687
        @date       2018.08.14
2688
    '''
2689
    def setInstrumentDataList(self, dataList):
2690
        try:
2691
            # Creates or opens a file called mydb with a SQLite3 DB
2692
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2693
            conn = sqlite3.connect(dbPath)
2694
            # Get a cursor object
2695
            cursor = conn.cursor()
2696

    
2697
            for data in dataList:
2698
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2699
                param = tuple(data)
2700
                cursor.execute(sql, param)
2701
            conn.commit()
2702

    
2703
        # Catch the exception
2704
        except Exception as ex:
2705
            # Roll back any change if something goes wrong
2706
            conn.rollback()
2707
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2708
        finally:
2709
            # Close the db connection
2710
            conn.close()
2711

    
2712
    '''
2713
        @brief      set Note data list
2714
        @author     kyoyho
2715
        @date       2018.10.10
2716
    '''
2717
    def setNoteDataList(self, dataList):
2718
        try:
2719
            # Creates or opens a file called mydb with a SQLite3 DB
2720
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2721
            conn = sqlite3.connect(dbPath)
2722
            # Get a cursor object
2723
            cursor = conn.cursor()
2724

    
2725
            for data in dataList:
2726
                sql = "insert or replace into NOTE_DATA_LIST(UID, NOTE_NO, DESCRIPTION, PNID_NO) values(?, ?, ?, ?)"
2727
                param = tuple(data)
2728
                cursor.execute(sql, param)
2729
            conn.commit()
2730

    
2731
        # Catch the exception
2732
        except Exception as ex:
2733
            # Roll back any change if something goes wrong
2734
            conn.rollback()
2735
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2736
        finally:
2737
            # Close the db connection
2738
            conn.close()
2739

    
2740
    def getDrawings(self):
2741
        """
2742
        @brief      get drawings
2743
        @author     humkyung
2744
        @date       2018.11.03
2745
        """
2746

    
2747
        res = []
2748
        try:
2749
            # Creates or opens a file called mydb with a SQLite3 DB
2750
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2751
            conn = sqlite3.connect(dbPath)
2752
            # Get a cursor object
2753
            cursor = conn.cursor()
2754

    
2755
            sql = 'select UID,[NAME],[DATETIME] from Drawings'
2756
            cursor.execute(sql)
2757
            rows = cursor.fetchall()
2758
            for row in rows:
2759
                res.append([row[0], row[1], row[2]])
2760

    
2761
        # Catch the exception
2762
        except Exception as ex:
2763
            # Roll back any change if something goes wrong
2764
            conn.rollback()
2765
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2766
        finally:
2767
            # Close the db connection
2768
            conn.close()
2769

    
2770
        return res
2771

    
2772
    def saveDrawings(self, drawings):
2773
        """
2774
        @brief      save drawings
2775
        @author     humkyung
2776
        @date       2018.11.03
2777
        """
2778

    
2779
        try:
2780
            # Creates or opens a file called mydb with a SQLite3 DB
2781
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2782
            conn = sqlite3.connect(dbPath)
2783
            # Get a cursor object
2784
            cursor = conn.cursor()
2785

    
2786
            for drawing in drawings:
2787
                if not drawing[0]:
2788
                    sql = 'insert or replace into Drawings(UID, [NAME], [DATETIME]) values(lower(hex(randomblob(16))), ?, ?)'
2789
                    param = tuple([drawing[1], ''])
2790
                else:
2791
                    sql = 'insert or replace into Drawings(UID, [NAME], [DATETIME]) values(?, ?, ?)'
2792
                    param = tuple(drawing)
2793

    
2794
                cursor.execute(sql, param)
2795
            conn.commit()
2796

    
2797
        # Catch the exception
2798
        except Exception as ex:
2799
            # Roll back any change if something goes wrong
2800
            conn.rollback()
2801
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2802
        finally:
2803
            # Close the db connection
2804
            conn.close()
2805

    
2806
    '''
2807
        @brief  get IsOriginDetect ComboBox Items
2808
    '''
2809
    def getIsOriginDetectComboBoxItems(self):
2810
        return [("원본 도면", 0), ("텍스트 제거 도면", 1)]
2811

    
2812
    '''
2813
        @brief  get IsOriginDetect ComboBox Items
2814
    '''
2815
    def getOcrOptionComboBoxItems(self):
2816
        return [("OCR 미적용", 0), ("일반 심볼", 1), ("Instrument 계통", 2)]
2817
    
2818
    '''
2819
        @brief      Return Symbol Type Items
2820
        @author     Jeongwoo
2821
        @date       18.04.20
2822
        @history    18.05.08    Jeongwoo type index changed
2823
    '''
2824
    def getSymbolTypeList(self):
2825
        symbolTypeList = []
2826

    
2827
        try:
2828
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2829

    
2830
            conn = sqlite3.connect(dbPath)
2831
            cursor = conn.cursor()
2832
            sql = 'SELECT * FROM SymbolType ORDER BY type ASC'
2833
            try:
2834
                cursor.execute(sql)
2835
                rows = cursor.fetchall()
2836
                for row in rows:
2837
                    symbolTypeList.append((row[0], row[1], row[2])) # UID, category, type
2838
            except Exception as ex:
2839
                from App import App
2840

    
2841
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2842
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2843
        finally:
2844
            conn.close()
2845

    
2846
        return symbolTypeList
2847

    
2848
    '''
2849
        @brief      Get Symbol Category by Symbol Type
2850
        @author     Jeongwoo
2851
        @date       2018.05.09
2852
    '''
2853
    def getSymbolCategoryByType(self, type):
2854
        category = None
2855
        try:
2856
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
2857
            conn = sqlite3.connect(dbPath)
2858
            cursor = conn.cursor()
2859
            sql = 'SELECT category FROM SymbolType WHERE type = "' + type + '"'
2860
            cursor.execute(sql)
2861
            rows = cursor.fetchall()
2862
            if rows is not None and len(rows) > 0:
2863
                category = rows[0][0]
2864
        except Exception as ex:
2865
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2866
        finally:
2867
            conn.close()
2868

    
2869
        return category
2870

    
2871
    '''
2872
        @brief      Check Symbol Type is included in 'Equipment' Category
2873
        @author     Jeongwoo
2874
        @date       2018.05.09
2875
    '''
2876
    def isEquipmentType(self, type):
2877
        category = self.getSymbolCategoryByType(type)
2878
        return (category is not None and category == 'Equipment')
2879

    
2880
    '''
2881
        @brief      Return Symbol Type Items with "None"
2882
        @author     Jeongwoo
2883
        @date       18.04.06
2884
        @history    Seperate SymbolTypeList and "None"
2885
    '''
2886
    def getSymbolTypeComboBoxItems(self):
2887
        symbolTypeList = self.getSymbolTypeList()
2888
        symbolTypeList.insert(0, ('None', 'None', 'None'))
2889

    
2890
        return symbolTypeList
2891

    
2892
    '''
2893
        @brief  get Base Symbol ComboBox Items
2894
    '''
2895
    def getBaseSymbolComboBoxItems(self, type = None):
2896
        bsymbolNameList = self.getSymbolNameListByType(type)
2897
        bsymbolNameList.sort()
2898
        bsymbolNameList.insert(0, "None")
2899
        return bsymbolNameList
2900

    
2901
    '''
2902
        @brief  get Additional Symbol ComboBox Items
2903
    '''
2904
    def getAdditionalSymbolComboBoxItems(self):
2905
        asymbolNameList = self.getSymbolNameList()
2906
        asymbolNameList.sort()
2907
        asymbolNameList.insert(0, "None")
2908
        return asymbolNameList
2909

    
2910
    '''
2911
        @brief  get Additional Symbol's default direction ComboBox Items
2912
    '''
2913
    def getDefaultSymbolDirectionComboBoxItems(self):
2914
        return [("UP", 0), ("DOWN", 2), ("LEFT", 3), ("RIGHT", 1)]
2915
    
2916
    '''
2917
        @brief  getter of activeDrawing
2918
        @author humkyung
2919
        @date   2018.07.07
2920
    '''
2921
    @property
2922
    def activeDrawing(self):
2923
        return self._activeDrawing
2924

    
2925
    '''
2926
        @brief  setter of activeDrawing
2927
        @author humkyung
2928
        @date   2018.07.07
2929
    '''
2930
    @activeDrawing.setter
2931
    def activeDrawing(self, value):
2932
        self._activeDrawing = value
2933

    
2934
    '''
2935
        @brief      delete data list before save
2936
        @author     euisung
2937
        @date       2018.11.05
2938
    '''
2939
    def deleteDataListBeforeSave(self):
2940
        try:
2941
            # Creates or opens a file called mydb with a SQLite3 DB
2942
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2943
            conn = sqlite3.connect(dbPath)
2944
            # Get a cursor object
2945
            cursor = conn.cursor()
2946
            pidNo = self.activeDrawing.name
2947
            sql = "delete from LINE_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2948
            cursor.execute(sql)
2949
            sql = "delete from EQUIPMENT_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2950
            cursor.execute(sql)
2951
            sql = "delete from VALVE_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2952
            cursor.execute(sql)
2953
            sql = "delete from INSTRUMENT_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2954
            cursor.execute(sql)
2955
            sql = "delete from NOTE_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2956
            cursor.execute(sql)
2957
            sql = "delete from TitleBlockValues where Drawings_UID = '{}'".format(pidNo)
2958
            cursor.execute(sql)
2959

    
2960
            sql = "delete from Attributes where Drawings_Name = '{}'".format(pidNo)
2961
            cursor.execute(sql)
2962

    
2963
            conn.commit()
2964

    
2965
        # Catch the exception
2966
        except Exception as ex:
2967
            # Roll back any change if something goes wrong
2968
            conn.rollback()
2969
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2970
        finally:
2971
            # Close the db connection
2972
            conn.close()
2973

    
2974
    def getColNames(self, table):
2975
        """
2976
        return column names of given table and attribute names if tabe is VALVE_DATA_LIST or EQUIPMET_DATA_LIST
2977
        """
2978
        res = None
2979
        try:
2980
            # Creates or opens a file called mydb with a SQLite3 DB
2981
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2982
            conn = sqlite3.connect(dbPath)
2983
            cursor = conn.execute('select * from {}'.format(table))
2984
            res = [col_name[0] for col_name in cursor.description]
2985

    
2986
            if table == 'EQUIPMET_DATA_LIST'or table == 'VALVE_DATA_LIST':
2987
                sql = 'select distinct c.Attribute from {} a left join Attributes b on a.uid=b.symbol_uid ' \
2988
                                                            'left join SymbolAttribute c on b.SymbolAttribute_UID=c.UID where c.Attribute is not NULL'.format(table)
2989
                cursor = conn.execute(sql)
2990
                rows = cursor.fetchall()
2991
                for row in rows:
2992
                    res.append(row[0])
2993
        # Catch the exception
2994
        except Exception as ex:
2995
            # Roll back any change if something goes wrong
2996
            conn.rollback()
2997
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2998
        finally:
2999
            # Close the db connection
3000
            conn.close()
3001

    
3002
        return res
3003

    
3004
    '''
3005
        @brief  getter of OCRData
3006
        @author humkyung
3007
        @date   2018.11.19
3008
    '''
3009
    @property
3010
    def OCRData(self):
3011
        if self._OCRData is None:
3012
            configs = self.getConfigs('Text Recognition', 'OCR Data')
3013
            self._OCRData = configs[0].value if 1 == len(configs) else 'eng'
3014

    
3015
        return self._OCRData
3016

    
3017
    '''
3018
        @brief  setter of OCRData
3019
        @author humkyung
3020
        @date   2018.11.19
3021
    '''
3022
    @OCRData.setter
3023
    def OCRData(self, value):
3024
        self._OCRData = value