프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / DTI_PID / AppDocData.py @ 6547b5f1

이력 | 보기 | 이력해설 | 다운로드 (106 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._colors = None
108
        self._lineNoProperties = None
109
        self._lineTypes = None
110
        self._lineTypeConfigs = None
111
        self._activeDrawing = None
112
        self._hmbTable = None
113
        self._titleBlockProperties = None
114

    
115
    '''
116
        @brief      clear
117
        @author     humkyung
118
        @date       2018.09.06
119
    '''
120
    def clear(self):
121
        self._imgFilePath = None
122
        self.imgName = None
123
        self.imgWidth = 0
124
        self.imgHeight = 0
125
        self._imgSrc = None
126

    
127
        self._areas.clear()
128
        self.equipments.clear()
129
        self.lineNos.clear()
130
        self.lines.clear()
131
        self.texts.clear()
132
        self.symbols.clear()
133
        self._colors = None
134
        self._lineNoProperties = None
135
        self._lineTypes = None
136
        self._lineTypeConfigs = None
137
        self._activeDrawing = None
138
        self._hmbTable = None
139
        self._titleBlockProperties = None
140

    
141
    '''
142
        @brief      Get drawing file list
143
        @author     euisung
144
        @date       2018.09.28
145
    '''
146
    def getDrawingFileList(self):
147
        try:
148
            project = AppDocData.instance().getCurrentProject()
149
            path = project.getDrawingFilePath()
150
            drawingFileList = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
151
            drawingFileList.sort()
152
        except Exception as ex:
153
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
154

    
155
        return drawingFileList
156

    
157
    '''
158
        @brief      Get Training file list
159
        @author     euisung
160
        @date       2018.10.16
161
    '''
162
    def getTrainingFileList(self):
163
        try:
164
            project = AppDocData.instance().getCurrentProject()
165
            path = project.getTrainingFilePath()
166
            drawingFileList = os.listdir(path)
167
            drawingFileList.sort()
168
        except Exception as ex:
169
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
170

    
171
        return drawingFileList
172

    
173
    '''
174
        @brief      Get DB file path in ProgramData
175
        @author     Jeongwoo
176
        @date       2018.06.27
177
        @history    2018.06.29  Jeongwoo    Change method to get template db path
178
    '''
179
    def getTemplateDbPath(self):
180
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
181
        templateDbPath = os.path.join(path, 'Template.db')
182
        return templateDbPath
183

    
184
    def getAppDbPath(self):
185
        """
186
        @brief      Get application DB file path in ProgramData
187
        @author     humkyung
188
        @date       2018.10.01
189
        """
190

    
191
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
192
        app_database = os.path.join(path, 'App.db')
193
        return app_database 
194

    
195
    '''
196
        @brief  getter of colors 
197
        @author humkyung
198
        @date   2018.06.18
199
    '''
200
    @property
201
    def colors(self):
202
        if self._colors is None:
203
            self._colors = []
204
            try:
205
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath() , 'ITI_PID.db')
206

    
207
                conn = sqlite3.connect(dbPath)
208
                cursor = conn.cursor()
209
                sql = 'SELECT UID,RED,GREEN,BLUE FROM Colors'
210
                cursor.execute(sql)
211
                rows = cursor.fetchall()
212
                for row in rows:
213
                    self._colors.append(Color(int(row[0]), int(row[1]), int(row[2]), int(row[3])))
214
            # Catch the exception
215
            except Exception as ex:
216
                # Roll back any change if something goes wrong
217
                conn.rollback()
218

    
219
                from App import App 
220
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
221
                App.mainWnd().addMessage.emit(MessageType.Error, message)
222
            finally:
223
                conn.close()
224

    
225
        return self._colors
226

    
227
    '''
228
        @brief  setter of colors
229
        @author humkyung
230
        @date   2018.06.18
231
    '''
232
    @colors.setter
233
    def colors(self, value):
234
        self._colors = value
235

    
236
    '''
237
        @brief      set image file path
238
        @author     humkyung
239
        @date       2018.07.30
240
    '''
241
    def setImgFilePath(self, path):
242
        self._imgFilePath = path
243
        self.imgName = os.path.splitext(os.path.basename(self._imgFilePath))[0]
244

    
245
    '''
246
        @brief      getter of imgSrc
247
        @author     humkyung
248
        @date       2018.07.30
249
    '''
250
    @property
251
    def imgSrc(self):
252
        import cv2
253

    
254
        if self._imgSrc is None and self._imgFilePath is not None and os.path.isfile(self._imgFilePath):
255
            self._imgSrc = cv2.cvtColor(cv2.imread(self._imgFilePath), cv2.COLOR_BGR2GRAY)
256
            blur = cv2.GaussianBlur(self._imgSrc , (5,5),0)
