프로젝트

일반

사용자정보

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

hytos / DTI_PID / DTI_PID / AppDocData.py @ c146ef30

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

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

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

    
23
from SingletonInstance import SingletonInstane
24
import symbol
25

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

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

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

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

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

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

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

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

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

    
118

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

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

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

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

    
174
        return drawingFileList
175

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

    
190
        return drawingFileList
191

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

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

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

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

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

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

    
244
        return self._colors
245

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
368
        self.currentPidSource = Source(image)
369

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

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

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

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

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

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

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

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

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

    
515
            conn = sqlite3.connect(dbPath)
516
            cursor = conn.cursor()
517
            sql = 'SELECT * FROM Symbol WHERE isExceptDetect = 0 order by width * height desc'
518
            try:
519
                cursor.execute(sql)
520
                rows = cursor.fetchall()
521
                for row in rows:
522
                    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
523
                    targetSymbolList.append(sym)
524
            except Exception as ex:
525
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
526
        finally:
527
            conn.close()
528

    
529
        return targetSymbolList
530

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

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

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

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

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

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

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

    
599
        return style
600

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

    
609
        try:
610
            self.buildAppDatabase()
611

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

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

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

    
634
        return styles
635

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

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

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

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

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

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

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

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

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

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

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

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

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

    
839
        return res
840

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

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

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

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

    
884
        return res
885

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

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

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

    
922
        return res
923

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

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

    
952
        return res
953

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

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

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

    
1013
        projectList = []
1014

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

    
1030
        return projectList
1031

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

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

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

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

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

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

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

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

    
1135
        return None
1136

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

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

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

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

    
1173
        return res
1174

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

    
1182
        res = []
1183

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

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

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

    
1211
        return res
1212

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1366
            conn.commit()
1367
        # Catch the exception
1368
        except Exception as ex:
1369
            # Roll back any change if something goes wrong
1370
            conn.rollback()
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
            # Close the db connection
1374
            self._areas = []
1375
            conn.close()
1376
            
1377
    '''
1378
        @brief  get symbol name list
1379
    '''
1380
    def getSymbolNameList(self):
1381
        symbolNametList = []
1382

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

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

    
1399
        return symbolNametList
1400

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

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

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

    
1428
        return symbolNametList
1429

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

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

    
1479
        return ret
1480

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

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

    
1510
        return ret
1511

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

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

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

    
1558
        return res
1559

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

    
1586

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

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

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

    
1636
        return result
1637

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

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

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

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

    
1667
        return result
1668

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

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

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

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

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

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

    
1754
        return result
1755

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

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

    
1786
        return False
1787

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

    
1797
        result = []
1798

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

    
1806
            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]'
1807
            param = (_type,)
1808
            cursor.execute(sql, param)
1809
            rows = cursor.fetchall()
1810
            for row in rows:
1811
                attr = SymbolAttr()
1812
                attr.UID = row[0]
1813
                attr.Attribute = row[1]
1814
                attr.DisplayAttribute = row[2]
1815
                attr.AttributeType = row[3]
1816
                attr.AttrAt = row[4]
1817
                attr.Expression = row[5]
1818
                result.append(attr)
1819
            # Catch the exception
1820
        except Exception as ex:
1821
            from App import App 
1822

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

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

    
1832
        return result
1833

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

    
1843
        res = None
1844

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

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

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

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

    
1876
        return res
1877

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

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

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

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

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

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

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

    
1936
            conn.commit()
1937

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

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

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

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

    
1984
        return result
1985

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

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

    
2027
        return result
2028

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

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

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

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

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

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

    
2085
                cursor.execute(sql, param)
2086

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

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

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

    
2115
            conn.commit()
2116

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

    
2126
    def getDocumentNameList(self):
2127
        '''
2128
            @brief      get documentName list
2129
            @author     euisung
2130
            @date       2018.12.11
2131
        '''
2132
        result = []
2133

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

    
2141
            sql = 'select DISTINCT(PNID_NO) from LINE_DATA_LIST'
2142
            cursor.execute(sql)
2143
            sql = 'select DISTINCT(PNID_NO) from EQUIPMENT_DATA_LIST'
2144
            cursor.execute(sql)
2145
            sql = 'select DISTINCT(PNID_NO) from INSTRUMENT_DATA_LIST'
2146
            cursor.execute(sql)
2147
            sql = 'select DISTINCT(PNID_NO) from NOTE_DATA_LIST'
2148
            cursor.execute(sql)
2149
            sql = 'select DISTINCT(PNID_NO) from VALVE_DATA_LIST'
2150
            cursor.execute(sql)
2151

    
2152
            rows = cursor.fetchall()
2153
            for row in rows:
2154
                result.append(row[0])
2155

    
2156
            result = list(set(result))
2157
            result.sort()
2158
        # Catch the exception
2159
        except Exception as ex:
2160
            # Roll back any change if something goes wrong
2161
            conn.rollback()
2162
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2163
        finally:
2164
            # Close the db connection
2165
            conn.close()
2166

    
2167
        return result
2168

    
2169

    
2170
    '''
2171
        @brief      get line documentName list
2172
        @author     kyouho
2173
        @date       2018.08.13
2174
    '''
2175
    def getLineDocumentNameList(self):
2176
        result = []
2177

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

    
2185
            sql = 'select DISTINCT(PNID_NO) from LINE_DATA_LIST'
2186

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

    
2200
        return result
2201

    
2202
    '''
2203
        @brief      get line documentName list
2204
        @author     kyouho
2205
        @date       2018.08.14
2206
    '''
2207
    def getEquipDocumentNameList(self):
2208
        result = []
2209

    
2210
        try:
2211
            # Creates or opens a file called mydb with a SQLite3 DB
2212
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2213
            conn = sqlite3.connect(dbPath)
2214
            # Get a cursor object
2215
            cursor = conn.cursor()
2216

    
2217
            sql = 'select DISTINCT(PNID_NO) from EQUIPMENT_DATA_LIST'
2218

    
2219
            cursor.execute(sql)
2220
            rows = cursor.fetchall()
2221
            for row in rows:
2222
                result.append(row[0])
2223
        # Catch the exception
2224
        except Exception as ex:
2225
            # Roll back any change if something goes wrong
2226
            conn.rollback()
2227
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2228
        finally:
2229
            # Close the db connection
2230
            conn.close()
2231

    
2232
        return result
2233

    
2234

    
2235
    '''
2236
        @brief      get line data list
2237
        @author     kyouho
2238
        @date       2018.08.13
2239
    '''
2240
    def getLineDataList(self, docName = None):
2241
        result = []
2242

    
2243
        try:
2244
            # Creates or opens a file called mydb with a SQLite3 DB
2245
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2246
            conn = sqlite3.connect(dbPath)
2247
            # Get a cursor object
2248
            cursor = conn.cursor()
2249

    
2250
            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'
2251
            if docName is not None:
2252
                sql += " where PNID_NO = '{}'".format(docName)
2253

    
2254
            cursor.execute(sql)
2255
            #columnName = list(map(lambda x: x[0].upper(), cursor.description))
2256
            rows = cursor.fetchall()
2257
            for row in rows:
2258
                data = []
2259
                for index in range(len(cursor.description)):
2260
                    data.append(row[index])
2261
                result.append(data)
2262
        # Catch the exception
2263
        except Exception as ex:
2264
            # Roll back any change if something goes wrong
2265
            conn.rollback()
2266
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2267
        finally:
2268
            # Close the db connection
2269
            conn.close()
2270

    
2271
        return result
2272

    
2273
    '''
2274
        @brief      set line data list
2275
        @author     kyouho
2276
        @date       2018.08.13
2277
    '''
2278
    def setLineDataList(self, dataLists):
2279
        try:
2280
            # Creates or opens a file called mydb with a SQLite3 DB
2281
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2282
            conn = sqlite3.connect(dbPath)
2283
            # Get a cursor object
2284
            cursor = conn.cursor()
2285
            
2286
            for data in dataLists:
2287
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2288
                param = tuple(data)
2289
                cursor.execute(sql, param)
2290

    
2291
            conn.commit()
2292

    
2293
        # Catch the exception
2294
        except Exception as ex:
2295
            # Roll back any change if something goes wrong