257
            self._imgSrc = cv2.threshold(self._imgSrc , 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
258
        
259
        return self._imgSrc
260

    
261
    '''
262
        @brief      setter of imgSrc
263
        @author     humkyung
264
        @date       2018.07.30
265
    '''
266
    @imgSrc.setter
267
    def imgSrc(self, value):
268
        self._imgSrc = value
269

    
270
    '''
271
        @brief      reset imgSrc
272
        @author     humkyung
273
        @date       2018.07.30
274
    '''
275
    def resetImgSrc(self):
276
        self._imgSrc = None
277

    
278
    '''
279
        @brief  getter of line type configs
280
        @author humkyung
281
        @date   2018.06.28
282
    '''
283
    @property
284
    def lineTypeConfigs(self):
285
        from PyQt5.QtCore import Qt
286

    
287
        if self._lineTypeConfigs is None:
288
            self._lineTypeConfigs = []
289

    
290
            styleMap = [('SolidLine', Qt.SolidLine), ('DashLine', Qt.DashLine), ('DotLine', Qt.DotLine), ('DashDotLine', Qt.DashDotLine), 
291
                ('DashDotDotLine', Qt.DashDotDotLine), ('CustomDashLine', Qt.CustomDashLine)]
292

    
293
            configs = self.getConfigs('LineTypes')
294
            for config in configs:
295
                width, _style = config.value.split(',')
296
                matches = [param for param in styleMap if param[0] == _style]
297
                style = matches[0][1] if matches else Qt.SolidLine
298
                self._lineTypeConfigs.append((config.key, int(width), style))
299
        
300
        return self._lineTypeConfigs
301

    
302
    '''
303
        @brief  setter of line type configs
304
        @author humkyung
305
        @date   2018.06.28
306
    '''
307
    @lineTypeConfigs.setter
308
    def lineTypeConfigs(self, value):
309
        self._lineTypeConfigs = value
310

    
311
    '''
312
        @brief      getter of hmb table
313
        @author     humkyung
314
        @date       2018.07.16
315
    '''
316
    @property
317
    def hmbTable(self):
318
        from HMBTable import HMBTable
319

    
320
        if self._hmbTable is None:
321
            self._hmbTable = HMBTable()
322
            self._hmbTable.loadData()
323
        
324
        return self._hmbTable
325

    
326
    '''
327
        @brief      setter of hmb table
328
        @author     humkyung
329
        @date       2018.07.16
330
    '''
331
    @hmbTable.setter
332
    def hmbTable(self, value):
333
        self._hmbTable = value
334

    
335
    '''
336
        @brief  get line type config of given line type
337
        @author humkyung
338
        @date   2018.06.28
339
    '''
340
    def getLineTypeConfig(self, lineType):
341
        from PyQt5.QtCore import Qt
342

    
343
        matches = [config for config in self.lineTypeConfigs if config[0] == lineType]
344
        return matches[0] if matches else (lineType, 5, Qt.SolidLine)        
345

    
346
    def setCurrentPidSource(self, image):
347
        self.imgWidth, self.imgHeight = image.size
348

    
349
        self.currentPidSource = Source(image)
350

    
351
    def getCurrentPidSource(self):
352
        return self.currentPidSource
353

    
354
    '''
355
        @brief      Check if Exist data or not, Moved from SG_DbHelper
356
        @author     Jeongwoo
357
        @date       2018.05.03
358
    '''
359
    def isExistData(self, fieldName, data):
360
        rows = None
361
        try:
362
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
363

    
364
            conn = sqlite3.connect(dbPath)
365
            cursor = conn.cursor()
366
            sql = ""
367
            if isinstance(data, str):
368
                sql = "SELECT * FROM Symbol WHERE " + fieldName + " = '"+ data +"'"
369
            else:
370
                sql = "SELECT * FROM Symbol WHERE " + fieldName + " = "+ str(data) +""
371
            cursor.execute(sql)
372
            rows = cursor.fetchall()
373
        # Catch the exception
374
        except Exception as ex:
375
            # Roll back any change if something goes wrong
376
            conn.rollback()
377
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
378
        finally:
379
            conn.close()
380
            if rows is not None and len(rows) > 0:
381
                return True
382
            else:
383
                return False
384

    
385
    '''
386
        @brief      Check if exist file name or not, Moved from SG_DbHelper
387
        @author     Jeongwoo
388
        @date       2018.05.03
389
    '''
390
    def isExistFileName(self, name):
391
        rows = None
392
        try:
393
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
394
            conn = sqlite3.connect(dbPath)
395
            cursor = conn.cursor()
396
            sql = "SELECT * FROM Symbol WHERE name = '"+ name +"'"
397
            cursor.execute(sql)
398
            rows = cursor.fetchall()
399
        # Catch the exception
400
        except Exception as ex:
401
            # Roll back any change if something goes wrong
402
            conn.rollback()
403
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
404
        finally:
405
            conn.close()
406
            if rows is not None and len(rows) > 0:
407
                return True
408
            else:
409
                return False
410

    
411
    '''
412
        @brief      Insert new symbol into Symbol Table, Moved from SG_DbHelper
413
        @author     Jeongwoo
414
        @date       2018.05.03
415
    '''
416
    def insertSymbol(self, symbol):
417
        isAdded = False
418
        try:
419
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
420
            conn = sqlite3.connect(dbPath)
421
            
422
            INSERT_SYMBOL_SQL = '''
423
                INSERT INTO Symbol(name, type, threshold, minMatchPoint, isDetectOrigin, rotationCount, ocrOption, isContainChild, originalPoint, connectionPoint, baseSymbol, additionalSymbol, isExceptDetect, hasInstrumentLabel) 
424
                VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
425
            '''
426

    
427
            cursor = conn.cursor()
428
            query = ( symbol.getName(), symbol.getType(), symbol.getThreshold()
429
                           , symbol.getMinMatchCount(), symbol.getIsDetectOnOrigin(), symbol.getRotationCount()
430
                           , symbol.getOcrOption(), symbol.getIsContainChild()
431
                           , symbol.getOriginalPoint(), symbol.getConnectionPoint()
432
                           , symbol.getBaseSymbol(), symbol.getAdditionalSymbol(), symbol.getIsExceptDetect(), symbol.getHasInstrumentLabel())
433
            cursor.execute(INSERT_SYMBOL_SQL, query)
434
            conn.commit()
435
            isAdded = True
436
        # Catch the exception
437
        except Exception as ex:
438
            # Roll back any change if something goes wrong
439
            conn.rollback()
440
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
441
        finally:
442
            conn.close()
443
            return (isAdded, symbol.getType(), symbol.getName(), symbol.getPath())
444

    
445
    '''
446
        @brief      Update symbol in Symbol Table, Moved from SG_DbHelper
447
        @author     Jeongwoo
448
        @date       2018.05.03
449
    '''
450
    def updateSymbol(self, symbol):
451
        isUpdated = False
452
        try:
453
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
454
            conn = sqlite3.connect(dbPath)
455
            
456
            UPDATE_SYMBOL_SQL = '''
457
                UPDATE Symbol
458
                SET
459
                    name = ?, type = ?, threshold = ?, minMatchPoint = ?, isDetectOrigin = ?,
460
                    rotationCount = ?, ocrOption = ?, isContainChild = ?, originalPoint = ?, connectionPoint = ?,
461
                    baseSymbol = ?, additionalSymbol = ?, isExceptDetect = ?, hasInstrumentLabel = ?
462
                WHERE uid = ?
463
            '''
464
            
465
            cursor = conn.cursor()
466
            query = (symbol.getName(), symbol.getType(), symbol.getThreshold()
467
                           , symbol.getMinMatchCount(), symbol.getIsDetectOnOrigin(), symbol.getRotationCount()
468
                           , symbol.getOcrOption(), symbol.getIsContainChild()
469
                           , symbol.getOriginalPoint(), symbol.getConnectionPoint()
470
                           , symbol.getBaseSymbol(), symbol.getAdditionalSymbol(), symbol.getIsExceptDetect(), symbol.getHasInstrumentLabel(), symbol.getUid())
471
            cursor.execute(UPDATE_SYMBOL_SQL, query)
472
            conn.commit()
473
            isUpdated = True
474
        # Catch the exception
475
        except Exception as ex:
476
            # Roll back any change if something goes wrong
477
            conn.rollback()
478
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
479
        finally:
480
            conn.close()
481
            return (isUpdated, symbol.getType(), symbol.getName(), symbol.getPath())
482

    
483
    '''
484
        @brief      Get Detecting Target Symbol List (Field 'isExceptDetect' == False(0))
485
        @author     Jeongwoo
486
        @date       18.04.24
487
        @history    humkyung 2018.06.28 select symbol order by threshold descending
488
    '''
489
    def getTargetSymbolList(self):
490
        targetSymbolList = []
491

    
492
        try:
493
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
494

    
495
            conn = sqlite3.connect(dbPath)
496
            cursor = conn.cursor()
497
            sql = 'SELECT * FROM Symbol WHERE isExceptDetect = 0 order by threshold desc'
498
            try:
499
                cursor.execute(sql)
500
                rows = cursor.fetchall()
501
                for row in rows:
502
                    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
503
                    targetSymbolList.append(sym)
504
            except Exception as ex:
505
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
506
        finally:
507
            conn.close()
508

    
509
        return targetSymbolList
510

    
511
    '''
512
        @brief  build application database
513
        @author humkyung
514
        @date   2018.04.20
515
    '''
516
    def buildAppDatabase(self):
517
        try:
518
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
519
            appDatabaseFilePath = os.path.join(path, 'App.db')
520

    
521
            # Creates or opens a file called mydb with a SQLite3 DB
522
            conn = sqlite3.connect(appDatabaseFilePath)
523
            # Get a cursor object
524
            cursor = conn.cursor()
525

    
526
            sqlFiles = ['App.Configuration.sql', 'App.Styles.sql']
527
            for sqlFile in sqlFiles:
528
                filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', sqlFile)
529
                try:
530
                    file = QFile(filePath)
531
                    file.open(QFile.ReadOnly)
532
                    sql = file.readAll()
533
                    sql = str(sql, encoding='utf8')
534
                    cursor.executescript(sql)
535
                finally:
536
                    file.close()
537
            conn.commit()
538
        # Catch the exception
539
        except Exception as ex:
540
            # Roll back any change if something goes wrong
541
            conn.rollback()
542
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
543
        finally:
544
            # Close the db connection
545
            conn.close()
546

    
547
    '''
548
        @brief  load app style
549
        @author humkyung
550
        @date   2018.04.20
551
    '''
552
    def loadAppStyle(self):
553
        style = 'Fusion'
554

    
555
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
556
        if not os.path.exists(path): os.makedirs(path)
557

    
558
        self.buildAppDatabase()
559
        try:
560
            appDatabaseFilePath = os.path.join(path, 'App.db')
561
            # Creates or opens a file called mydb with a SQLite3 DB
562
            conn = sqlite3.connect(appDatabaseFilePath)
563
            # Get a cursor object
564
            cursor = conn.cursor()
565

    
566
            sql = "select Value from Configuration where Section='App' and Key='Style'" 
567
            cursor.execute(sql)
568
            rows = cursor.fetchall()
569
            style = rows[0][0] if 1 == len(rows) else 'Fusion'
570
        # Catch the exception
571
        except Exception as ex:
572
            # Roll back any change if something goes wrong
573
            conn.rollback()
574
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
575
        finally:
576
            # Close the db connection
577
            conn.close()
578

    
579
        return style
580

    
581
    '''
582
        @brief  load app styles and then return a list
583
        @author humkyung
584
        @date   2018.04.20
585
    '''
586
    def loadAppStyles(self):
587
        styles = []
588

    
589
        try:
590
            self.buildAppDatabase()
591

    
592
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
593
            appDatabaseFilePath = os.path.join(path, 'App.db')
594

    
595
            # Creates or opens a file called mydb with a SQLite3 DB
596
            conn = sqlite3.connect(appDatabaseFilePath)
597
            # Get a cursor object
598
            cursor = conn.cursor()
599

    
600
            sql = 'select UID,Value from Styles'
601
            cursor.execute(sql)
602
            rows = cursor.fetchall()
603
            for row in rows: styles.append(row[1])
604
            if 0 == len(rows): rows.append('fusion')
605
        # Catch the exception
606
        except Exception as ex:
607
            # Roll back any change if something goes wrong
608
            conn.rollback()
609
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
610
        finally:
611
            # Close the db connection
612
            conn.close()
613

    
614
        return styles
615

    
616
    '''
617
        @brief  Set current Project
618
        @history    2018.06.27  Jeongwoo    If DB file is not, copy DB file from ProgramData
619
    '''
620
    def setCurrentProject(self, project):
621
        self.project = project
622
        self.makeChildDir()
623
        try:
624
            # Creates or opens a file called mydb with a SQLite3 DB
625
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath() , "ITI_PID.db")
626
            
627
            if not os.path.isfile(dbPath):
628
                templatePath = self.getTemplateDbPath()
629
                templateFile = QFile(templatePath)
630
                templateFile.copy(dbPath)
631
            else:
632
                try:
633
                    conn = sqlite3.connect(dbPath)
634
                    # Get a cursor object
635
                    cursor = conn.cursor()
636

    
637
                    fileNames = os.listdir(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts'))
638
                    for fileName in fileNames:
639
                        if fileName.endswith(".sql") and (1 == len(os.path.splitext(fileName)[0].split('.'))):
640
                            try:
641
                                file = QFile(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', fileName))
642
                                file.open(QFile.ReadOnly)
643
                                sql = file.readAll()
644
                                sql = str(sql, encoding='utf8')
645
                                cursor.executescript(sql)
646
                            finally:
647
                                file.close()
648
                    conn.commit()
649
                except Exception as ex:
650
                    print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
651
                finally:
652
                    conn.close()
653
        # Catch the exception
654
        except Exception as ex:
655
            # Roll back any change if something goes wrong
656
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
657
        finally:
658
            pass
659

    
660
    '''
661
        @brief      Make Directory
662
        @author     Jeongwoo
663
        @date       18.05.08
664
        @history    humkyung 2018.06.19 make 'Tile' directory
665
                    humkyung 2018.07.09 make drawing folder if not exists
666
                    euisung 2018.09.28 make training folder if not exists
667
    '''
668
    def makeChildDir(self):
669
        project = AppDocData.instance().getCurrentProject()
670
        dbDir = project.getDbFilePath()
671
        if not os.path.exists(dbDir):
672
            os.makedirs(dbDir)
673
        imgDir = project.getImageFilePath()
674
        if not os.path.exists(imgDir):
675
            os.makedirs(imgDir)
676
        svgDir = project.getSvgFilePath()
677
        if not os.path.exists(svgDir):
678
            os.makedirs(svgDir)
679
        outputDir = project.getOutputPath()
680
        if not os.path.exists(outputDir):
681
            os.makedirs(outputDir)
682
        tempDir = project.getTempPath()
683
        if not os.path.exists(tempDir):
684
            os.makedirs(tempDir)
685
        drawingPath = project.getDrawingFilePath()
686
        if not os.path.exists(drawingPath):
687
            os.makedirs(drawingPath)
688
        trainingPath = project.getTrainingFilePath()
689
        if not os.path.exists(trainingPath):
690
            os.makedirs(trainingPath)
691
        
692
        path = os.path.join(tempDir, 'Tile')
693
        if not os.path.exists(path):
694
            os.makedirs(path)
695

    
696
    '''
697
        @brief  Get current Project
698
    '''
699
    def getCurrentProject(self):
700
        return self.project
701

    
702
    '''
703
        @brief      return project database path
704
        @history    humkyung 2018.04.19 return Project.db in Program Data folder instead of PROJECT_DB_PATH variable
705
    '''
706
    def getPrjDatabasePath(self):
707
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
708
        if not os.path.exists(path): os.makedirs(path)
709

    
710
        prjDatabaseFilePath = os.path.join(path, 'Project.db')
711
        try:
712
            # Creates or opens a file called mydb with a SQLite3 DB
713
            conn = sqlite3.connect(prjDatabaseFilePath)
714
            # Get a cursor object
715
            cursor = conn.cursor()
716

    
717
            filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', 'Project.Projects.sql')
718
            try:
719
                file = QFile(filePath)
720
                file.open(QFile.ReadOnly)
721
                sql = file.readAll()
722
                sql = str(sql, encoding='utf8')
723
                cursor.executescript(sql)
724
            finally:
725
                file.close()
726
            conn.commit()
727
        # Catch the exception
728
        except Exception as ex:
729
            # Roll back any change if something goes wrong
730
            conn.rollback()
731
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
732
        finally:
733
            # Close the db connection
734
            conn.close()
735
        
736
        return prjDatabaseFilePath
737

    
738
    def updateTitleBlockProperties(self, titleBlockProps):
739
        '''
740
            @brief  update title block properties
741
            @author euisung
742
            @date   2018.11.09
743
        '''
744
        try:
745
            originTitleBlockProps = self.getTitleBlockProperties()
746
            deletedTitleBlockProps = []
747
            for originTitleBlockProp in originTitleBlockProps:
748
                for titleBlockProp in titleBlockProps:
749
                    # uid compare for determine delete props
750
                    if originTitleBlockProp[0] == titleBlockProp[0]:
751
                        break
752
                deletedTitleBlockProps.append(originTitleBlockProp[0])
753
            
754
            # Creates or opens a file called mydb with a SQLite3 DB
755
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
756
            conn = sqlite3.connect(dbPath)
757
            # Get a cursor object
758
            cursor = conn.cursor()
759

    
760
            for deletedTitleBlockProp in deletedTitleBlockProps:
761
                sql = "delete from TitleBlockProperties where UID='{}'".format(deletedTitleBlockProp)
762
                cursor.execute(sql)
763

    
764
            for titleBlockProp in titleBlockProps:
765
                sql = "insert or replace into TitleBlockProperties values(?,?,?)"
766
                param = (titleBlockProp[0], titleBlockProp[1], titleBlockProp[2]) # uid, name, area
767
                cursor.execute(sql, param)
768
            conn.commit()
769
        # Catch the exception
770
        except Exception as ex:
771
            # Roll back any change if something goes wrong
772
            conn.rollback()
773
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
774
        finally:
775
            # Close the db connection
776
            conn.close()
777

    
778
        self._titleBlockProperties = None
779
    
780
    def getTitleBlockProperties(self):
781
        '''
782
            @brief  return title block properties
783
            @author euisung
784
            @date   2018.11.09
785
        '''
786
        res = None
787
        if self._titleBlockProperties is None:
788
            try:
789
                self._titleBlockProperties = []
790

    
791
                # Creates or opens a file called mydb with a SQLite3 DB
792
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
793
                db = sqlite3.connect(dbPath)
794
                # Get a cursor object
795
                cursor = db.cursor()
796

    
797
                sql = "select UID, Name, AREA from TitleBlockProperties" 
798
                cursor.execute(sql)
799
                rows = cursor.fetchall()
800
                for row in rows:
801
                    attr = []
802
                    attr.append(row[0]) # uid
803
                    attr.append(row[1]) # name
804
                    attr.append(row[2]) # area
805
                    self._titleBlockProperties.append(attr)
806
                
807
                res = self._titleBlockProperties
808
            # Catch the exception
809
            except Exception as ex:
810
                # Roll back any change if something goes wrong
811
                db.rollback()
812
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
813
            finally:
814
                # Close the db connection
815
                db.close()
816
        else:
817
            res = self._titleBlockProperties
818

    
819
        return res
820

    
821
    '''
822
        @brief  return line properties
823
        @author humkyung
824
        @date   2018.04.09
825
    '''
826
    def getLineProperties(self):
827
        from SymbolAttr import SymbolAttr
828

    
829
        res = None
830
        if self._lineNoProperties is None:
831
            try:
832
                self._lineNoProperties = []
833

    
834
                # Creates or opens a file called mydb with a SQLite3 DB
835
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
836
                db = sqlite3.connect(dbPath)
837
                # Get a cursor object
838
                cursor = db.cursor()
839

    
840
                sql = "select UID, Name, DisplayName, Type, LimitNumber, [index] from LineProperties order by [index]" 
841
                cursor.execute(sql)
842
                rows = cursor.fetchall()
843
                for row in rows:
844
                    attr = SymbolAttr()
845
                    attr.UID = row[0]
846
                    attr.Attribute = row[1]
847
                    attr.DisplayAttribute = row[2]
848
                    attr.AttributeType = row[3]
849
                    attr.Length = row[4]
850
                    self._lineNoProperties.append(attr)
851
                
852
                res = self._lineNoProperties
853
            # Catch the exception
854
            except Exception as ex:
855
                # Roll back any change if something goes wrong
856
                db.rollback()
857
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
858
            finally:
859
                # Close the db connection
860
                db.close()
861
        else:
862
            res = self._lineNoProperties
863

    
864
        return res
865

    
866
    '''
867
        @brief  return line properties
868
        @author humkyung
869
        @date   2018.04.09
870
    '''
871
    def getLinePropertiesByUID(self, UID):
872
        from SymbolAttr import SymbolAttr
873

    
874
        res = []
875
        try:
876
            # Creates or opens a file called mydb with a SQLite3 DB
877
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
878
            db = sqlite3.connect(dbPath)
879
            # Get a cursor object
880
            cursor = db.cursor()
881

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

    
902
        return res
903

    
904
    '''
905
        @brief  return line types 
906
        @author humkyung
907
        @date   2018.06.27
908
    '''
909
    def getLineTypes(self):
910
        res = []
911
        try:
912
            # Creates or opens a file called mydb with a SQLite3 DB
913
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
914
            db = sqlite3.connect(dbPath)
915
            # Get a cursor object
916
            cursor = db.cursor()
917

    
918
            sql = "select Name from LineTypes order by Name" 
919
            cursor.execute(sql)
920
            rows = cursor.fetchall()
921
            for row in rows:
922
                res.append(row[0])
923
        # Catch the exception
924
        except Exception as ex:
925
            # Roll back any change if something goes wrong
926
            db.rollback()
927
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
928
        finally:
929
            # Close the db connection
930
            db.close()
931

    
932
        return res
933

    
934
    '''
935
        @brief      Insert New Project Info
936
        @author     Jeongwoo
937
        @date       2018.04.06
938
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
939
    '''
940
    def insertProjectInfo(self, dir):
941
        try:
942
            prjDatabaseFilePath = self.getPrjDatabasePath()
943
            conn = sqlite3.connect(prjDatabaseFilePath)
944
            folderName = dir.split('/')[-1]
945
            if folderName:
946
                nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
947
                sql = "INSERT INTO Projects(Name, Path, CreatedDate, UpdatedDate) VALUES('" + folderName + "', '" + dir + "', '" + nowDate + "', '" + nowDate + "')"
948
                cur = conn.cursor()
949
                cur.execute(sql)
950
                conn.commit()
951
            else:
952
                print("Empty folder name")
953
        except Exception as ex:
954
            # Roll back any change if something goes wrong
955
            conn.rollback()
956
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
957
        finally:
958
            conn.close()
959

    
960
    '''
961
        @brief      Update Project UpdatedDate Field
962
        @author     Jeongwoo
963
        @date       2018.04.06
964
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
965
    '''
966
    def updateProjectUpdatedDate(self, id):
967
        try:
968
            prjDatabaseFilePath = self.getPrjDatabasePath()
969
            conn = sqlite3.connect(prjDatabaseFilePath)
970
            nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
971
            sql = '''
972
                UPDATE Projects
973
                SET UpdatedDate = ?
974
                WHERE Id = ?
975
            '''
976
            cur = conn.cursor()
977
            cur.execute(sql, (nowDate, id))
978
            conn.commit()
979
        except Exception as ex:
980
            # Roll back any change if something goes wrong
981
            conn.rollback()
982
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
983
        finally:
984
            conn.close()
985

    
986
    '''
987
        @brief  get project list from database
988
        @history    humkyung 2018.04.18 add only project which's project exists
989
    '''
990
    def getProjectList(self):
991
        from Project import Project
992

    
993
        projectList = []
994

    
995
        try:
996
            conn = sqlite3.connect(self.getPrjDatabasePath())
997
            cursor = conn.cursor()
998
            sql = 'SELECT id,name,path,createddate,updateddate  FROM Projects ORDER BY UpdatedDate DESC'
999
            try:
1000
                cursor.execute(sql)
1001
                rows = cursor.fetchall()
1002
                for row in rows:
1003
                    if os.path.isdir(row[2]):   # check if folder exists
1004
                        projectList.append(Project(row[0], row[1], row[2], row[3], row[4]))
1005
            except Exception as ex:
1006
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1007
        finally:
1008
            conn.close()
1009

    
1010
        return projectList
1011

    
1012
    '''
1013
        @brief  get sliding window size
1014
        @author humkyung
1015
    '''
1016
    def getSlidingWindowSize(self):
1017
        res = [10,10]
1018
        try:
1019
            configs = self.getConfigs('Sliding Window')
1020
            for config in configs:
1021
                if config.key == 'Width':
1022
                    res[0] = int(config.value)
1023
                elif config.key == 'Height':
1024
                    res[1] = int(config.value)
1025
        # Catch the exception
1026
        except Exception as ex:
1027
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1028
        
1029
        return res
1030

    
1031
    '''
1032
        @brief  get line no configuration
1033
        @author humkyung
1034
        @date   2018.04.16
1035
    '''
1036
    def getLineNoConfiguration(self):
1037
        res = None
1038
        try:
1039
            # Creates or opens a file called mydb with a SQLite3 DB
1040
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1041
            conn = sqlite3.connect(dbPath)
1042
            # Get a cursor object
1043
            cursor = conn.cursor()
1044

    
1045
            delimiter = None
1046
            sql = "select * from configuration where section='Line No' and key='Delimiter"
1047
            cursor.execute(sql)
1048
            rows = cursor.fetchall()
1049
            if len(rows) == 1:
1050
                delimiter = rows[0][2]
1051

    
1052
            if delimiter is not None:
1053
                sql = "select * from configuration where section='Line No' and key='Configuration'"
1054
                cursor.execute(sql)
1055
                rows = cursor.fetchall()
1056
                if len(rows) == 1:
1057
                    res = rows[0][2].split(delimiter)
1058
        # Catch the exception
1059
        except Exception as ex:
1060
            # Roll back any change if something goes wrong
1061
            conn.rollback()
1062
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1063
        finally:
1064
            # Close the db connection
1065
            conn.close()
1066
        
1067
        return res
1068

    
1069
    '''
1070
        @brief  get area list
1071
        @author humkyung
1072
    '''
1073
    def getAreaList(self):
1074
        from Area import Area
1075

    
1076
        if len(self._areas) == 0:
1077
            try:
1078
                # Creates or opens a file called mydb with a SQLite3 DB
1079
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1080
                conn = sqlite3.connect(dbPath)
1081
                # Get a cursor object
1082
                cursor = conn.cursor()
1083

    
1084
                sql = "select * from configuration where section='Area'"
1085
                cursor.execute(sql)
1086
                rows = cursor.fetchall()
1087
                for row in rows:
1088
                    name = row[1]
1089
                    area = Area(name)
1090
                    area.parse(row[2])
1091
                    self._areas.append(area)
1092
            # Catch the exception
1093
            except Exception as ex:
1094
                # Roll back any change if something goes wrong
1095
                conn.rollback()
1096
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1097
            finally:
1098
                # Close the db connection
1099
                conn.close()
1100
        
1101
        return self._areas 
1102

    
1103
    '''
1104
        @brief  get area of given name
1105
        @author humkyung
1106
        @date   2018.04.07
1107
    '''
1108
    def getArea(self, name):
1109
        areas = self.getAreaList()
1110
        matches = [area for area in areas if area.name==name]
1111
        if 1 == len(matches): return matches[0]
1112

    
1113
        return None
1114

    
1115
    '''
1116
        @brief  get configurations
1117
        @author humkyung
1118
        @date   2018.04.16
1119
        @history kyouho 2018.07.09 change query method
1120
    '''
1121
    def getConfigs(self, section, key=None):
1122
        res = []
1123

    
1124
        try:
1125
            # Creates or opens a file called mydb with a SQLite3 DB
1126
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1127
            conn = sqlite3.connect(dbPath)
1128
            # Get a cursor object
1129
            cursor = conn.cursor()
1130

    
1131
            if key is not None:
1132
                sql = "select * from configuration where section=? and key=?"
1133
                param = (section, key)
1134
            else:
1135
                sql = "select * from configuration where section=?"
1136
                param = (section,)
1137

    
1138
            cursor.execute(sql, param)
1139
            rows = cursor.fetchall()
1140
            for row in rows:
1141
                res.append(Config(row[0], row[1], row[2]))
1142
        # Catch the exception
1143
        except Exception as ex:
1144
            # Roll back any change if something goes wrong
1145
            conn.rollback()
1146
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1147
        finally:
1148
            # Close the db connection
1149
            conn.close()
1150

    
1151
        return res
1152

    
1153
    def getAppConfigs(self, section, key=None):
1154
        """
1155
            @brief  get application configurations
1156
            @author humkyung
1157
            @date   2018.11.01
1158
        """
1159

    
1160
        res = []
1161

    
1162
        try:
1163
            # Creates or opens a file called mydb with a SQLite3 DB
1164
            dbPath = self.getAppDbPath()
1165
            conn = sqlite3.connect(dbPath)
1166
            # Get a cursor object
1167
            cursor = conn.cursor()
1168

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

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

    
1189
        return res
1190

    
1191
    '''
1192
        @brief      save configurations
1193
        @author     humkyung
1194
        @date       2018.04.16
1195
        @history    humkyung 2018.07.03 replace ' with " if value has '
1196
                    kyouho 2018.07.09 change query method
1197
    '''
1198
    def saveConfigs(self, configs):
1199
        try:
1200
            # Creates or opens a file called mydb with a SQLite3 DB
1201
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
1202
            conn = sqlite3.connect(dbPath)
1203
            # Get a cursor object
1204
            cursor = conn.cursor()
1205

    
1206
            for config in configs:
1207
                value = config.value
1208
                if type(value) is str and "'" in value:
1209
                    value = value.replace("'", "''")
1210

    
1211
                sql = "insert or replace into configuration values(?,?,?)"
1212
                param = (config.section, config.key, value)
1213

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

    
1225
    def saveAppConfigs(self, configs):
1226
        """
1227
        @brief      save application configurations
1228
        @author     humkyung
1229
        @date       2018.10.01
1230
        """
1231

    
1232
        try:
1233
            # Creates or opens a file called mydb with a SQLite3 DB
1234
            dbPath = self.getAppDbPath()
1235
            conn = sqlite3.connect(dbPath)
1236
            # Get a cursor object
1237
            cursor = conn.cursor()
1238

    
1239
            for config in configs:
1240
                value = config.value
1241
                if type(value) is str and "'" in value:
1242
                    value = value.replace("'", "''")
1243

    
1244
                sql = "insert or replace into configuration values(?,?,?)"
1245
                param = (config.section, config.key, value)
1246

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

    
1258
    '''
1259
        @brief  delete configurations
1260
        @author humkyung
1261
        @date   2018.06.29
1262
    '''
1263
    def deleteConfigs(self, section, key=None):
1264
        try:
1265
            # Creates or opens a file called mydb with a SQLite3 DB
1266
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
1267
            conn = sqlite3.connect(dbPath)
1268
            # Get a cursor object
1269
            cursor = conn.cursor()
1270

    
1271
            if key is not None:
1272
                sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
1273
            else:
1274
                sql = "delete from configuration where section='{}'".format(section)
1275
            cursor.execute(sql)
1276

    
1277
            conn.commit()
1278
        # Catch the exception
1279
        except Exception as ex:
1280
            # Roll back any change if something goes wrong
1281
            conn.rollback()
1282
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1283
        finally:
1284
            # Close the db connection
1285
            conn.close()
1286

    
1287
    def deleteAppConfigs(self, section, key=None):
1288
        """
1289
        @brief  delete application configurations
1290
        @author humkyung
1291
        @date   2018.11.01
1292
        """
1293

    
1294
        try:
1295
            # Creates or opens a file called mydb with a SQLite3 DB
1296
            dbPath = self.getAppDbPath()
1297
            conn = sqlite3.connect(dbPath)
1298
            # Get a cursor object
1299
            cursor = conn.cursor()
1300

    
1301
            if key is not None:
1302
                sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
1303
            else:
1304
                sql = "delete from configuration where section='{}'".format(section)
1305
            cursor.execute(sql)
1306

    
1307
            conn.commit()
1308
        # Catch the exception
1309
        except Exception as ex:
1310
            # Roll back any change if something goes wrong
1311
            conn.rollback()
1312
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1313
        finally:
1314
            # Close the db connection
1315
            conn.close()
1316

    
1317
    '''
1318
        @brief      set area list
1319
        @history    humkyung 2018.05.18 round area coordinate and dimension before saving
1320
    '''
1321
    def setAreaList(self, areas):
1322
        for area in areas:
1323
            matches = [x for x in self._areas if x.name==area.name]
1324
            if 1 == len(matches):
1325
                matches[0].x = area.x
1326
                matches[0].y = area.y
1327
                matches[0].width = area.width
1328
                matches[0].height = area.height
1329
            elif 0 == len(matches):
1330
                self._areas.append(area)
1331

    
1332
        try:
1333
            # Creates or opens a file called mydb with a SQLite3 DB
1334
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
1335
            conn = sqlite3.connect(dbPath)
1336
            # Get a cursor object
1337
            cursor = conn.cursor()
1338

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

    
1343
            conn.commit()
1344
        # Catch the exception
1345
        except Exception as ex:
1346
            # Roll back any change if something goes wrong
1347
            conn.rollback()
1348
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1349
        finally:
1350
            # Close the db connection
1351
            conn.close()
1352
            
1353
    '''
1354
        @brief  get symbol name list
1355
    '''
1356
    def getSymbolNameList(self):
1357
        symbolNametList = []
1358

    
1359
        try:
1360
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
1361

    
1362
            conn = sqlite3.connect(dbPath)
1363
            cursor = conn.cursor()
1364
            sql = 'SELECT * FROM SymbolName'
1365
            try:
1366
                cursor.execute(sql)
1367
                rows = cursor.fetchall()
1368
                for row in rows:
1369
                    symbolNametList.append(row[2]) # Name String
1370
            except Exception as ex:
1371
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1372
        finally:
1373
            conn.close()
1374

    
1375
        return symbolNametList
1376

    
1377
    '''
1378
        @brief      get symbol name list by symbol Type
1379
        @author     Jeongwoo
1380
        @date       18.04.06
1381
        @history    .
1382
    '''
1383
    def getSymbolNameListByType(self, type):
1384
        symbolNametList = []
1385

    
1386
        try:
1387
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
1388

    
1389
            conn = sqlite3.connect(dbPath)
1390
            cursor = conn.cursor()
1391
            sql = ''
1392
            if type is not None:
1393
                sql = 'SELECT * FROM SymbolName WHERE type = "' + type + '"'
1394
                try:
1395
                    cursor.execute(sql)
1396
                    rows = cursor.fetchall()
1397
                    for row in rows:
1398
                        symbolNametList.append(row[2]) # Name String
1399
                except Exception as ex:
1400
                    print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1401
        finally:
1402
            conn.close()
1403

    
1404
        return symbolNametList
1405

    
1406
    '''
1407
        @brief  delete added symbol data
1408
    '''
1409
    def deleteSymbol(self, fileName):
1410
        ret = False
1411
        try:
1412
            dbPath = self.getCurrentProject().getPath() + "/db/ITI_PID.db"
1413
            conn = sqlite3.connect(dbPath)
1414
            cursor = conn.cursor()
1415
            sql = "DELETE FROM Symbol WHERE name = ?"
1416
            try:
1417
                cursor.execute(sql, (fileName,))
1418
                conn.commit()
1419
                ret = True
1420
            except Exception as ex:
1421
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1422
                ret = False
1423
        finally:
1424
            conn.close()
1425
            return (ret, fileName)
1426
        
1427
    '''
1428
        @brief  get symbol name
1429
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1430
    '''
1431
    def getSymbolByQuery(self, fieldName, param):
1432
        ret = None
1433

    
1434
        try:
1435
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
1436
            conn = sqlite3.connect(dbPath)
1437
            cursor = conn.cursor()
1438
            sql = 'SELECT * FROM Symbol WHERE ' + fieldName + ' = "' + param + '"'
1439
            try:
1440
                cursor.execute(sql)
1441
                rows = cursor.fetchall()
1442
                if rows is not None and len(rows) > 0:
1443
                    symbolTuple = rows[0]
1444
                    ret = symbol.SymbolBase(symbolTuple[1], symbolTuple[2], symbolTuple[3]
1445
                                            , symbolTuple[4], symbolTuple[5], symbolTuple[6], symbolTuple[7], symbolTuple[8]
1446
                                            , symbolTuple[9], symbolTuple[10], symbolTuple[11], symbolTuple[12], symbolTuple[13], symbolTuple[14], symbolTuple[0]) ## uid is last item
1447
                    #ret = symbol.SymbolBase(symbolTuple[1], symbolTuple[2], symbolTuple[3], symbolTuple[4]
1448
                    #                        , symbolTuple[5], symbolTuple[6], symbolTuple[7], symbolTuple[8], symbolTuple[9]
1449
                    #                        , symbolTuple[10], symbolTuple[11], symbolTuple[12], symbolTuple[13], symbolTuple[14], symbolTuple[0]) ## uid is last item
1450
            except Exception as ex:
1451
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1452
        finally:
1453
            conn.close()
1454

    
1455
        return ret
1456

    
1457
    '''
1458
        @brief  get symbol name list
1459
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1460
    '''
1461
    def getSymbolListByQuery(self, fieldName=None, param=None):
1462
        ret = []
1463

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

    
1486
        return ret
1487

    
1488
    '''
1489
        @brief      get NominalDiameter
1490
        @author     humkyung
1491
        @date       2018.04.20
1492
        @history    humkyung 2018.04.24 read MetricStr column and set size unit
1493
                    kyouho 2018.07.04 forCheckLineNumber get only inch or metric
1494
                    kyouho 2018.07.16 edit query order by code
1495
    '''
1496
    def getNomialPipeSizeData(self, forCheckLineNumber = False, orderStr = "CODE"):
1497
        res = []
1498
        try:
1499
            configs = self.getConfigs('Line No', 'Size Unit')
1500
            sizeUnit = configs[0].value if 1 == len(configs) else 'Metric'
1501

    
1502
            # Creates or opens a file called mydb with a SQLite3 DB
1503
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1504
            conn = sqlite3.connect(dbPath)
1505
            # Get a cursor object
1506
            cursor = conn.cursor()
1507

    
1508
            sql = "select Code,Metric,Inch,InchStr,MetricStr from NominalDiameter ORDER BY {} ASC".format(orderStr)
1509
            cursor.execute(sql)
1510
            rows = cursor.fetchall()
1511
            for row in rows:
1512
                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])