2296
            conn.rollback()
2297
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2298
        finally:
2299
            # Close the db connection
2300
            conn.close()
2301

    
2302
    '''
2303
        @brief      delete line data list
2304
        @author     kyouho
2305
        @date       2018.08.13
2306
    '''
2307
    def deleteLineDataList(self, removeUID):
2308
        try:
2309
            # Creates or opens a file called mydb with a SQLite3 DB
2310
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2311
            conn = sqlite3.connect(dbPath)
2312
            # Get a cursor object
2313
            cursor = conn.cursor()
2314
            
2315
            for uid in removeUID:
2316
                sql = "delete from LINE_DATA_LIST where uid = '{}'".format(uid)
2317
                cursor.execute(sql)
2318

    
2319
            conn.commit()
2320

    
2321
        # Catch the exception
2322
        except Exception as ex:
2323
            # Roll back any change if something goes wrong
2324
            conn.rollback()
2325
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2326
        finally:
2327
            # Close the db connection
2328
            conn.close()
2329

    
2330
    '''
2331
        @brief      delete line data list
2332
        @author     kyouho
2333
        @date       2018.08.13
2334
    '''
2335
    def deleteLineDataList_LineNo(self, removeUID):
2336
        try:
2337
            # Creates or opens a file called mydb with a SQLite3 DB
2338
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2339
            conn = sqlite3.connect(dbPath)
2340
            # Get a cursor object
2341
            cursor = conn.cursor()
2342
            
2343
            for uid in removeUID:
2344
                sql = "delete from LINE_DATA_LIST where LINE_NO = ?"
2345
                param = (uid,)
2346
                cursor.execute(sql, param)
2347

    
2348
            conn.commit()
2349

    
2350
        # Catch the exception
2351
        except Exception as ex:
2352
            # Roll back any change if something goes wrong
2353
            conn.rollback()
2354
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2355
        finally:
2356
            # Close the db connection
2357
            conn.close()
2358

    
2359
    '''
2360
        @brief      delete equip data list
2361
        @author     kyouho
2362
        @date       2018.08.14
2363
    '''
2364
    def deleteEquipDataList(self, removeUID):
2365
        try:
2366
            # Creates or opens a file called mydb with a SQLite3 DB
2367
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2368
            conn = sqlite3.connect(dbPath)
2369
            # Get a cursor object
2370
            cursor = conn.cursor()
2371
            
2372
            for uid in removeUID:
2373
                sql = "delete from EQUIPMENT_DATA_LIST where uid = '{}'".format(uid)
2374
                cursor.execute(sql)
2375

    
2376
            conn.commit()
2377

    
2378
        # Catch the exception
2379
        except Exception as ex:
2380
            # Roll back any change if something goes wrong
2381
            conn.rollback()
2382
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2383
        finally:
2384
            # Close the db connection
2385
            conn.close()
2386

    
2387
    '''
2388
        @brief      delete inst data list
2389
        @author     kyouho
2390
        @date       2018.08.14
2391
    '''
2392
    def deleteInstDataList(self, removeUID):
2393
        try:
2394
            # Creates or opens a file called mydb with a SQLite3 DB
2395
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2396
            conn = sqlite3.connect(dbPath)
2397
            # Get a cursor object
2398
            cursor = conn.cursor()
2399
            
2400
            for uid in removeUID:
2401
                sql = "delete from INSTRUMENT_DATA_LIST where uid = '{}'".format(uid)
2402
                cursor.execute(sql)
2403

    
2404
            conn.commit()
2405

    
2406
        # Catch the exception
2407
        except Exception as ex:
2408
            # Roll back any change if something goes wrong
2409
            conn.rollback()
2410
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2411
        finally:
2412
            # Close the db connection
2413
            conn.close()
2414

    
2415
    '''
2416
        @brief      delete note data list
2417
        @author     kyouho
2418
        @date       2018.10.10
2419
    '''
2420
    def deleteNoteDataList(self, removeUID):
2421
        try:
2422
            # Creates or opens a file called mydb with a SQLite3 DB
2423
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2424
            conn = sqlite3.connect(dbPath)
2425
            # Get a cursor object