1513
                pipeSize.sizeUnit = sizeUnit
1514
                if forCheckLineNumber:
1515
                    if sizeUnit == 'Inch' and pipeSize.inchStr:
1516
                        res.append(pipeSize.inchStr)
1517
                    elif sizeUnit == 'Metric' and pipeSize.metricStr:
1518
                        res.append(pipeSize.metricStr)
1519
                else:
1520
                    res.append(pipeSize)
1521
                
1522
        # Catch the exception
1523
        except Exception as ex:
1524
            # Roll back any change if something goes wrong
1525
            conn.rollback()
1526
            
1527
            from App import App 
1528
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1529
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1530
        finally:
1531
            # Close the db connection
1532
            conn.close()
1533

    
1534
        return res
1535

    
1536
    '''
1537
        @brief      insert NominalDiameter table
1538
        @author     kyouho
1539
        @date       2018.07.16
1540
    '''
1541
    def insertNomialPipeSize(self, pipeSizes):
1542
        try:
1543
            # Creates or opens a file called mydb with a SQLite3 DB
1544
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1545
            conn = sqlite3.connect(dbPath)
1546
            # Get a cursor object
1547
            cursor = conn.cursor()
1548
            sql = "INSERT INTO NominalDiameter(Code, Metric, Inch, InchStr, MetricStr) VALUES(?,?,?,?,?)"