2426
            cursor = conn.cursor()
2427
            
2428
            for uid in removeUID:
2429
                sql = "delete from NOTE_DATA_LIST where uid = '{}'".format(uid)
2430
                cursor.execute(sql)
2431

    
2432
            conn.commit()
2433

    
2434
        # Catch the exception
2435
        except Exception as ex:
2436
            # Roll back any change if something goes wrong
2437
            conn.rollback()
2438
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2439
        finally:
2440
            # Close the db connection
2441
            conn.close()
2442

    
2443
    '''
2444
        @brief      get equipment data list
2445
        @author     humkyung
2446
        @date       2018.05.03
2447
    '''
2448
    def getEquipmentDataList(self, docName = None):
2449
        result = []
2450
        try:
2451
            # Creates or opens a file called mydb with a SQLite3 DB
2452
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2453
            conn = sqlite3.connect(dbPath)
2454
            # Get a cursor object
2455
            cursor = conn.cursor()
2456

    
2457
            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'
2458
            if docName is not None:
2459
                sql += " where PNID_NO = '{}'".format(docName)
2460

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

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

    
2481
        return result
2482

    
2483
    def get_valve_data_list(self, docName = None):
2484
        """
2485
        @brief      get valve data list
2486
        @author     humkyung
2487
        @date       2018.10.11
2488
        """
2489

    
2490
        result = []
2491
        try:
2492
            # Creates or opens a file called mydb with a SQLite3 DB
2493
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2494
            conn = sqlite3.connect(dbPath)
2495
            # Get a cursor object
2496
            cursor = conn.cursor()
2497

    
2498
            sql = 'select UID, ITEM_NO, PNID_NO from VALVE_DATA_LIST'
2499
            if docName is not None:
2500
                sql += " where PNID_NO = '{}'".format(docName)
2501

    
2502
            cursor.execute(sql)
2503
            rows = cursor.fetchall()
2504
            for row in rows:
2505
                data = []
2506
                for index in range(len(cursor.description)): 
2507
                    data.append(row[index])
2508
                result.append(data)
2509
        # Catch the exception
2510
        except Exception as ex:
2511
            from App import App 
2512

    
2513
            # Roll back any change if something goes wrong
2514
            conn.rollback()
2515
            
2516
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2517
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2518
        finally:
2519
            # Close the db connection
2520
            conn.close()
2521

    
2522
        return result
2523

    
2524
    '''
2525
        @brief      get instrument data list
2526
        @author     kyouho
2527
        @date       2018.08.14
2528
    '''
2529
    def getInstrumentDataList(self, docName = None):
2530
        result = []
2531
        try:
2532
            # Creates or opens a file called mydb with a SQLite3 DB
2533
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2534
            conn = sqlite3.connect(dbPath)
2535
            # Get a cursor object
2536
            cursor = conn.cursor()
2537

    
2538
            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'
2539
            if docName is not None:
2540
                sql += " where PNID_NO = '{}'".format(docName)
2541

    
2542
            cursor.execute(sql)
2543
            rows = cursor.fetchall()
2544
            for row in rows:
2545
                data = []
2546
                for index in range(len(cursor.description)): 
2547
                    data.append(row[index])
2548
                result.append(data)
2549
        # Catch the exception
2550
        except Exception as ex:
2551
            # Roll back any change if something goes wrong
2552
            conn.rollback()
2553
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2554
        finally:
2555
            # Close the db connection
2556
            conn.close()
2557

    
2558
        return result
2559

    
2560
    '''
2561
        @brief      get Note data list
2562
        @author     kyouho
2563
        @date       2018.10.10
2564
    '''
2565
    def getNoteDataList(self, docName = None):
2566
        result = []
2567
        try:
2568
            # Creates or opens a file called mydb with a SQLite3 DB
2569
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2570
            conn = sqlite3.connect(dbPath)
2571
            # Get a cursor object
2572
            cursor = conn.cursor()
2573

    
2574
            sql = 'select UID, NOTE_NO, DESCRIPTION, PNID_NO from NOTE_DATA_LIST'
2575
            if docName is not None:
2576
                sql += " where PNID_NO = '{}'".format(docName)