1549
            for pipeSize in pipeSizes:
1550
                param = (pipeSize.code, pipeSize.metric, pipeSize.inch, pipeSize.inchStr, pipeSize.metricStr)
1551
                cursor.execute(sql, param)
1552
            conn.commit()
1553
            # Catch the exception
1554
        except Exception as ex:
1555
            # Roll back any change if something goes wrong
1556
            conn.rollback()
1557
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1558
        finally:
1559
            # Close the db connection
1560
            conn.close()
1561

    
1562

    
1563
    '''
1564
        @brief      delete NominalDiameter table
1565
        @author     kyouho
1566
        @date       2018.07.16
1567
    '''
1568
    def deleteNomialPipeSize(self):
1569
        try:
1570
            dbPath = os.path.join(self.getCurrentProject().getPath(), 'db', 'ITI_PID.db')
1571
            conn = sqlite3.connect(dbPath)
1572
            cursor = conn.cursor()
1573
            sql = "DELETE FROM NominalDiameter"
1574
            try:
1575
                cursor.execute(sql)
1576
                conn.commit()
1577
            except Exception as ex:
1578
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1579
        finally:
1580
            conn.close()
1581

    
1582
    '''
1583
        @brief      convert inch to metric
1584
        @author     kyouho
1585
        @date       2018.07.09
1586
    '''
1587
    def convertInchToMetric(self, inch):
1588
        result = ''
1589
        try:
1590
            # Creates or opens a file called mydb with a SQLite3 DB
1591
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1592
            conn = sqlite3.connect(dbPath)
1593
            # Get a cursor object
1594
            cursor = conn.cursor()
1595
            
1596
            sql = "select MetricStr from NominalDiameter WHERE InchStr = ?"
1597
            param = (inch,)
1598
            cursor.execute(sql, param)
1599
            rows = cursor.fetchall()
1600

    
1601
            if rows:
1602
                result = rows[0][0]
1603
            # Catch the exception
1604
        except Exception as ex:
1605
            # Roll back any change if something goes wrong
1606
            conn.rollback()
1607
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1608
        finally:
1609
            # Close the db connection
1610
            conn.close()
1611

    
1612
        return result
1613

    
1614
    '''
1615
        @brief      get Color MaxUID
1616
        @author     kyouho
1617
        @date       2018.07.03
1618
    '''
1619
    def getMaxColorUID(self):
1620
        result = 0
1621

    
1622
        try:
1623
            # Creates or opens a file called mydb with a SQLite3 DB
1624
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1625
            conn = sqlite3.connect(dbPath)
1626
            # Get a cursor object
1627
            cursor = conn.cursor()
1628

    
1629
            sql = "select MAX(UID) from Colors"
1630
            cursor.execute(sql)
1631
            rows = cursor.fetchall()
1632

    
1633
            result = rows[0][0]
1634
            # Catch the exception
1635
        except Exception as ex:
1636
            # Roll back any change if something goes wrong
1637
            conn.rollback()
1638
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1639
        finally:
1640
            # Close the db connection
1641
            conn.close()
1642

    
1643
        return result
1644

    
1645
    '''
1646
        @brief      insert Color property
1647
        @author     kyouho
1648
        @date       2018.07.09
1649
    '''
1650
    def setPropertyColor(self, _color):
1651
        try:
1652
            # Creates or opens a file called mydb with a SQLite3 DB
1653
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1654
            conn = sqlite3.connect(dbPath)
1655
            # Get a cursor object
1656
            cursor = conn.cursor()
1657
            sql = "INSERT INTO Colors(UID, RED, GREEN, BLUE, PROPERTY, VALUE) VALUES(?,?,?,?,?,?)"
1658
            param = (_color.index, _color.red, _color.green, _color.blue, _color._property, _color.value)
1659
            cursor.execute(sql, param)
1660
            conn.commit()
1661
            # Catch the exception
1662
        except Exception as ex:
1663
            # Roll back any change if something goes wrong
1664
            conn.rollback()
1665
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1666
        finally:
1667
            # Close the db connection
1668
            conn.close()
1669

    
1670
    '''
1671
        @brief      delete Color property
1672
        @author     kyouho
1673
        @date       2018.07.09
1674
    '''
1675
    def deletePropertyColor(self, property):
1676
        try:
1677
            # Creates or opens a file called mydb with a SQLite3 DB
1678
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1679
            conn = sqlite3.connect(dbPath)
1680
            # Get a cursor object
1681
            cursor = conn.cursor()
1682

    
1683
            sql = "DELETE FROM Colors WHERE PROPERTY = '{}'".format(property)
1684
            cursor.execute(sql)
1685
            conn.commit()
1686
            # Catch the exception
1687
        except Exception as ex:
1688
            # Roll back any change if something goes wrong
1689
            conn.rollback()
1690
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1691
        finally:
1692
            # Close the db connection
1693
            conn.close()
1694

    
1695
    '''
1696
        @brief      get Fluid Code
1697
        @author     kyouho
1698
        @date       2018.07.03
1699
        @history    kyouho 2018.07.04 kyouho 2018.07.04 forCheckLineNumber get only code
1700
    '''
1701
    def getFluidCodeData(self, forCheckLineNumber = False):
1702
        from FluidCodeData import FluidCodeData
1703
        result = []
1704

    
1705
        try:
1706
            # Creates or opens a file called mydb with a SQLite3 DB
1707
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1708
            conn = sqlite3.connect(dbPath)
1709
            # Get a cursor object
1710
            cursor = conn.cursor()
1711

    
1712
            sql = 'select uid, code, description from FluidCode order by length(code) DESC'
1713
            cursor.execute(sql)
1714
            rows = cursor.fetchall()
1715
            for row in rows:
1716
                data = FluidCodeData(row[0], row[1], row[2])
1717
                if forCheckLineNumber:
1718
                    result.append(data.code)
1719
                else:
1720
                    result.append(data)
1721
            # Catch the exception
1722
        except Exception as ex:
1723
            # Roll back any change if something goes wrong
1724
            conn.rollback()
1725
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1726
        finally:
1727
            # Close the db connection
1728
            conn.close()
1729

    
1730
        return result
1731

    
1732
    '''
1733
        @brief      get Symbol Attribute
1734
        @author     kyouho
1735
        @date       2018.07.18
1736
    '''
1737
    def checkAttribute(self, attr):
1738
        try:
1739
            # Creates or opens a file called mydb with a SQLite3 DB
1740
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1741
            conn = sqlite3.connect(dbPath)
1742
            # Get a cursor object
1743
            cursor = conn.cursor()
1744

    
1745
            sql = 'select UID from SymbolAttribute where UID = ?'
1746
            param = (attr,)
1747
            cursor.execute(sql, param)
1748
            rows = cursor.fetchall()
1749
            if len(rows):
1750
                return True
1751
            else:
1752
                return False
1753
            # Catch the exception
1754
        except Exception as ex:
1755
            # Roll back any change if something goes wrong
1756
            conn.rollback()
1757
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1758
        finally:
1759
            # Close the db connection
1760
            conn.close()
1761

    
1762
        return False
1763

    
1764
    '''
1765
        @brief      get Symbol Attribute
1766
        @author     kyouho
1767
        @date       2018.07.18
1768
        @history    humkyung 2018.10.13 load expression
1769
    '''
1770
    def getSymbolAttribute(self, _type):
1771
        from SymbolAttr import SymbolAttr
1772

    
1773
        result = []
1774

    
1775
        try:
1776
            # Creates or opens a file called mydb with a SQLite3 DB
1777
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1778
            conn = sqlite3.connect(dbPath)
1779
            # Get a cursor object
1780
            cursor = conn.cursor()
1781

    
1782
            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]'
1783
            param = (_type,)
1784
            cursor.execute(sql, param)
1785
            rows = cursor.fetchall()
1786
            for row in rows:
1787
                attr = SymbolAttr()
1788
                attr.UID = row[0]
1789
                attr.Attribute = row[1]
1790
                attr.DisplayAttribute = row[2]
1791
                attr.AttributeType = row[3]
1792
                attr.AttrAt = row[4]
1793
                attr.Expression = row[5]
1794
                result.append(attr)
1795
            # Catch the exception
1796
        except Exception as ex:
1797
            from App import App 
1798

    
1799
            # Roll back any change if something goes wrong
1800
            conn.rollback()
1801

    
1802
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1803
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1804
        finally:
1805
            # Close the db connection
1806
            conn.close()
1807

    
1808
        return result
1809

    
1810
    '''
1811
        @brief      get Symbol Attribute by UID
1812
        @author     kyouho
1813
        @date       2018.08.17
1814
        @history    humkyung 2018.10.13 load expression
1815
    '''
1816
    def getSymbolAttributeByUID(self, UID):
1817
        from SymbolAttr import SymbolAttr
1818

    
1819
        res = None
1820

    
1821
        try:
1822
            # Creates or opens a file called mydb with a SQLite3 DB
1823
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1824
            conn = sqlite3.connect(dbPath)
1825
            # Get a cursor object
1826
            cursor = conn.cursor()
1827

    
1828
            sql = 'select Attribute, DisplayAttribute, AttributeType, AttrAt, Expression from SymbolAttribute where uid = "{}"'.format(UID)
1829
            cursor.execute(sql)
1830
            rows = cursor.fetchall()
1831
            if len(rows):
1832
                res = SymbolAttr()
1833
                res.UID = UID
1834
                res.Attribute = rows[0][0]
1835
                res.DisplayAttribute = rows[0][1]
1836
                res.AttributeType = rows[0][2]
1837
                res.AttrAt = rows[0][3]
1838
                res.Expression = rows[0][4]
1839
            # Catch the exception
1840
        except Exception as ex:
1841
            from App import App
1842

    
1843
            # Roll back any change if something goes wrong
1844
            conn.rollback()
1845

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

    
1852
        return res
1853

    
1854
    '''
1855
        @brief      save symbol attributes
1856
        @author     humkyung
1857
        @date       2018.08.14
1858
        @history    humkyung 2018.10.13 save expression
1859
    '''
1860
    def saveSymbolAttributes(self, type, attrs):
1861
        try:
1862
            # Creates or opens a file called mydb with a SQLite3 DB
1863
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1864
            conn = sqlite3.connect(dbPath)
1865
            # Get a cursor object
1866
            cursor = conn.cursor()
1867

    
1868
            sql = 'delete from SymbolAttribute where SymbolType = ?'
1869
            param = (type,)
1870
            cursor.execute(sql, param)
1871

    
1872
            for attr in attrs:
1873
                sql = 'insert into SymbolAttribute(UID, SymbolType, Attribute, DisplayAttribute, AttributeType, AttrAt, Expression, [index]) values(?, ?, ?, ?, ?, ?, ?, ?)'
1874
                attr.insert(1, type)
1875
                param = tuple(attr)
1876
                cursor.execute(sql, param)
1877

    
1878
            conn.commit()
1879
            # Catch the exception
1880
        except Exception as ex:
1881
            # Roll back any change if something goes wrong
1882
            conn.rollback()
1883
            
1884
            from App import App 
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
    '''
1892
        @brief      save symbol attributes
1893
        @author     humkyung
1894
        @date       2018.08.14
1895
    '''
1896
    def saveLineAttributes(self, attrs):
1897
        try:
1898
            # Creates or opens a file called mydb with a SQLite3 DB
1899
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1900
            conn = sqlite3.connect(dbPath)
1901
            # Get a cursor object
1902
            cursor = conn.cursor()
1903

    
1904
            sql = 'delete from LineProperties'
1905
            cursor.execute(sql)
1906

    
1907
            for attr in attrs:
1908
                sql = 'insert into LineProperties(UID, Name, DisplayName, Type, LimitNumber, [index]) values(?, ?, ?, ?, ?, ?)'
1909
                param = tuple(attr)
1910
                cursor.execute(sql, param)
1911

    
1912
            conn.commit()
1913

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

    
1927
    '''
1928
        @brief      get symbol type id
1929
        @author     kyouho
1930
        @date       2018.08.17
1931
    '''
1932
    def getSymbolTypeId(self, symbolType):
1933
        result = []
1934

    
1935
        try:
1936
            # Creates or opens a file called mydb with a SQLite3 DB
1937
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1938
            conn = sqlite3.connect(dbPath)
1939
            # Get a cursor object
1940
            cursor = conn.cursor()
1941

    
1942
            sql = 'select id from SymbolType where type = ?'
1943
            param = (symbolType,)
1944
            cursor.execute(sql, param)
1945
            rows = cursor.fetchall()
1946
            
1947
            if len(rows):
1948
                result = rows[0][0]
1949
            else:
1950
                result = -1
1951
            # Catch the exception
1952
        except Exception as ex:
1953
            # Roll back any change if something goes wrong
1954
            conn.rollback()
1955
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1956
        finally:
1957
            # Close the db connection
1958
            conn.close()
1959

    
1960
        return result
1961

    
1962
    '''
1963
        @brief      get Code Table Data
1964
        @author     kyouho
1965
        @date       2018.07.10
1966
    '''
1967
    def getCodeTable(self, property, forCheckLineNumber = False):
1968
        result = []
1969
        try:
1970
            # Creates or opens a file called mydb with a SQLite3 DB
1971
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1972
            conn = sqlite3.connect(dbPath)
1973
            # Get a cursor object
1974
            cursor = conn.cursor()
1975

    
1976
            if property.upper().replace(' ','') == "NOMINALDIAMETER" and forCheckLineNumber:
1977
                sql = 'select InchStr, MetricStr from [{}] order by Metric ASC'.format(property)
1978
                cursor.execute(sql)
1979
                rows = cursor.fetchall()
1980
                for index in range(2):
1981
                    for row in rows:
1982
                        if row[index] != '' and result.count(row[index].replace("'", '"')) == 0:
1983
                            result.append(row[index].replace("'", '"'))
1984
            else:
1985
                sql = 'select uid, code, description, Allowables from [{}] order by length(code) DESC'.format(property)
1986
                cursor.execute(sql)
1987
                rows = cursor.fetchall()
1988
                for row in rows:
1989
                    if forCheckLineNumber:
1990
                        data = row[1]
1991
                    else:
1992
                        data = (row[0], row[1], row[2], row[3])
1993
                    result.append(data)
1994
            # Catch the exception
1995
        except Exception as ex:
1996
            # Roll back any change if something goes wrong
1997
            conn.rollback()
1998
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1999
        finally:
2000
            # Close the db connection
2001
            conn.close()
2002

    
2003
        return result
2004

    
2005
    '''
2006
        @brief      Set Common Code Data
2007
        @author     kyouho
2008
        @date       2018.07.12
2009
    '''
2010
    def saveCommonCodeData(self, tableName, datas):
2011
        try:
2012
            # Creates or opens a file called mydb with a SQLite3 DB
2013
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2014
            conn = sqlite3.connect(dbPath)
2015
            # Get a cursor object
2016
            cursor = conn.cursor()
2017

    
2018
            for data in datas:
2019
                uid = data[0]
2020
                if not uid:
2021
                    sql = "insert or replace into {}(UID, CODE, DESCRIPTION, ALLOWABLES) values(lower(hex(randomblob(16))), ?, ?, ?)".format(tableName)
2022
                    param = (data[1], data[2], data[3])
2023
                else:
2024
                    sql = "update {} SET CODE=?, DESCRIPTION=?, ALLOWABLES=? WHERE UID = ?".format(tableName)
2025
                    param = (data[1], data[2], data[3], data[0])
2026
                cursor.execute(sql, param)
2027

    
2028
            conn.commit()
2029
        
2030
        # Catch the exception
2031
        except Exception as ex:
2032
            # Roll back any change if something goes wrong
2033
            conn.rollback()
2034
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2035
        finally:
2036
            # Close the db connection
2037
            conn.close()
2038

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

    
2052
            for data in datas:
2053
                uid = data[0]
2054
                tableName = data[1]
2055

    
2056
                if uid:
2057
                    sql = "delete from {} where UID = ?".format(tableName)
2058
                    param = (uid,)
2059
                    cursor.execute(sql, param)
2060

    
2061
                cursor.execute(sql, param)
2062

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

    
2074
    '''
2075
        @brief      delete data list
2076
        @author     kyouho
2077
        @date       2018.08.16
2078
    '''
2079
    def deleteDataList(self, tableName, UID):
2080
        try:
2081
            # Creates or opens a file called mydb with a SQLite3 DB
2082
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2083
            conn = sqlite3.connect(dbPath)
2084
            # Get a cursor object
2085
            cursor = conn.cursor()
2086

    
2087
            sql = 'delete from {} where UID = {}'.format(tableName, UID)
2088
            
2089
            cursor.execute(sql)
2090

    
2091
            conn.commit()
2092

    
2093
        # Catch the exception
2094
        except Exception as ex:
2095
            # Roll back any change if something goes wrong
2096
            conn.rollback()
2097
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2098
        finally:
2099
            # Close the db connection
2100
            conn.close()
2101

    
2102
    '''
2103
        @brief      get line documentName list
2104
        @author     kyouho
2105
        @date       2018.08.13
2106
    '''
2107
    def getLineDocumentNameList(self):
2108
        result = []
2109

    
2110
        try:
2111
            # Creates or opens a file called mydb with a SQLite3 DB
2112
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2113
            conn = sqlite3.connect(dbPath)
2114
            # Get a cursor object
2115
            cursor = conn.cursor()
2116

    
2117
            sql = 'select DISTINCT(PNID_NO) from LINE_DATA_LIST'
2118

    
2119
            cursor.execute(sql)
2120
            rows = cursor.fetchall()
2121
            for row in rows:
2122
                result.append(row[0])
2123
        # Catch the exception
2124
        except Exception as ex:
2125
            # Roll back any change if something goes wrong
2126
            conn.rollback()