2577

    
2578
            sql += ' ORDER BY NOTE_NO ASC'
2579
            cursor.execute(sql)
2580
            rows = cursor.fetchall()
2581
            for row in rows:
2582
                data = []
2583
                for index in range(len(cursor.description)): 
2584
                    data.append(row[index])
2585
                result.append(data)
2586
        # Catch the exception
2587
        except Exception as ex:
2588
            # Roll back any change if something goes wrong
2589
            conn.rollback()
2590
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2591
        finally:
2592
            # Close the db connection
2593
            conn.close()
2594

    
2595
        return result
2596

    
2597
    def saveToDatabase(self, items):
2598
        """
2599
        save given items to database
2600
        """
2601
        try:
2602
            # Creates or opens a file called mydb with a SQLite3 DB
2603
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2604
            conn = sqlite3.connect(dbPath)
2605
            # Get a cursor object
2606
            cursor = conn.cursor()
2607

    
2608
            for item in items:
2609
                sql = item.toSql()
2610
                if type(sql) is list:
2611
                    for item in sql:
2612
                        if item is not None and 2 == len(item):
2613
                            cursor.execute(item[0], item[1])
2614
                else:
2615
                    if sql is not None and 2 == len(sql):
2616
                        cursor.execute(sql[0], sql[1])
2617

    
2618
            conn.commit()
2619
        # Catch the exception
2620
        except Exception as ex:
2621
            from App import App
2622
            # Roll back any change if something goes wrong
2623
            conn.rollback()
2624

    
2625
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2626
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2627
        finally:
2628
            # Close the db connection
2629
            conn.close()
2630

    
2631
    '''
2632
        @brief      set equipment data list
2633
        @author     humkyung
2634
        @date       2018.05.03
2635
    '''
2636
    def setEquipmentDataList(self, dataList):
2637
        try:
2638
            # Creates or opens a file called mydb with a SQLite3 DB
2639
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2640
            conn = sqlite3.connect(dbPath)
2641
            # Get a cursor object
2642
            cursor = conn.cursor()
2643

    
2644
            for data in dataList:
2645
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2646
                param = tuple(data)
2647
                cursor.execute(sql, param)
2648
            conn.commit()
2649
        # Catch the exception
2650
        except Exception as ex:
2651
            # Roll back any change if something goes wrong
2652
            conn.rollback()
2653
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2654
        finally:
2655
            # Close the db connection
2656
            conn.close()
2657

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

    
2671
            for data in dataList:
2672
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2673
                param = tuple(data)
2674
                cursor.execute(sql, param)
2675
            conn.commit()
2676

    
2677
        # Catch the exception
2678
        except Exception as ex:
2679
            # Roll back any change if something goes wrong
2680
            conn.rollback()
2681
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2682
        finally:
2683
            # Close the db connection
2684
            conn.close()
2685

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

    
2699
            for data in dataList:
2700
                sql = "insert or replace into NOTE_DATA_LIST(UID, NOTE_NO, DESCRIPTION, PNID_NO) values(?, ?, ?, ?)"
2701
                param = tuple(data)
2702
                cursor.execute(sql, param)
2703
            conn.commit()
2704

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

    
2714
    def getDrawings(self):
2715
        """
2716
        @brief      get drawings
2717
        @author     humkyung
2718
        @date       2018.11.03
2719
        """
2720

    
2721
        res = []
2722
        try:
2723
            # Creates or opens a file called mydb with a SQLite3 DB
2724
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2725
            conn = sqlite3.connect(dbPath)
2726
            # Get a cursor object
2727
            cursor = conn.cursor()
2728

    
2729
            sql = 'select UID,[NAME],[DATETIME] from Drawings'
2730
            cursor.execute(sql)
2731
            rows = cursor.fetchall()
2732
            for row in rows:
2733
                res.append([row[0], row[1], row[2]])
2734

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

    
2744
        return res
2745

    
2746
    def saveDrawings(self, drawings):
2747
        """
2748
        @brief      save drawings
2749
        @author     humkyung
2750
        @date       2018.11.03
2751
        """
2752

    
2753
        try:
2754
            # Creates or opens a file called mydb with a SQLite3 DB