2127
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2128
        finally:
2129
            # Close the db connection
2130
            conn.close()
2131

    
2132
        return result
2133

    
2134
    '''
2135
        @brief      get line documentName list
2136
        @author     kyouho
2137
        @date       2018.08.14
2138
    '''
2139
    def getEquipDocumentNameList(self):
2140
        result = []
2141

    
2142
        try:
2143
            # Creates or opens a file called mydb with a SQLite3 DB
2144
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2145
            conn = sqlite3.connect(dbPath)
2146
            # Get a cursor object
2147
            cursor = conn.cursor()
2148

    
2149
            sql = 'select DISTINCT(PNID_NO) from EQUIPMENT_DATA_LIST'
2150

    
2151
            cursor.execute(sql)
2152
            rows = cursor.fetchall()
2153
            for row in rows:
2154
                result.append(row[0])
2155
        # Catch the exception
2156
        except Exception as ex:
2157
            # Roll back any change if something goes wrong
2158
            conn.rollback()
2159
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2160
        finally:
2161
            # Close the db connection
2162
            conn.close()
2163

    
2164
        return result
2165

    
2166

    
2167
    '''
2168
        @brief      get line data list
2169
        @author     kyouho
2170
        @date       2018.08.13
2171
    '''
2172
    def getLineDataList(self, docName = None):
2173
        result = []
2174

    
2175
        try:
2176
            # Creates or opens a file called mydb with a SQLite3 DB
2177
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2178
            conn = sqlite3.connect(dbPath)
2179
            # Get a cursor object
2180
            cursor = conn.cursor()
2181

    
2182
            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'
2183
            if docName is not None:
2184
                sql += " where PNID_NO = '{}'".format(docName)
2185

    
2186
            cursor.execute(sql)
2187
            #columnName = list(map(lambda x: x[0].upper(), cursor.description))
2188
            rows = cursor.fetchall()
2189
            for row in rows:
2190
                data = []
2191
                for index in range(len(cursor.description)):
2192
                    data.append(row[index])
2193
                result.append(data)
2194
        # Catch the exception
2195
        except Exception as ex:
2196
            # Roll back any change if something goes wrong
2197
            conn.rollback()
2198
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2199
        finally:
2200
            # Close the db connection
2201
            conn.close()
2202

    
2203
        return result
2204

    
2205
    '''
2206
        @brief      set line data list
2207
        @author     kyouho
2208
        @date       2018.08.13
2209
    '''
2210
    def setLineDataList(self, dataLists):
2211
        try:
2212
            # Creates or opens a file called mydb with a SQLite3 DB
2213
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2214
            conn = sqlite3.connect(dbPath)
2215
            # Get a cursor object
2216
            cursor = conn.cursor()
2217
            
2218
            for data in dataLists:
2219
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2220
                param = tuple(data)
2221
                cursor.execute(sql, param)
2222

    
2223
            conn.commit()
2224

    
2225
        # Catch the exception
2226
        except Exception as ex:
2227
            # Roll back any change if something goes wrong
2228
            conn.rollback()
2229
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2230
        finally:
2231
            # Close the db connection
2232
            conn.close()
2233

    
2234
    '''
2235
        @brief      delete line data list
2236
        @author     kyouho
2237
        @date       2018.08.13
2238
    '''
2239
    def deleteLineDataList(self, removeUID):
2240
        try:
2241
            # Creates or opens a file called mydb with a SQLite3 DB
2242
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2243
            conn = sqlite3.connect(dbPath)
2244
            # Get a cursor object
2245
            cursor = conn.cursor()
2246
            
2247
            for uid in removeUID:
2248
                sql = "delete from LINE_DATA_LIST where uid = '{}'".format(uid)
2249
                cursor.execute(sql)
2250

    
2251
            conn.commit()
2252

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

    
2262
    '''
2263
        @brief      delete line data list
2264
        @author     kyouho
2265
        @date       2018.08.13
2266
    '''
2267
    def deleteLineDataList_LineNo(self, removeUID):
2268
        try:
2269
            # Creates or opens a file called mydb with a SQLite3 DB
2270
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2271
            conn = sqlite3.connect(dbPath)
2272
            # Get a cursor object
2273
            cursor = conn.cursor()
2274
            
2275
            for uid in removeUID:
2276
                sql = "delete from LINE_DATA_LIST where LINE_NO = ?"
2277
                param = (uid,)
2278
                cursor.execute(sql, param)
2279

    
2280
            conn.commit()
2281

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

    
2291
    '''
2292
        @brief      delete equip data list
2293
        @author     kyouho
2294
        @date       2018.08.14
2295
    '''
2296
    def deleteEquipDataList(self, removeUID):
2297
        try:
2298
            # Creates or opens a file called mydb with a SQLite3 DB
2299
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2300
            conn = sqlite3.connect(dbPath)
2301
            # Get a cursor object
2302
            cursor = conn.cursor()
2303
            
2304
            for uid in removeUID:
2305
                sql = "delete from EQUIPMENT_DATA_LIST where uid = '{}'".format(uid)
2306
                cursor.execute(sql)
2307

    
2308
            conn.commit()
2309

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

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

    
2336
            conn.commit()
2337

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

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

    
2364
            conn.commit()
2365

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

    
2375
    '''
2376
        @brief      get equipment data list
2377
        @author     humkyung
2378
        @date       2018.05.03
2379
    '''
2380
    def getEquipmentDataList(self, docName = None):
2381
        result = []
2382
        try:
2383
            # Creates or opens a file called mydb with a SQLite3 DB
2384
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2385
            conn = sqlite3.connect(dbPath)
2386
            # Get a cursor object
2387
            cursor = conn.cursor()
2388

    
2389
            sql = 'select UID, ITEM_NO, SERVICE, NO_REQ, FLUID, DESC_OF_PART, OPERATION_CONDITION_TEMP, OPERATION_CONDITION_PRESS, DESIGN_CONDITION_TEMP, DESIGN_CONDITION_PRESS, MATERIAL, WEIGHT, POWER, INSULATION, PNID_NO, REV from EQUIPMENT_DATA_LIST'
2390
            if docName is not None:
2391
                sql += " where PNID_NO = '{}'".format(docName)
2392

    
2393
            cursor.execute(sql)
2394
            rows = cursor.fetchall()
2395
            for row in rows:
2396
                data = []
2397
                for index in range(len(cursor.description)): 
2398
                    data.append(row[index])
2399
                result.append(data)
2400
        # Catch the exception
2401
        except Exception as ex:
2402
            from App import App 
2403

    
2404
            # Roll back any change if something goes wrong
2405
            conn.rollback()
2406
            
2407
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2408
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2409
        finally:
2410
            # Close the db connection
2411
            conn.close()
2412

    
2413
        return result
2414

    
2415
    def get_valve_data_list(self, docName = None):
2416
        """
2417
        @brief      get valve data list
2418
        @author     humkyung
2419
        @date       2018.10.11
2420
        """
2421

    
2422
        result = []
2423
        try:
2424
            # Creates or opens a file called mydb with a SQLite3 DB
2425
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2426
            conn = sqlite3.connect(dbPath)
2427
            # Get a cursor object
2428
            cursor = conn.cursor()
2429

    
2430
            sql = 'select UID, ITEM_NO from VALVE_DATA_LIST'
2431
            if docName is not None:
2432
                sql += " where PNID_NO = '{}'".format(docName)
2433

    
2434
            cursor.execute(sql)
2435
            rows = cursor.fetchall()
2436
            for row in rows:
2437
                data = []
2438
                for index in range(len(cursor.description)): 
2439
                    data.append(row[index])
2440
                result.append(data)
2441
        # Catch the exception
2442
        except Exception as ex:
2443
            from App import App 
2444

    
2445
            # Roll back any change if something goes wrong
2446
            conn.rollback()
2447
            
2448
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2449
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2450
        finally:
2451
            # Close the db connection
2452
            conn.close()
2453

    
2454
        return result
2455

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

    
2470
            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'
2471
            if docName is not None:
2472
                sql += " where PNID_NO = '{}'".format(docName)
2473

    
2474
            cursor.execute(sql)
2475
            rows = cursor.fetchall()
2476
            for row in rows:
2477
                data = []
2478
                for index in range(len(cursor.description)): 
2479
                    data.append(row[index])
2480
                result.append(data)
2481
        # Catch the exception
2482
        except Exception as ex:
2483
            # Roll back any change if something goes wrong
2484
            conn.rollback()
2485
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2486
        finally:
2487
            # Close the db connection
2488
            conn.close()
2489

    
2490
        return result
2491

    
2492
    '''
2493
        @brief      get Note data list
2494
        @author     kyouho
2495
        @date       2018.10.10
2496
    '''
2497
    def getNoteDataList(self, docName = None):
2498
        result = []
2499
        try:
2500
            # Creates or opens a file called mydb with a SQLite3 DB
2501
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2502
            conn = sqlite3.connect(dbPath)
2503
            # Get a cursor object
2504
            cursor = conn.cursor()
2505

    
2506
            sql = 'select UID, NOTE_NO, DESCRIPTION, PNID_NO from NOTE_DATA_LIST'
2507
            if docName is not None:
2508
                sql += " where PNID_NO = '{}'".format(docName)
2509

    
2510
            cursor.execute(sql)
2511
            rows = cursor.fetchall()
2512
            for row in rows:
2513
                data = []
2514
                for index in range(len(cursor.description)): 
2515
                    data.append(row[index])
2516
                result.append(data)
2517
        # Catch the exception
2518
        except Exception as ex:
2519
            # Roll back any change if something goes wrong
2520
            conn.rollback()
2521
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2522
        finally:
2523
            # Close the db connection
2524
            conn.close()
2525

    
2526
        return result
2527

    
2528
    def saveToDatabase(self, items):
2529
        """
2530
        save given items to database
2531
        """
2532
        try:
2533
            # Creates or opens a file called mydb with a SQLite3 DB
2534
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2535
            conn = sqlite3.connect(dbPath)
2536
            # Get a cursor object
2537
            cursor = conn.cursor()
2538

    
2539
            for item in items:
2540
                sql = item.toSql()
2541
                if sql is not None and 2 == len(sql):
2542
                    cursor.execute(sql[0], sql[1])
2543

    
2544
            conn.commit()
2545
        # Catch the exception
2546
        except Exception as ex:
2547
            # Roll back any change if something goes wrong
2548
            conn.rollback()
2549
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2550
        finally:
2551
            # Close the db connection
2552
            conn.close()
2553

    
2554
    '''
2555
        @brief      set equipment data list
2556
        @author     humkyung
2557
        @date       2018.05.03
2558
    '''
2559
    def setEquipmentDataList(self, dataList):
2560
        try:
2561
            # Creates or opens a file called mydb with a SQLite3 DB
2562
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2563
            conn = sqlite3.connect(dbPath)
2564
            # Get a cursor object
2565
            cursor = conn.cursor()
2566

    
2567
            for data in dataList:
2568
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2569
                param = tuple(data)
2570
                cursor.execute(sql, param)
2571
            conn.commit()
2572
        # Catch the exception
2573
        except Exception as ex:
2574
            # Roll back any change if something goes wrong
2575
            conn.rollback()
2576
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2577
        finally:
2578
            # Close the db connection
2579
            conn.close()
2580

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

    
2594
            for data in dataList:
2595
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2596
                param = tuple(data)
2597
                cursor.execute(sql, param)
2598
            conn.commit()
2599

    
2600
        # Catch the exception
2601
        except Exception as ex:
2602
            # Roll back any change if something goes wrong
2603
            conn.rollback()
2604
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2605
        finally:
2606
            # Close the db connection
2607
            conn.close()
2608

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

    
2622
            for data in dataList:
2623
                sql = "insert or replace into NOTE_DATA_LIST(UID, NOTE_NO, DESCRIPTION, PNID_NO) values(?, ?, ?, ?)"
2624
                param = tuple(data)
2625
                cursor.execute(sql, param)
2626
            conn.commit()
2627

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

    
2637
    def getDrawings(self):
2638
        """
2639
        @brief      get drawings
2640
        @author     humkyung
2641
        @date       2018.11.03
2642
        """
2643

    
2644
        res = []
2645
        try:
2646
            # Creates or opens a file called mydb with a SQLite3 DB
2647
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2648
            conn = sqlite3.connect(dbPath)
2649
            # Get a cursor object
2650
            cursor = conn.cursor()
2651

    
2652
            sql = 'select UID,[NAME],[DATETIME] from Drawings'
2653
            cursor.execute(sql)
2654
            rows = cursor.fetchall()
2655
            for row in rows:
2656
                res.append([row[0], row[1], row[2]])
2657

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

    
2667
        return res
2668

    
2669
    def saveDrawings(self, drawings):
2670
        """
2671
        @brief      save drawings
2672
        @author     humkyung
2673
        @date       2018.11.03
2674
        """
2675

    
2676
        try:
2677
            # Creates or opens a file called mydb with a SQLite3 DB
2678
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2679
            conn = sqlite3.connect(dbPath)
2680
            # Get a cursor object
2681
            cursor = conn.cursor()
2682

    
2683
            for drawing in drawings:
2684
                if not drawing[0]:
2685
                    sql = 'insert or replace into Drawings(UID, [NAME], [DATETIME]) values(lower(hex(randomblob(16))), ?, ?)'
2686
                    param = tuple([drawing[1], ''])
2687
                else:
2688
                    sql = 'insert or replace into Drawings(UID, [NAME], [DATETIME]) values(?, ?, ?)'
2689
                    param = tuple(drawing)
2690

    
2691
                cursor.execute(sql, param)
2692
            conn.commit()
2693

    
2694
        # Catch the exception
2695
        except Exception as ex:
2696
            # Roll back any change if something goes wrong
2697
            conn.rollback()
2698
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2699
        finally:
2700
            # Close the db connection
2701
            conn.close()
2702

    
2703
    '''
2704
        @brief  get IsOriginDetect ComboBox Items
2705
    '''
2706
    def getIsOriginDetectComboBoxItems(self):
2707
        return [("원본 도면", 0), ("텍스트 제거 도면", 1)]
2708

    
2709
    '''
2710
        @brief  get IsOriginDetect ComboBox Items
2711
    '''
2712
    def getOcrOptionComboBoxItems(self):
2713
        return [("OCR 미적용", 0), ("일반 심볼", 1), ("Instrument 계통", 2)]
2714
    
2715
    '''
2716
        @brief      Return Symbol Type Items
2717
        @author     Jeongwoo
2718
        @date       18.04.20
2719
        @history    18.05.08    Jeongwoo type index changed
2720
    '''
2721
    def getSymbolTypeList(self):
2722
        symbolTypeList = []
2723

    
2724
        try:
2725
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2726

    
2727
            conn = sqlite3.connect(dbPath)
2728
            cursor = conn.cursor()
2729
            sql = 'SELECT * FROM SymbolType ORDER BY type ASC'
2730
            try:
2731
                cursor.execute(sql)
2732
                rows = cursor.fetchall()
2733
                for row in rows:
2734
                    symbolTypeList.append((row[0], row[1], row[2])) # UID, category, type
2735
            except Exception as ex:
2736
                from App import App
2737

    
2738
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2739
                App.mainWin().addMessage(MessageType.Error, message)
2740
        finally:
2741
            conn.close()
2742

    
2743
        return symbolTypeList
2744

    
2745
    '''
2746
        @brief      Get Symbol Category by Symbol Type
2747
        @author     Jeongwoo
2748
        @date       2018.05.09
2749
    '''
2750
    def getSymbolCategoryByType(self, type):
2751
        category = None
2752
        try:
2753
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
2754
            conn = sqlite3.connect(dbPath)
2755
            cursor = conn.cursor()
2756
            sql = 'SELECT category FROM SymbolType WHERE type = "' + type + '"'
2757
            cursor.execute(sql)
2758
            rows = cursor.fetchall()
2759
            if rows is not None and len(rows) > 0:
2760
                category = rows[0][0]
2761
        except Exception as ex:
2762
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2763
        finally:
2764
            conn.close()
2765

    
2766
        return category
2767

    
2768
    '''
2769
        @brief      Check Symbol Type is included in 'Equipment' Category
2770
        @author     Jeongwoo
2771
        @date       2018.05.09
2772
    '''
2773
    def isEquipmentType(self, type):
2774
        category = self.getSymbolCategoryByType(type)
2775
        return (category is not None and category == 'Equipment')
2776

    
2777
    '''
2778
        @brief      Return Symbol Type Items with "None"
2779
        @author     Jeongwoo
2780
        @date       18.04.06
2781
        @history    Seperate SymbolTypeList and "None"
2782
    '''
2783
    def getSymbolTypeComboBoxItems(self):
2784
        symbolTypeList = self.getSymbolTypeList()
2785
        symbolTypeList.insert(0, ('None', 'None', 'None'))
2786

    
2787
        return symbolTypeList
2788

    
2789
    '''
2790
        @brief  get Base Symbol ComboBox Items
2791
    '''
2792
    def getBaseSymbolComboBoxItems(self, type = None):
2793
        bsymbolNameList = self.getSymbolNameListByType(type)
2794
        bsymbolNameList.sort()
2795
        bsymbolNameList.insert(0, "None")
2796
        return bsymbolNameList
2797

    
2798
    '''
2799
        @brief  get Additional Symbol ComboBox Items
2800
    '''
2801
    def getAdditionalSymbolComboBoxItems(self):
2802
        asymbolNameList = self.getSymbolNameList()
2803
        asymbolNameList.sort()
2804
        asymbolNameList.insert(0, "None")
2805
        return asymbolNameList
2806

    
2807
    '''
2808
        @brief  get Additional Symbol's default direction ComboBox Items
2809
    '''
2810
    def getDefaultSymbolDirectionComboBoxItems(self):
2811
        return [("UP", 0), ("DOWN", 2), ("LEFT", 3), ("RIGHT", 1)]
2812
    
2813
    '''
2814
        @brief  getter of activeDrawing
2815
        @author humkyung
2816
        @date   2018.07.07
2817
    '''
2818
    @property
2819
    def activeDrawing(self):
2820
        return self._activeDrawing
2821

    
2822
    '''
2823
        @brief  setter of activeDrawing
2824
        @author humkyung
2825
        @date   2018.07.07
2826
    '''
2827
    @activeDrawing.setter
2828
    def activeDrawing(self, value):
2829
        self._activeDrawing = value
2830

    
2831
    '''
2832
        @brief      delete data list before save
2833
        @author     euisung
2834
        @date       2018.11.05
2835
    '''
2836
    def deleteDataListBeforeSave(self):
2837
        try:
2838
            # Creates or opens a file called mydb with a SQLite3 DB
2839
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2840
            conn = sqlite3.connect(dbPath)
2841
            # Get a cursor object
2842
            cursor = conn.cursor()
2843
            pidNo = self.activeDrawing.name
2844
            sql = "delete from LINE_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2845
            cursor.execute(sql)
2846
            sql = "delete from EQUIPMENT_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2847
            cursor.execute(sql)
2848
            sql = "delete from VALVE_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2849
            cursor.execute(sql)
2850
            sql = "delete from INSTRUMENT_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2851
            cursor.execute(sql)
2852
            sql = "delete from NOTE_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2853
            cursor.execute(sql)
2854
            sql = "delete from TitleBlockValues where Drawings_UID = '{}'".format(pidNo)
2855
            cursor.execute(sql)
2856

    
2857
            conn.commit()
2858

    
2859
        # Catch the exception
2860
        except Exception as ex:
2861
            # Roll back any change if something goes wrong
2862
            conn.rollback()
2863
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2864
        finally:
2865
            # Close the db connection
2866
            conn.close()
2867

    
2868
    def getColNames(self, table):
2869
        """
2870
        return column names of given table
2871
        """
2872
        res = None
2873
        try:
2874
            # Creates or opens a file called mydb with a SQLite3 DB
2875
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2876
            conn = sqlite3.connect(dbPath)
2877
            cursor = conn.execute('select * from {}'.format(table))
2878
            res = [col_name[0] for col_name in cursor.description]
2879
        # Catch the exception
2880
        except Exception as ex:
2881
            # Roll back any change if something goes wrong
2882
            conn.rollback()
2883
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2884
        finally:
2885
            # Close the db connection
2886
            conn.close()
2887

    
2888
        return res
2889

    
2890
    '''
2891
        @brief  getter of OCRData
2892
        @author humkyung
2893
        @date   2018.11.19
2894
    '''
2895
    @property
2896
    def OCRData(self):
2897
        if self._OCRData is None:
2898
            configs = self.getConfigs('Text Recognition', 'OCR Data')
2899
            self._OCRData = configs[0].value if 1 == len(configs) else 'eng'
2900

    
2901
        return self._OCRData
2902

    
2903
    '''
2904
        @brief  setter of OCRData
2905
        @author humkyung
2906
        @date   2018.11.19
2907
    '''
2908
    @OCRData.setter
2909
    def OCRData(self, value):
2910
        self._OCRData = value