2755
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2756
            conn = sqlite3.connect(dbPath)
2757
            # Get a cursor object
2758
            cursor = conn.cursor()
2759

    
2760
            for drawing in drawings:
2761
                if not drawing[0]:
2762
                    sql = 'insert or replace into Drawings(UID, [NAME], [DATETIME]) values(lower(hex(randomblob(16))), ?, ?)'
2763
                    param = tuple([drawing[1], ''])
2764
                else:
2765
                    sql = 'insert or replace into Drawings(UID, [NAME], [DATETIME]) values(?, ?, ?)'
2766
                    param = tuple(drawing)
2767

    
2768
                cursor.execute(sql, param)
2769
            conn.commit()
2770

    
2771
        # Catch the exception
2772
        except Exception as ex:
2773
            # Roll back any change if something goes wrong
2774
            conn.rollback()
2775
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2776
        finally:
2777
            # Close the db connection
2778
            conn.close()
2779

    
2780
    '''
2781
        @brief  get IsOriginDetect ComboBox Items
2782
    '''
2783
    def getIsOriginDetectComboBoxItems(self):
2784
        return [("원본 도면", 0), ("텍스트 제거 도면", 1)]
2785

    
2786
    '''
2787
        @brief  get IsOriginDetect ComboBox Items
2788
    '''
2789
    def getOcrOptionComboBoxItems(self):
2790
        return [("OCR 미적용", 0), ("일반 심볼", 1), ("Instrument 계통", 2)]
2791
    
2792
    '''
2793
        @brief      Return Symbol Type Items
2794
        @author     Jeongwoo
2795
        @date       18.04.20
2796
        @history    18.05.08    Jeongwoo type index changed
2797
    '''
2798
    def getSymbolTypeList(self):
2799
        symbolTypeList = []
2800

    
2801
        try:
2802
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2803

    
2804
            conn = sqlite3.connect(dbPath)
2805
            cursor = conn.cursor()
2806
            sql = 'SELECT * FROM SymbolType ORDER BY type ASC'
2807
            try:
2808
                cursor.execute(sql)
2809
                rows = cursor.fetchall()
2810
                for row in rows:
2811
                    symbolTypeList.append((row[0], row[1], row[2])) # UID, category, type
2812
            except Exception as ex:
2813
                from App import App
2814

    
2815
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2816
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2817
        finally:
2818
            conn.close()
2819

    
2820
        return symbolTypeList
2821

    
2822
    '''
2823
        @brief      Get Symbol Category by Symbol Type
2824
        @author     Jeongwoo
2825
        @date       2018.05.09
2826
    '''
2827
    def getSymbolCategoryByType(self, type):
2828
        category = None
2829
        try:
2830
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
2831
            conn = sqlite3.connect(dbPath)
2832
            cursor = conn.cursor()
2833
            sql = 'SELECT category FROM SymbolType WHERE type = "' + type + '"'
2834
            cursor.execute(sql)
2835
            rows = cursor.fetchall()
2836
            if rows is not None and len(rows) > 0:
2837
                category = rows[0][0]
2838
        except Exception as ex:
2839
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2840
        finally:
2841
            conn.close()
2842

    
2843
        return category
2844

    
2845
    '''
2846
        @brief      Check Symbol Type is included in 'Equipment' Category
2847
        @author     Jeongwoo
2848
        @date       2018.05.09
2849
    '''
2850
    def isEquipmentType(self, type):
2851
        category = self.getSymbolCategoryByType(type)
2852
        return (category is not None and category == 'Equipment')
2853

    
2854
    '''
2855
        @brief      Return Symbol Type Items with "None"
2856
        @author     Jeongwoo
2857
        @date       18.04.06
2858
        @history    Seperate SymbolTypeList and "None"
2859
    '''
2860
    def getSymbolTypeComboBoxItems(self):
2861
        symbolTypeList = self.getSymbolTypeList()
2862
        symbolTypeList.insert(0, ('None', 'None', 'None'))
2863

    
2864
        return symbolTypeList
2865

    
2866
    '''
2867
        @brief  get Base Symbol ComboBox Items
2868
    '''
2869
    def getBaseSymbolComboBoxItems(self, type = None):
2870
        bsymbolNameList = self.getSymbolNameListByType(type)
2871
        bsymbolNameList.sort()
2872
        bsymbolNameList.insert(0, "None")
2873
        return bsymbolNameList
2874

    
2875
    '''
2876
        @brief  get Additional Symbol ComboBox Items
2877
    '''
2878
    def getAdditionalSymbolComboBoxItems(self):
2879
        asymbolNameList = self.getSymbolNameList()
2880
        asymbolNameList.sort()
2881
        asymbolNameList.insert(0, "None")
2882
        return asymbolNameList
2883

    
2884
    '''
2885
        @brief  get Additional Symbol's default direction ComboBox Items
2886
    '''
2887
    def getDefaultSymbolDirectionComboBoxItems(self):
2888
        return [("UP", 0), ("DOWN", 2), ("LEFT", 3), ("RIGHT", 1)]
2889
    
2890
    '''
2891
        @brief  getter of activeDrawing
2892
        @author humkyung
2893
        @date   2018.07.07
2894
    '''
2895
    @property
2896
    def activeDrawing(self):
2897
        return self._activeDrawing
2898

    
2899
    '''
2900
        @brief  setter of activeDrawing
2901
        @author humkyung
2902
        @date   2018.07.07
2903
    '''
2904
    @activeDrawing.setter
2905
    def activeDrawing(self, value):
2906
        self._activeDrawing = value
2907

    
2908
    '''
2909
        @brief      delete data list before save
2910
        @author     euisung
2911
        @date       2018.11.05
2912
    '''
2913
    def deleteDataListBeforeSave(self):
2914
        try:
2915
            # Creates or opens a file called mydb with a SQLite3 DB
2916
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2917
            conn = sqlite3.connect(dbPath)
2918
            # Get a cursor object
2919
            cursor = conn.cursor()
2920
            pidNo = self.activeDrawing.name
2921
            sql = "delete from LINE_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2922
            cursor.execute(sql)
2923
            sql = "delete from EQUIPMENT_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2924
            cursor.execute(sql)
2925
            sql = "delete from VALVE_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2926
            cursor.execute(sql)
2927
            sql = "delete from INSTRUMENT_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2928
            cursor.execute(sql)
2929
            sql = "delete from NOTE_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2930
            cursor.execute(sql)
2931
            sql = "delete from TitleBlockValues where Drawings_UID = '{}'".format(pidNo)
2932
            cursor.execute(sql)
2933

    
2934
            conn.commit()
2935

    
2936
        # Catch the exception
2937
        except Exception as ex:
2938
            # Roll back any change if something goes wrong
2939
            conn.rollback()
2940
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2941
        finally:
2942
            # Close the db connection
2943
            conn.close()
2944

    
2945
    def getColNames(self, table):
2946
        """
2947
        return column names of given table
2948
        """
2949
        res = None
2950
        try:
2951
            # Creates or opens a file called mydb with a SQLite3 DB
2952
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2953
            conn = sqlite3.connect(dbPath)
2954
            cursor = conn.execute('select * from {}'.format(table))
2955
            res = [col_name[0] for col_name in cursor.description]
2956
        # Catch the exception
2957
        except Exception as ex:
2958
            # Roll back any change if something goes wrong
2959
            conn.rollback()
2960
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2961
        finally:
2962
            # Close the db connection
2963
            conn.close()
2964

    
2965
        return res
2966

    
2967
    '''
2968
        @brief  getter of OCRData
2969
        @author humkyung
2970
        @date   2018.11.19
2971
    '''
2972
    @property
2973
    def OCRData(self):
2974
        if self._OCRData is None:
2975
            configs = self.getConfigs('Text Recognition', 'OCR Data')
2976
            self._OCRData = configs[0].value if 1 == len(configs) else 'eng'
2977

    
2978
        return self._OCRData
2979

    
2980
    '''
2981
        @brief  setter of OCRData
2982
        @author humkyung
2983
        @date   2018.11.19
2984
    '''
2985
    @OCRData.setter
2986
    def OCRData(self, value):
2987
        self._OCRData = value
클립보드 이미지 추가 (최대 크기: 500 MB)