프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / DTI_PID / AppDocData.py @ c5e51d41

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

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

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

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

    
22
from SingletonInstance import SingletonInstane
23
import symbol
24
from NominalPipeSize import NominalPipeSize
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
    '''
57
        @brief  return size value string
58
        @author humkyung
59
        @date   2018.04.24
60
    '''
61
    def sizeValue(self):
62
        return self.inchStr if 'Inch' == self.sizeUnit else self.metricStr
63

    
64
'''
65
    @brief  Pipe color class
66
'''
67
class Color:
68
    def __init__(self, index, red, green, blue):
69
        self.index = index
70
        self.red = red
71
        self.green = green
72
        self.blue = blue
73

    
74
'''
75
    @brief      MessageType
76
    @author     humkyung 
77
    @date       2018.07.31
78
'''
79
class MessageType(Enum):
80
    Normal = 1
81
    Error = 2
82

    
83
class AppDocData(SingletonInstane):
84
    DATABASE = 'ITI_PID.db'
85
    def __init__(self):
86
        from DisplayColors import DisplayColors
87

    
88
        self._imgFilePath = None
89
        self.imgName = None
90
        self.imgWidth = 0
91
        self.imgHeight = 0
92
        self._OCRData = None
93
        self._imgSrc = None
94

    
95
        self._areas = []
96
        self.equipments = []
97
        self.lineNos = []
98
        self.lines = []
99
        self.texts = []
100
        self.symbols = []
101
        self.unknowns = []
102
        self.allItems = []
103
        self.tracerLineNos = []
104
        self.lineIndicators = []
105
        self._colors = None
106
        self._lineNoProperties = None
107
        self._lineTypes = None
108
        self._lineTypeConfigs = None
109
        self._activeDrawing = None
110
        self._hmbTable = None
111
        self._titleBlockProperties = None
112
        self.needReOpening = None
113

    
114
        self.configTable = None
115

    
116
    def clearItemList(self, trim):
117
        '''
118
            @brief      clear item list
119
            @author     euisung
120
            @date       2018.11.28
121
        '''
122
        self.equipments.clear()
123
        self.symbols.clear()
124
        self.lineNos.clear()
125
        self.texts.clear()
126
        self.lines.clear()
127
        self.unknowns.clear()
128
        self.allItems.clear()
129
        self.lineIndicators.clear()
130
        if trim:
131
            self.tracerLineNos.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.allItems.clear()
153
        self.tracerLineNos.clear()
154
        self.lineIndicators.clear()
155
        self._colors = None
156
        self._lineNoProperties = None
157
        self._lineTypeConfigs = None
158
        self._activeDrawing = None
159
        self._hmbTable = None
160
        self._titleBlockProperties = None
161

    
162
    '''
163
        @brief      Get drawing file list
164
        @author     euisung
165
        @date       2018.09.28
166
    '''
167
    def getDrawingFileList(self):
168
        """
169
        get drawing files which's extension is .png or jpg from drawing folder
170
        """
171
        try:
172
            project = AppDocData.instance().getCurrentProject()
173
            path = project.getDrawingFilePath()
174
            drawingFileList = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f)) and (os.path.splitext(f)[1] == '.png' or os.path.splitext(f)[1] == '.jpg' or os.path.splitext(f)[1] == '.jpeg' or os.path.splitext(f)[1] == '.JPEG' or os.path.splitext(f)[1] == '.PNG')]
175
            drawingFileList.sort()
176
        except Exception as ex:
177
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
178

    
179
        return drawingFileList
180

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

    
197
        return drawingFileList
198

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

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

    
217
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
218
        app_database = os.path.join(path, 'App.db')
219
        return app_database 
220

    
221
    '''
222
        @brief  getter of colors 
223
        @author humkyung
224
        @date   2018.06.18
225
    '''
226
    @property
227
    def colors(self):
228
        import random
229

    
230
        if self._colors is None or self._colors == []:
231
            self._colors = []
232
            try:
233
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath() , AppDocData.DATABASE)
234

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

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

    
253
        return self._colors.pop(random.randrange(0, len(self._colors)))
254

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

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

    
273
    @staticmethod
274
    def my_imread(filePath):
275
        """ read a file which's name contains unicode string : ref http://devdoftech.co.kr:82/redmine/issues/631 """
276
        import numpy as np
277
        import cv2
278

    
279
        stream = open(filePath.encode('utf-8') , 'rb')
280
        _bytes = bytearray(stream.read())
281
        numpyArray = np.asarray(_bytes, dtype=np.uint8)
282
        return cv2.imdecode(numpyArray, cv2.IMREAD_UNCHANGED)
283

    
284
    '''
285
        @brief      getter of imgSrc
286
        @author     humkyung
287
        @date       2018.07.30
288
    '''
289
    @property
290
    def imgSrc(self):
291
        import cv2
292
        import numpy as np
293

    
294
        if self._imgSrc is None and self._imgFilePath is not None and os.path.isfile(self._imgFilePath):
295
            self._imgSrc = cv2.cvtColor(AppDocData.my_imread(self._imgFilePath), cv2.COLOR_BGR2GRAY)
296
            kernel = np.array([[-1,-1,-1], 
297
                   [-1, 9,-1],
298
                   [-1,-1,-1]])
299
            self._imgSrc = cv2.filter2D(self._imgSrc, -1, kernel)
300
            #blur = cv2.GaussianBlur(self._imgSrc , (5,5), 0)
301
            #smooth = cv2.addWeighted(blur, 1.5, self._imgSrc, -0.5, 0)
302
            #self._imgSrc = cv2.threshold(smooth, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
303
            self._imgSrc = cv2.threshold(self._imgSrc, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
304
            
305
            configs = AppDocData.instance().getConfigs('Filter', 'DilateSize')
306
            if 1 == len(configs) and int(configs[0].value) is not 0:
307
                size = int(configs[0].value)
308
                kernel = np.ones((size, size), np.uint8)
309
                self._imgSrc = cv2.erode(self._imgSrc, kernel, iterations=1)
310
            
311
        return self._imgSrc
312

    
313
    '''
314
        @brief      setter of imgSrc
315
        @author     humkyung
316
        @date       2018.07.30
317
    '''
318
    @imgSrc.setter
319
    def imgSrc(self, value):
320
        self._imgSrc = value
321

    
322
    '''
323
        @brief      reset imgSrc
324
        @author     humkyung
325
        @date       2018.07.30
326
    '''
327
    def resetImgSrc(self):
328
        self._imgSrc = None
329

    
330
    '''
331
        @brief  getter of line type configs
332
        @author humkyung
333
        @date   2018.06.28
334
    '''
335
    @property
336
    def lineTypeConfigs(self):
337
        from PyQt5.QtCore import Qt
338

    
339
        if self._lineTypeConfigs is None:
340
            self._lineTypeConfigs = []
341

    
342
            styleMap = [('SolidLine', Qt.SolidLine), ('DashLine', Qt.DashLine), ('DotLine', Qt.DotLine), ('DashDotLine', Qt.DashDotLine), 
343
                ('DashDotDotLine', Qt.DashDotDotLine), ('CustomDashLine', Qt.CustomDashLine)]
344

    
345
            configs = self.getConfigs('LineTypes')
346
            for config in configs:
347
                color, width, _style, transparent = config.value.split(',')
348
                matches = [param for param in styleMap if param[0] == _style]
349
                style = matches[0][1] if matches else Qt.SolidLine
350
                self._lineTypeConfigs.append((config.key, color, int(width), style, float(transparent)))
351
        
352
        return self._lineTypeConfigs
353

    
354
    '''
355
        @brief  setter of line type configs
356
        @author humkyung
357
        @date   2018.06.28
358
    '''
359
    @lineTypeConfigs.setter
360
    def lineTypeConfigs(self, value):
361
        self._lineTypeConfigs = value
362

    
363
    @property
364
    def drain_size(self):
365
        """ getter of drain_size """
366
        if not hasattr(self, '_drain_size') or not self._drain_size:
367
            configs = self.getConfigs('Drain Size Rule', 'Size')
368
            self._drain_size = configs[0].value if configs else '1"'
369

    
370
        return self._drain_size
371

    
372
    @drain_size.setter
373
    def drain_size(self, value):
374
        """ setter of drain_size """
375
        self._drain_size = value
376

    
377
    '''
378
        @brief      getter of hmb table
379
        @author     humkyung
380
        @date       2018.07.16
381
    '''
382
    @property
383
    def hmbTable(self):
384
        from HMBTable import HMBTable
385

    
386
        if self._hmbTable is None:
387
            self._hmbTable = HMBTable()
388
            self._hmbTable.loadData()
389
        
390
        return self._hmbTable
391

    
392
    '''
393
        @brief      setter of hmb table
394
        @author     humkyung
395
        @date       2018.07.16
396
    '''
397
    @hmbTable.setter
398
    def hmbTable(self, value):
399
        self._hmbTable = value
400

    
401
    '''
402
        @brief  get line type config of given line type
403
        @author humkyung
404
        @date   2018.06.28
405
    '''
406
    def getLineTypeConfig(self, lineType):
407
        from PyQt5.QtCore import Qt
408

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

    
412
    def setCurrentPidSource(self, image):
413
        self.imgWidth, self.imgHeight = image.size
414

    
415
        self.currentPidSource = Source(image)
416

    
417
    def getCurrentPidSource(self):
418
        return self.currentPidSource
419

    
420
    '''
421
        @brief      Check if data exists or not
422
        @author     Jeongwoo
423
        @date       2018.05.03
424
    '''
425
    def isExistData(self, fieldName, data):
426
        rows = None
427
        try:
428
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
429

    
430
            conn = sqlite3.connect(dbPath)
431
            cursor = conn.cursor()
432
            sql = ""
433
            if isinstance(data, str):
434
                sql = "SELECT * FROM Symbol WHERE " + fieldName + " = '"+ data +"'"
435
            else:
436
                sql = "SELECT * FROM Symbol WHERE " + fieldName + " = "+ str(data) +""
437
            cursor.execute(sql)
438
            rows = cursor.fetchall()
439
        # Catch the exception
440
        except Exception as ex:
441
            # Roll back any change if something goes wrong
442
            conn.rollback()
443
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
444
        finally:
445
            conn.close()
446
            if rows is not None and len(rows) > 0:
447
                return True
448
            else:
449
                return False
450

    
451
    '''
452
        @brief      Check if exist file name or not
453
        @author     Jeongwoo
454
        @date       2018.05.03
455
    '''
456
    def isExistFileName(self, name):
457
        rows = None
458
        try:
459
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
460
            conn = sqlite3.connect(dbPath)
461
            cursor = conn.cursor()
462
            sql = "SELECT * FROM Symbol WHERE name = '"+ name +"'"
463
            cursor.execute(sql)
464
            rows = cursor.fetchall()
465
        # Catch the exception
466
        except Exception as ex:
467
            # Roll back any change if something goes wrong
468
            conn.rollback()
469
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
470
        finally:
471
            conn.close()
472
            if rows is not None and len(rows) > 0:
473
                return True
474
            else:
475
                return False
476

    
477
    '''
478
        @brief      Insert new symbol into Symbol Table, Moved from SG_DbHelper
479
        @author     Jeongwoo
480
        @date       2018.05.03
481
    '''
482
    def insertSymbol(self, symbol):
483
        isAdded = False
484
        try:
485
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
486
            conn = sqlite3.connect(dbPath)
487
            
488
            INSERT_SYMBOL_SQL = """
489
                INSERT INTO Symbol(name, SymbolType_UID, threshold, minMatchPoint, isDetectOrigin, rotationCount, ocrOption, isContainChild, originalPoint, connectionPoint, baseSymbol, additionalSymbol, isExceptDetect, hasInstrumentLabel, width, height, flip) 
490
                VALUES(?, (select UID from SymbolType where Type=?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
491
            """
492

    
493
            cursor = conn.cursor()
494
            query = ( symbol.getName(), symbol.getType(), symbol.getThreshold()
495
                           , symbol.getMinMatchCount(), symbol.getIsDetectOnOrigin(), symbol.getRotationCount()
496
                           , symbol.getOcrOption(), symbol.getIsContainChild()
497
                           , symbol.getOriginalPoint(), symbol.getConnectionPoint()
498
                           , symbol.getBaseSymbol(), symbol.getAdditionalSymbol(), symbol.getIsExceptDetect(), symbol.getHasInstrumentLabel()
499
                           , symbol.width, symbol.height, symbol.detectFlip)
500
            cursor.execute(INSERT_SYMBOL_SQL, query)
501
            conn.commit()
502
            isAdded = True
503
        # Catch the exception
504
        except Exception as ex:
505
            # Roll back any change if something goes wrong
506
            conn.rollback()
507
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
508
        finally:
509
            conn.close()
510
            return (isAdded, symbol.getType(), symbol.getName(), symbol.getPath())
511

    
512
    '''
513
        @brief      Update symbol in Symbol Table, Moved from SG_DbHelper
514
        @author     Jeongwoo
515
        @date       2018.05.03
516
    '''
517
    def updateSymbol(self, symbol):
518
        isUpdated = False
519
        try:
520
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
521
            conn = sqlite3.connect(dbPath)
522
            
523
            UPDATE_SYMBOL_SQL = """
524
                UPDATE Symbol
525
                SET
526
                    name = ?, SymbolType_UID=(select UID from SymbolType where Type=?), threshold = ?, minMatchPoint = ?, isDetectOrigin = ?,
527
                    rotationCount = ?, ocrOption = ?, isContainChild = ?, originalPoint = ?, connectionPoint = ?,
528
                    baseSymbol = ?, additionalSymbol = ?, isExceptDetect = ?, hasInstrumentLabel = ?, width = ?, height = ?, flip = ?
529
                WHERE uid = ?
530
            """
531
            
532
            cursor = conn.cursor()
533
            query = (symbol.getName(), symbol.getType(), symbol.getThreshold()
534
                           , symbol.getMinMatchCount(), symbol.getIsDetectOnOrigin(), symbol.getRotationCount()
535
                           , symbol.getOcrOption(), symbol.getIsContainChild()
536
                           , symbol.getOriginalPoint(), symbol.getConnectionPoint()
537
                           , symbol.getBaseSymbol(), symbol.getAdditionalSymbol(), symbol.getIsExceptDetect(), symbol.getHasInstrumentLabel(), symbol.width, symbol.height, symbol.detectFlip, symbol.getUid())
538
            cursor.execute(UPDATE_SYMBOL_SQL, query)
539
            conn.commit()
540
            isUpdated = True
541
        # Catch the exception
542
        except Exception as ex:
543
            # Roll back any change if something goes wrong
544
            conn.rollback()
545
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
546
        finally:
547
            conn.close()
548
            return (isUpdated, symbol.getType(), symbol.getName(), symbol.getPath())
549

    
550
    '''
551
        @brief      Get Detecting Target Symbol List (Field 'isExceptDetect' == False(0))
552
        @author     Jeongwoo
553
        @date       18.04.24
554
        @history    humkyung 2018.06.28 select symbol order by threshold descending
555
    '''
556
    def getTargetSymbolList(self):
557
        targetSymbolList = []
558

    
559
        try:
560
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
561

    
562
            conn = sqlite3.connect(dbPath)
563
            cursor = conn.cursor()
564
            sql = """SELECT a.UID,a.Name,b.Type,a.Threshold,a.MinMatchPoint,a.IsDetectOrigin,a.RotationCount,a.OCROption,a.IsContainChild,a.OriginalPoint,a.ConnectionPoint,
565
                    a.BaseSymbol,a.AdditionalSymbol,a.IsExceptDetect,a.HasInstrumentLabel,a.flip FROM Symbol a inner join SymbolType b on a.SymbolType_UID=b.UID WHERE a.IsExceptDetect = 0 order by width * height desc"""
566
            try:
567
                cursor.execute(sql)
568
                rows = cursor.fetchall()
569
                for row in rows:
570
                    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], detectFlip=row[15]) ## uid is last item
571
                    targetSymbolList.append(sym)
572
            except Exception as ex:
573
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
574
        finally:
575
            conn.close()
576

    
577
        return targetSymbolList
578

    
579
    '''
580
        @brief  build application database
581
        @author humkyung
582
        @date   2018.04.20
583
    '''
584
    def buildAppDatabase(self):
585
        try:
586
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
587
            appDatabaseFilePath = os.path.join(path, 'App.db')
588

    
589
            # Creates or opens a file called mydb with a SQLite3 DB
590
            conn = sqlite3.connect(appDatabaseFilePath)
591
            # Get a cursor object
592
            cursor = conn.cursor()
593

    
594
            sqlFiles = ['App.Configuration.sql', 'App.Styles.sql']
595
            for sqlFile in sqlFiles:
596
                filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', sqlFile)
597
                try:
598
                    file = QFile(filePath)
599
                    file.open(QFile.ReadOnly)
600
                    sql = file.readAll()
601
                    sql = str(sql, encoding='utf8')
602
                    cursor.executescript(sql)
603
                finally:
604
                    file.close()
605
            conn.commit()
606
        # Catch the exception
607
        except Exception as ex:
608
            # Roll back any change if something goes wrong
609
            conn.rollback()
610
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
611
        finally:
612
            # Close the db connection
613
            conn.close()
614

    
615
        configs = [Config('app', 'mode', 'advanced'), Config('app', 'error origin point', '51,72')]
616
        self.saveAppConfigs(configs)
617

    
618
    '''
619
        @brief  load app style
620
        @author humkyung
621
        @date   2018.04.20
622
    '''
623
    def loadAppStyle(self):
624
        style = 'Fusion'
625

    
626
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
627
        if not os.path.exists(path): os.makedirs(path)
628

    
629
        self.buildAppDatabase()
630
        try:
631
            appDatabaseFilePath = os.path.join(path, 'App.db')
632
            # Creates or opens a file called mydb with a SQLite3 DB
633
            conn = sqlite3.connect(appDatabaseFilePath)
634
            # Get a cursor object
635
            cursor = conn.cursor()
636

    
637
            sql = "select Value from Configuration where Section='App' and Key='Style'" 
638
            cursor.execute(sql)
639
            rows = cursor.fetchall()
640
            style = rows[0][0] if 1 == len(rows) else 'Fusion'
641
        # Catch the exception
642
        except Exception as ex:
643
            # Roll back any change if something goes wrong
644
            conn.rollback()
645
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
646
        finally:
647
            # Close the db connection
648
            conn.close()
649

    
650
        return style
651

    
652
    '''
653
        @brief  load app styles and then return a list
654
        @author humkyung
655
        @date   2018.04.20
656
    '''
657
    def loadAppStyles(self):
658
        styles = []
659

    
660
        try:
661
            self.buildAppDatabase()
662

    
663
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
664
            appDatabaseFilePath = os.path.join(path, 'App.db')
665

    
666
            # Creates or opens a file called mydb with a SQLite3 DB
667
            conn = sqlite3.connect(appDatabaseFilePath)
668
            # Get a cursor object
669
            cursor = conn.cursor()
670

    
671
            sql = 'select UID,Value from Styles'
672
            cursor.execute(sql)
673
            rows = cursor.fetchall()
674
            for row in rows: styles.append(row[1])
675
            if 0 == len(rows): rows.append('fusion')
676
        # Catch the exception
677
        except Exception as ex:
678
            # Roll back any change if something goes wrong
679
            conn.rollback()
680
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
681
        finally:
682
            # Close the db connection
683
            conn.close()
684

    
685
        return styles
686

    
687
    '''
688
        @brief  Set current Project
689
        @history    2018.06.27  Jeongwoo    If DB file is not, copy DB file from ProgramData
690
    '''
691
    def setCurrentProject(self, project):
692
        self.project = project
693
        self.makeChildDir()
694
        try:
695
            # Creates or opens a file called mydb with a SQLite3 DB
696
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath() , "ITI_PID.db")
697
            
698
            if not os.path.isfile(dbPath):
699
                templatePath = self.getTemplateDbPath()
700
                templateFile = QFile(templatePath)
701
                templateFile.copy(dbPath)
702
            else:
703
                try:
704
                    conn = sqlite3.connect(dbPath)
705
                    # Get a cursor object
706
                    cursor = conn.cursor()
707

    
708
                    fileNames = os.listdir(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts'))
709
                    for fileName in fileNames:
710
                        if fileName.endswith(".sql") and (1 == len(os.path.splitext(fileName)[0].split('.'))):
711
                            try:
712
                                file = QFile(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', fileName))
713
                                file.open(QFile.ReadOnly)
714
                                sql = file.readAll()
715
                                sql = str(sql, encoding='utf8')
716
                                cursor.executescript(sql)
717
                            finally:
718
                                file.close()
719
                    conn.commit()
720
                except Exception as ex:
721
                    print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
722
                finally:
723
                    conn.close()
724
        # Catch the exception
725
        except Exception as ex:
726
            # Roll back any change if something goes wrong
727
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
728
        finally:
729
            pass
730

    
731
    '''
732
        @brief      Make Directory
733
        @author     Jeongwoo
734
        @date       18.05.08
735
        @history    humkyung 2018.06.19 make 'Tile' directory
736
                    humkyung 2018.07.09 make drawing folder if not exists
737
                    euisung 2018.09.28 make training folder if not exists
738
    '''
739
    def makeChildDir(self):
740
        project = AppDocData.instance().getCurrentProject()
741
        dbDir = project.getDbFilePath()
742
        if not os.path.exists(dbDir):
743
            os.makedirs(dbDir)
744
        imgDir = project.getImageFilePath()
745
        if not os.path.exists(imgDir):
746
            os.makedirs(imgDir)
747
        svgDir = project.getSvgFilePath()
748
        if not os.path.exists(svgDir):
749
            os.makedirs(svgDir)
750
        outputDir = project.getOutputPath()
751
        if not os.path.exists(outputDir):
752
            os.makedirs(outputDir)
753
        tempDir = project.getTempPath()
754
        if not os.path.exists(tempDir):
755
            os.makedirs(tempDir)
756
        drawingPath = project.getDrawingFilePath()
757
        if not os.path.exists(drawingPath):
758
            os.makedirs(drawingPath)
759
        trainingPath = project.getTrainingFilePath()
760
        if not os.path.exists(trainingPath):
761
            os.makedirs(trainingPath)
762
        
763
        path = os.path.join(tempDir, 'Tile')
764
        if not os.path.exists(path):
765
            os.makedirs(path)
766

    
767
    '''
768
        @brief  Get current Project
769
    '''
770
    def getCurrentProject(self):
771
        return self.project
772

    
773
    '''
774
        @brief      return project database path
775
        @history    humkyung 2018.04.19 return Project.db in Program Data folder instead of PROJECT_DB_PATH variable
776
    '''
777
    def getPrjDatabasePath(self):
778
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
779
        if not os.path.exists(path): os.makedirs(path)
780

    
781
        prjDatabaseFilePath = os.path.join(path, 'Project.db')
782
        try:
783
            # Creates or opens a file called mydb with a SQLite3 DB
784
            conn = sqlite3.connect(prjDatabaseFilePath)
785
            # Get a cursor object
786
            cursor = conn.cursor()
787

    
788
            filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', 'Project.Projects.sql')
789
            try:
790
                file = QFile(filePath)
791
                file.open(QFile.ReadOnly)
792
                sql = file.readAll()
793
                sql = str(sql, encoding='utf8')
794
                cursor.executescript(sql)
795
            finally:
796
                file.close()
797
            conn.commit()
798
        # Catch the exception
799
        except Exception as ex:
800
            # Roll back any change if something goes wrong
801
            conn.rollback()
802
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
803
        finally:
804
            # Close the db connection
805
            conn.close()
806
        
807
        return prjDatabaseFilePath
808

    
809
    def getErrorItemSvgPath(self):
810
        '''
811
            @brief  return error item svg path
812
            @author euisung
813
            @date   2019.04.02
814
        '''
815
        return os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID', 'Explode.svg')
816

    
817
    def updateTitleBlockProperties(self, titleBlockProps):
818
        '''
819
            @brief  update title block properties
820
            @author euisung
821
            @date   2018.11.09
822
        '''
823
        try:
824
            for titleBlockProp in titleBlockProps:
825
                titleBlockProp[1] = self.imgName + '!@!' + titleBlockProp[1]
826
            originTitleBlockProps = self.getTitleBlockProperties()
827
            deletedTitleBlockProps = []
828
            for originTitleBlockProp in originTitleBlockProps:
829
                for titleBlockProp in titleBlockProps:
830
                    # uid compare for determine delete props
831
                    if originTitleBlockProp[0] == titleBlockProp[0]:
832
                        break
833
                deletedTitleBlockProps.append(originTitleBlockProp[0])
834
            
835
            # Creates or opens a file called mydb with a SQLite3 DB
836
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
837
            conn = sqlite3.connect(dbPath)
838
            # Get a cursor object
839
            cursor = conn.cursor()
840

    
841
            for deletedTitleBlockProp in deletedTitleBlockProps:
842
                sql = "delete from TitleBlockProperties where UID='{}'".format(deletedTitleBlockProp)
843
                cursor.execute(sql)
844

    
845
            for titleBlockProp in titleBlockProps:
846
                sql = "insert or replace into TitleBlockProperties values(?,?,?)"
847
                param = (titleBlockProp[0], titleBlockProp[1], titleBlockProp[2]) # uid, name, area
848
                cursor.execute(sql, param)
849
            conn.commit()
850
        # Catch the exception
851
        except Exception as ex:
852
            # Roll back any change if something goes wrong
853
            conn.rollback()
854
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
855
        finally:
856
            # Close the db connection
857
            conn.close()
858

    
859
        self._titleBlockProperties = None
860
    
861
    def getTitleBlockProperties(self):
862
        '''
863
            @brief  return title block properties
864
            @author euisung
865
            @date   2018.11.09
866
        '''
867
        res = None
868
        if True:#self._titleBlockProperties is None:
869
            try:
870
                self._titleBlockProperties = []
871

    
872
                # Creates or opens a file called mydb with a SQLite3 DB
873
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
874
                db = sqlite3.connect(dbPath)
875
                # Get a cursor object
876
                cursor = db.cursor()
877

    
878
                sql = "select UID, Name, AREA from TitleBlockProperties" 
879
                cursor.execute(sql)
880
                rows = cursor.fetchall()
881
                for row in rows:
882
                    if row[1].split('!@!')[0] != self.imgName:
883
                        continue
884
                    else:
885
                        attr = []
886
                        attr.append(row[0]) # uid
887
                        attr.append(row[1].split('!@!')[1]) # name
888
                        attr.append(row[2]) # area
889
                        self._titleBlockProperties.append(attr)
890
                
891
                res = self._titleBlockProperties
892
            # Catch the exception
893
            except Exception as ex:
894
                # Roll back any change if something goes wrong
895
                db.rollback()
896
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
897
            finally:
898
                # Close the db connection
899
                db.close()
900
        else:
901
            res = self._titleBlockProperties
902

    
903
        return res
904

    
905
    def clearLineNoProperties(self):
906
        self._lineNoProperties = None
907

    
908
    '''
909
        @brief  return line properties
910
        @author humkyung
911
        @date   2018.04.09
912
    '''
913
    def getLineProperties(self):
914
        from SymbolAttr import SymbolAttr
915

    
916
        res = None
917
        if self._lineNoProperties is None:
918
            try:
919
                self._lineNoProperties = []
920

    
921
                # Creates or opens a file called mydb with a SQLite3 DB
922
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
923
                db = sqlite3.connect(dbPath)
924
                # Get a cursor object
925
                cursor = db.cursor()
926

    
927
                sql = "select UID, Name, DisplayName, Type, LimitNumber, [index] from LineProperties order by [index]" 
928
                cursor.execute(sql)
929
                rows = cursor.fetchall()
930
                for row in rows:
931
                    attr = SymbolAttr()
932
                    attr.UID = row[0]
933
                    attr.Attribute = row[1]
934
                    attr.DisplayAttribute = row[2]
935
                    attr.AttributeType = row[3]
936
                    attr.Length = row[4]
937
                    self._lineNoProperties.append(attr)
938
                
939
                res = self._lineNoProperties
940
            # Catch the exception
941
            except Exception as ex:
942
                # Roll back any change if something goes wrong
943
                db.rollback()
944
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
945
            finally:
946
                # Close the db connection
947
                db.close()
948
        else:
949
            res = self._lineNoProperties
950

    
951
        return res
952

    
953
    '''
954
        @brief  return line properties
955
        @author humkyung
956
        @date   2018.04.09
957
    '''
958
    def getLinePropertiesByUID(self, UID):
959
        from SymbolAttr import SymbolAttr
960

    
961
        res = []
962
        try:
963
            # Creates or opens a file called mydb with a SQLite3 DB
964
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
965
            db = sqlite3.connect(dbPath)
966
            # Get a cursor object
967
            cursor = db.cursor()
968

    
969
            sql = "select UID, Name, DisplayName, Type, LimitNumber, [index] from LineProperties where uid = '{}'".format(UID)
970
            cursor.execute(sql)
971
            rows = cursor.fetchall()
972
            for row in rows:
973
                attr = SymbolAttr()
974
                attr.UID = row[0]
975
                attr.Attribute = row[1]
976
                attr.DisplayAttribute = row[2]
977
                attr.AttributeType = row[3]
978
                attr.Length = row[4]
979
                res.append(attr)
980
        # Catch the exception
981
        except Exception as ex:
982
            # Roll back any change if something goes wrong
983
            db.rollback()
984
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
985
        finally:
986
            # Close the db connection
987
            db.close()
988

    
989
        return res
990

    
991
    '''
992
        @brief  return line types 
993
        @author humkyung
994
        @date   2018.06.27
995
    '''
996
    def getLineTypes(self):
997
        from LineTypeConditions import LineTypeConditions
998

    
999
        res = []
1000
        try:
1001
            # Creates or opens a file called mydb with a SQLite3 DB
1002
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1003
            db = sqlite3.connect(dbPath)
1004
            # Get a cursor object
1005
            cursor = db.cursor()
1006

    
1007
            sql = "select UID,Name,Type1,Conditions1,Type2,Conditions2 from LineTypes order by Name" 
1008
            cursor.execute(sql)
1009
            rows = cursor.fetchall()
1010
            for row in rows:
1011
                line_type = LineTypeConditions(row[0], row[1])
1012
                line_type._conditions[0][0] = row[2]
1013
                line_type._conditions[0][1] = row[3]
1014
                line_type._conditions[1][0] = row[4]
1015
                line_type._conditions[1][1] = row[5]
1016
                res.append(line_type)
1017
        # Catch the exception
1018
        except Exception as ex:
1019
            # Roll back any change if something goes wrong
1020
            db.rollback()
1021
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1022
        finally:
1023
            # Close the db connection
1024
            db.close()
1025

    
1026
        return res
1027

    
1028
    '''
1029
        @brief      Insert New Project Info
1030
        @author     Jeongwoo
1031
        @date       2018.04.06
1032
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
1033
    '''
1034
    def insertProjectInfo(self, desc, prj_unit, dir):
1035
        try:
1036
            prjDatabaseFilePath = self.getPrjDatabasePath()
1037
            conn = sqlite3.connect(prjDatabaseFilePath)
1038
            folderName = dir.split('/')[-1]
1039
            if folderName:
1040
                nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
1041
                sql = "insert or replace into Projects(Name, [Desc], [Unit], Path, CreatedDate, UpdatedDate) values(?, ?, ?, ?, ?, ?)"
1042
                param = (folderName, desc, prj_unit, dir, nowDate, nowDate)
1043
    
1044
                cursor = conn.cursor()
1045
                cursor.execute(sql, param)
1046
                conn.commit()
1047
            else:
1048
                print("Empty folder name")
1049
        except Exception as ex:
1050
            # Roll back any change if something goes wrong
1051
            conn.rollback()
1052
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1053
        finally:
1054
            conn.close()
1055

    
1056
    def removeProjectInfo(self, targetProject):
1057
        '''
1058
        @brief      Remove Project Info
1059
        @author     Euisung
1060
        @date       2019.01.28
1061
        '''
1062
        try:
1063
            prjDatabaseFilePath = self.getPrjDatabasePath()
1064
            conn = sqlite3.connect(prjDatabaseFilePath)
1065
            sql = "delete from Projects where Id = '{}'".format(targetProject.id)
1066
            cur = conn.cursor()
1067
            cur.execute(sql)
1068
            conn.commit()
1069
        except Exception as ex:
1070
            # Roll back any change if something goes wrong
1071
            conn.rollback()
1072
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1073
        finally:
1074
            conn.close()
1075

    
1076
    '''
1077
        @brief      Update Project UpdatedDate Field
1078
        @author     Jeongwoo
1079
        @date       2018.04.06
1080
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
1081
    '''
1082
    def updateProjectUpdatedDate(self, id, desc, prj_unit):
1083
        try:
1084
            prjDatabaseFilePath = self.getPrjDatabasePath()
1085
            conn = sqlite3.connect(prjDatabaseFilePath)
1086
            nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
1087
            sql = '''
1088
                UPDATE Projects
1089
                SET UpdatedDate = ?,[Desc]=?,[Unit]=? 
1090
                WHERE Id = ?
1091
            '''
1092
            cur = conn.cursor()
1093
            cur.execute(sql, (nowDate, desc, prj_unit, id))
1094
            conn.commit()
1095
        except Exception as ex:
1096
            # Roll back any change if something goes wrong
1097
            conn.rollback()
1098
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1099
        finally:
1100
            conn.close()
1101

    
1102
    '''
1103
        @brief  get project list from database
1104
        @history    humkyung 2018.04.18 add only project which's project exists
1105
    '''
1106
    def getProjectList(self):
1107
        from Project import Project
1108

    
1109
        projectList = []
1110

    
1111
        try:
1112
            conn = sqlite3.connect(self.getPrjDatabasePath())
1113
            cursor = conn.cursor()
1114
            sql = 'SELECT id,name,[desc],[unit],path,createddate,updateddate  FROM Projects ORDER BY UpdatedDate DESC'
1115
            try:
1116
                cursor.execute(sql)
1117
                rows = cursor.fetchall()
1118
                for row in rows:
1119
                    if os.path.isdir(row[4]):   # check if folder exists
1120
                        projectList.append(Project(row[0], row[1], desc=row[2], prj_unit=row[3], path=row[4], createDate=row[5], updateDate=row[6]))
1121
            except Exception as ex:
1122
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1123
        finally:
1124
            conn.close()
1125

    
1126
        return projectList
1127

    
1128
    '''
1129
        @brief  get sliding window size
1130
        @author humkyung
1131
    '''
1132
    def getSlidingWindowSize(self):
1133
        res = [10,15]
1134
        try:
1135
            configs = self.getConfigs('Sliding Window')
1136
            for config in configs:
1137
                if config.key == 'Width':
1138
                    res[0] = int(config.value)
1139
                elif config.key == 'Height':
1140
                    res[1] = int(config.value)
1141
        # Catch the exception
1142
        except Exception as ex:
1143
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1144
        
1145
        return res
1146

    
1147
    '''
1148
        @brief  get line no configuration
1149
        @author humkyung
1150
        @date   2018.04.16
1151
    '''
1152
    def getLineNoConfiguration(self):
1153
        res = None
1154
        try:
1155
            # Creates or opens a file called mydb with a SQLite3 DB
1156
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1157
            conn = sqlite3.connect(dbPath)
1158
            # Get a cursor object
1159
            cursor = conn.cursor()
1160

    
1161
            delimiter = None
1162
            sql = "select * from configuration where section='Line No' and key='Delimiter"
1163
            cursor.execute(sql)
1164
            rows = cursor.fetchall()
1165
            if len(rows) == 1:
1166
                delimiter = rows[0][2]
1167

    
1168
            if delimiter is not None:
1169
                sql = "select * from configuration where section='Line No' and key='Configuration'"
1170
                cursor.execute(sql)
1171
                rows = cursor.fetchall()
1172
                if len(rows) == 1:
1173
                    res = rows[0][2].split(delimiter)
1174
        # Catch the exception
1175
        except Exception as ex:
1176
            # Roll back any change if something goes wrong
1177
            conn.rollback()
1178
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1179
        finally:
1180
            # Close the db connection
1181
            conn.close()
1182
        
1183
        return res
1184

    
1185
    '''
1186
        @brief  get area list
1187
        @author humkyung
1188
        @history    euisung     2018.11.20 (0,0),(0,0) process add
1189
    '''
1190
    def getAreaList(self):
1191
        from Area import Area
1192

    
1193
        if len(self._areas) == 0:
1194
            try:
1195
                # Creates or opens a file called mydb with a SQLite3 DB
1196
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1197
                conn = sqlite3.connect(dbPath)
1198
                # Get a cursor object
1199
                cursor = conn.cursor()
1200

    
1201
                sql = "select * from configuration where section='Area'"
1202
                cursor.execute(sql)
1203
                rows = cursor.fetchall()
1204
                for row in rows:
1205
                    name = row[1]
1206
                    area = Area(name)
1207
                    area.parse(row[2])
1208
                    self._areas.append(area)
1209
            # Catch the exception
1210
            except Exception as ex:
1211
                # Roll back any change if something goes wrong
1212
                conn.rollback()
1213
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1214
            finally:
1215
                # Close the db connection
1216
                conn.close()
1217
        
1218
        return self._areas 
1219

    
1220
    '''
1221
        @brief  get area of given name
1222
        @author humkyung
1223
        @date   2018.04.07
1224
    '''
1225
    def getArea(self, name):
1226
        areas = self.getAreaList()
1227
        matches = [area for area in areas if area.name==name]
1228
        if 1 == len(matches) and matches[0].height is not 0 and matches[0].width is not 0:
1229
            return matches[0]
1230

    
1231
        return None
1232

    
1233
    '''
1234
        @brief  get configurations
1235
        @author humkyung
1236
        @date   2018.04.16
1237
        @history kyouho 2018.07.09 change query method
1238
    '''
1239
    '''
1240
    def getConfigs(self, section, key=None):
1241
        res = []
1242

1243
        try:
1244
            # Creates or opens a file called mydb with a SQLite3 DB
1245
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1246
            conn = sqlite3.connect(dbPath)
1247
            # Get a cursor object
1248
            cursor = conn.cursor()
1249

1250
            if key is not None:
1251
                sql = "select * from configuration where section=? and key=?"
1252
                param = (section, key)
1253
            else:
1254
                sql = "select * from configuration where section=?"
1255
                param = (section,)
1256

1257
            cursor.execute(sql, param)
1258
            rows = cursor.fetchall()
1259
            for row in rows:
1260
                res.append(Config(row[0], row[1], row[2]))
1261
        # Catch the exception
1262
        except Exception as ex:
1263
            # Roll back any change if something goes wrong
1264
            conn.rollback()
1265
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1266
        finally:
1267
            # Close the db connection
1268
            conn.close()
1269

1270
        return res
1271
        '''
1272
    def getConfigs(self, section, key=None):        
1273
        res = []
1274

    
1275
        if self.configTable is None:
1276
            self.configTable = []
1277
            try:
1278
                # Creates or opens a file called mydb with a SQLite3 DB
1279
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1280
                conn = sqlite3.connect(dbPath)
1281
                # Get a cursor object
1282
                cursor = conn.cursor()
1283

    
1284
                sql = "select * from configuration"
1285
            
1286
                cursor.execute(sql)
1287
                rows = cursor.fetchall()
1288
                for row in rows:
1289
                    self.configTable.append(Config(row[0], row[1], row[2]))
1290
                # Catch the exception
1291
            except Exception as ex:
1292
                # Roll back any change if something goes wrong
1293
                conn.rollback()
1294
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1295
            finally:
1296
                # Close the db connection
1297
                conn.close()
1298

    
1299
        if key is not None:
1300
            for con in self.configTable:
1301
                if con.section == section and con.key == key:
1302
                    res.append(con)
1303
        else:
1304
            for con in self.configTable:
1305
                if con.section == section:
1306
                    res.append(con)
1307

    
1308
        return res
1309

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

    
1317
        res = []
1318

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

    
1326
            if key is not None:
1327
                sql = "select * from configuration where section=? and key=?"
1328
                param = (section, key)
1329
            else:
1330
                sql = "select * from configuration where section=?"
1331
                param = (section,)
1332

    
1333
            cursor.execute(sql, param)
1334
            rows = cursor.fetchall()
1335
            for row in rows:
1336
                res.append(Config(row[0], row[1], row[2]))
1337
        # Catch the exception
1338
        except Exception as ex:
1339
            # Roll back any change if something goes wrong
1340
            conn.rollback()
1341
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1342
        finally:
1343
            # Close the db connection
1344
            conn.close()
1345

    
1346
        return res
1347

    
1348
    '''
1349
        @brief      save configurations
1350
        @author     humkyung
1351
        @date       2018.04.16
1352
        @history    humkyung 2018.07.03 replace ' with " if value has '
1353
                    kyouho 2018.07.09 change query method
1354
    '''
1355
    def saveConfigs(self, configs):
1356
        try:
1357
            # Creates or opens a file called mydb with a SQLite3 DB
1358
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1359
            conn = sqlite3.connect(dbPath, isolation_level=None)
1360
            # Get a cursor object
1361
            cursor = conn.cursor()
1362

    
1363
            for config in configs:
1364
                if type(config) is Config:
1365
                    value = config.value
1366
                    if type(value) is str and "'" in value:
1367
                        value = value.replace("'", "''")
1368

    
1369
                    sql = "insert or replace into configuration values(?,?,?)"
1370
                    param = (config.section, config.key, value)
1371

    
1372
                    cursor.execute(sql, param)
1373
                elif hasattr(config, 'toSql'):
1374
                    sql = config.toSql()
1375
                    if type(sql) is list:
1376
                        for item in sql:
1377
                            if item is not None and 2 == len(item):
1378
                                cursor.execute(item[0], item[1])
1379
                    else:
1380
                        if sql is not None and 2 == len(sql):
1381
                            cursor.execute(sql[0], sql[1])
1382

    
1383
            conn.commit()
1384
        # Catch the exception
1385
        except Exception as ex:
1386
            # Roll back any change if something goes wrong
1387
            conn.rollback()
1388
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1389
        finally:
1390
            # Close the db connection
1391
            conn.close()
1392

    
1393
    def saveAppConfigs(self, configs):
1394
        """
1395
        @brief      save application configurations
1396
        @author     humkyung
1397
        @date       2018.10.01
1398
        """
1399

    
1400
        try:
1401
            # Creates or opens a file called mydb with a SQLite3 DB
1402
            dbPath = self.getAppDbPath()
1403
            conn = sqlite3.connect(dbPath)
1404
            # Get a cursor object
1405
            cursor = conn.cursor()
1406

    
1407
            for config in configs:
1408
                value = config.value
1409
                if type(value) is str and "'" in value:
1410
                    value = value.replace("'", "''")
1411

    
1412
                sql = "insert or replace into configuration values(?,?,?)"
1413
                param = (config.section, config.key, value)
1414

    
1415
                cursor.execute(sql, param)
1416
            conn.commit()
1417
        # Catch the exception
1418
        except Exception as ex:
1419
            # Roll back any change if something goes wrong
1420
            conn.rollback()
1421
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1422
        finally:
1423
            # Close the db connection
1424
            conn.close()
1425

    
1426
    '''
1427
        @brief  delete configurations
1428
        @author humkyung
1429
        @date   2018.06.29
1430
    '''
1431
    def deleteConfigs(self, section, key=None):
1432
        try:
1433
            # Creates or opens a file called mydb with a SQLite3 DB
1434
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
1435
            conn = sqlite3.connect(dbPath)
1436
            # Get a cursor object
1437
            cursor = conn.cursor()
1438

    
1439
            if key is not None:
1440
                sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
1441
            else:
1442
                sql = "delete from configuration where section='{}'".format(section)
1443
            cursor.execute(sql)
1444

    
1445
            conn.commit()
1446
        # Catch the exception
1447
        except Exception as ex:
1448
            # Roll back any change if something goes wrong
1449
            conn.rollback()
1450
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1451
        finally:
1452
            # Close the db connection
1453
            conn.close()
1454

    
1455
    def deleteAppConfigs(self, section, key=None):
1456
        """
1457
        @brief  delete application configurations
1458
        @author humkyung
1459
        @date   2018.11.01
1460
        """
1461

    
1462
        try:
1463
            # Creates or opens a file called mydb with a SQLite3 DB
1464
            dbPath = self.getAppDbPath()
1465
            conn = sqlite3.connect(dbPath)
1466
            # Get a cursor object
1467
            cursor = conn.cursor()
1468

    
1469
            if key is not None:
1470
                sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
1471
            else:
1472
                sql = "delete from configuration where section='{}'".format(section)
1473
            cursor.execute(sql)
1474

    
1475
            conn.commit()
1476
        # Catch the exception
1477
        except Exception as ex:
1478
            # Roll back any change if something goes wrong
1479
            conn.rollback()
1480
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1481
        finally:
1482
            # Close the db connection
1483
            conn.close()
1484

    
1485
    '''
1486
        @brief      set area list
1487
        @history    humkyung 2018.05.18 round area coordinate and dimension before saving
1488
        @history    euisung  2018.11.20 add self._area reset process
1489
    '''
1490
    def setAreaList(self, areas):
1491
        for area in areas:
1492
            matches = [x for x in self._areas if x.name==area.name]
1493
            if 1 == len(matches):
1494
                matches[0].x = area.x
1495
                matches[0].y = area.y
1496
                matches[0].width = area.width
1497
                matches[0].height = area.height
1498
            elif 0 == len(matches):
1499
                self._areas.append(area)
1500

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

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

    
1512
            conn.commit()
1513
        # Catch the exception
1514
        except Exception as ex:
1515
            # Roll back any change if something goes wrong
1516
            conn.rollback()
1517
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1518
        finally:
1519
            # Close the db connection
1520
            self._areas = []
1521
            conn.close()
1522
            
1523
    '''
1524
        @brief  get symbol name list
1525
    '''
1526
    def getSymbolNameList(self):
1527
        symbolNametList = []
1528

    
1529
        try:
1530
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
1531

    
1532
            conn = sqlite3.connect(dbPath)
1533
            cursor = conn.cursor()
1534
            sql = 'SELECT * FROM SymbolName'
1535
            try:
1536
                cursor.execute(sql)
1537
                rows = cursor.fetchall()
1538
                for row in rows:
1539
                    symbolNametList.append(row[4]) # Name String
1540
            except Exception as ex:
1541
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1542
        finally:
1543
            conn.close()
1544

    
1545
        return symbolNametList
1546

    
1547
    '''
1548
        @brief      get symbol name list by symbol Type
1549
        @author     Jeongwoo
1550
        @date       18.04.06
1551
        @history    .
1552
    '''
1553
    def getSymbolNameListByType(self, type):
1554
        symbolNametList = []
1555

    
1556
        try:
1557
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
1558

    
1559
            conn = sqlite3.connect(dbPath)
1560
            cursor = conn.cursor()
1561
            sql = ''
1562
            if type is not None:
1563
                sql = 'SELECT * FROM SymbolName WHERE type = "' + type + '"'
1564
                try:
1565
                    cursor.execute(sql)
1566
                    rows = cursor.fetchall()
1567
                    for row in rows:
1568
                        symbolNametList.append(row[4]) # Name String
1569
                except Exception as ex:
1570
                    print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1571
        finally:
1572
            conn.close()
1573

    
1574
        return symbolNametList
1575

    
1576
    '''
1577
        @brief  delete added symbol data
1578
    '''
1579
    def deleteSymbol(self, fileName):
1580
        ret = False
1581
        try:
1582
            dbPath = self.getCurrentProject().getPath() + "/db/ITI_PID.db"
1583
            conn = sqlite3.connect(dbPath)
1584
            cursor = conn.cursor()
1585
            sql = "DELETE FROM Symbol WHERE name = ?"
1586
            try:
1587
                cursor.execute(sql, (fileName,))
1588
                conn.commit()
1589
                ret = True
1590
            except Exception as ex:
1591
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1592
                ret = False
1593
        finally:
1594
            conn.close()
1595
            return (ret, fileName)
1596
        
1597
    '''
1598
        @brief  get symbol name
1599
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1600
    '''
1601
    def getSymbolByQuery(self, fieldName, param):
1602
        ret = None
1603

    
1604
        try:
1605
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1606
            conn = sqlite3.connect(dbPath)
1607
            cursor = conn.cursor()
1608
            sql = """SELECT a.UID,a.Name,b.Type,a.Threshold,a.MinMatchPoint,a.IsDetectOrigin,a.RotationCount,a.OCROption,a.IsContainChild,a.OriginalPoint,a.ConnectionPoint,
1609
                        a.BaseSymbol,a.AdditionalSymbol,a.IsExceptDetect,a.HasInstrumentLabel,a.flip FROM Symbol a inner join SymbolType b on a.SymbolType_UID=b.UID WHERE """ + "a." + fieldName + '=?'
1610
            try:
1611
                cursor.execute(sql, (param,))
1612
                rows = cursor.fetchall()
1613
                if rows is not None and len(rows) > 0:
1614
                    symbolTuple = rows[0]
1615
                    ret = symbol.SymbolBase(symbolTuple[1], symbolTuple[2], symbolTuple[3]
1616
                                            , symbolTuple[4], symbolTuple[5], symbolTuple[6], symbolTuple[7], symbolTuple[8]
1617
                                            , symbolTuple[9], symbolTuple[10], symbolTuple[11], symbolTuple[12], symbolTuple[13], symbolTuple[14], symbolTuple[0], detectFlip=symbolTuple[15]) ## uid is last item
1618
            except Exception as ex:
1619
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1620
        finally:
1621
            conn.close()
1622

    
1623
        return ret
1624

    
1625
    '''
1626
        @brief  get symbol name list
1627
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1628
    '''
1629
    def getSymbolListByType(self, fieldName=None, param=None):
1630
        ret = []
1631

    
1632
        try:
1633
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1634
            conn = sqlite3.connect(dbPath)
1635
            cursor = conn.cursor()
1636
            if fieldName is not None and param is not None:
1637
                sql = """SELECT a.UID,a.Name,b.Type,a.Threshold,a.MinMatchPoint,a.IsDetectOrigin,a.RotationCount,a.OCROption,a.IsContainChild,a.OriginalPoint,a.ConnectionPoint,
1638
                        a.BaseSymbol,a.AdditionalSymbol,a.IsExceptDetect,a.HasInstrumentLabel,a.flip
1639
                        FROM Symbol a inner join SymbolType b on a.SymbolType_UID=b.UID WHERE SymbolType_UID = (select UID from SymbolType where Type=?)"""
1640
            else:
1641
                sql = """SELECT a.UID,a.Name,b.Type,a.Threshold,a.MinMatchPoint,a.IsDetectOrigin,a.RotationCount,a.OCROption,a.IsContainChild,a.OriginalPoint,a.ConnectionPoint,
1642
                        a.BaseSymbol,a.AdditionalSymbol,a.IsExceptDetect,a.HasInstrumentLabel,a.flip FROM Symbol a inner join SymbolType b on a.SymbolType_UID=b.UID"""
1643
            try:
1644
                cursor.execute(sql, (param,)) if param is not None else cursor.execute(sql)
1645
                rows = cursor.fetchall()
1646
                if rows is not None and len(rows) > 0:
1647
                    for symbolTuple in rows:
1648
                        sym = symbol.SymbolBase(symbolTuple[1], symbolTuple[2], symbolTuple[3], symbolTuple[4]
1649
                                                , symbolTuple[5], symbolTuple[6], symbolTuple[7], symbolTuple[8], symbolTuple[9]
1650
                                                , symbolTuple[10], symbolTuple[11], symbolTuple[12], symbolTuple[13], symbolTuple[14], symbolTuple[0], detectFlip=symbolTuple[15]) ## uid is last item
1651
                        ret.append(sym)
1652
            except Exception as ex:
1653
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1654
        finally:
1655
            conn.close()
1656

    
1657
        return ret
1658

    
1659
    '''
1660
        @brief      get NominalDiameter
1661
        @author     humkyung
1662
        @date       2018.04.20
1663
        @history    humkyung 2018.04.24 read MetricStr column and set size unit
1664
                    kyouho 2018.07.04 forCheckLineNumber get only inch or metric
1665
                    kyouho 2018.07.16 edit query order by code
1666
    '''
1667
    def getNomialPipeSizeData(self, forCheckLineNumber = False, orderStr = "CODE"):
1668
        res = []
1669
        try:
1670
            configs = self.getConfigs('Line No', 'Size Unit')
1671
            sizeUnit = configs[0].value if 1 == len(configs) else 'Metric'
1672

    
1673
            # Creates or opens a file called mydb with a SQLite3 DB
1674
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1675
            conn = sqlite3.connect(dbPath)
1676
            # Get a cursor object
1677
            cursor = conn.cursor()
1678

    
1679
            sql = "select UID,Code,Metric,Inch,InchStr,AllowableInchStr,MetricStr,AllowableMetricStr from NominalDiameter ORDER BY {} ASC".format(orderStr)
1680
            cursor.execute(sql)
1681
            rows = cursor.fetchall()
1682
            for row in rows:
1683
                pipeSize = NominalPipeSize(row[0], row[1], float(row[2]) if row[2] else None, float(row[3]) if row[3] else None, row[4], row[5], row[6], row[7])
1684
                pipeSize.sizeUnit = sizeUnit
1685
                if forCheckLineNumber:
1686
                    if sizeUnit == 'Inch' and pipeSize.inchStr:
1687
                        res.append(pipeSize.inchStr)
1688
                    elif sizeUnit == 'Metric' and pipeSize.metricStr:
1689
                        res.append(pipeSize.metricStr)
1690
                else:
1691
                    res.append(pipeSize)
1692
                
1693
        # Catch the exception
1694
        except Exception as ex:
1695
            # Roll back any change if something goes wrong
1696
            conn.rollback()
1697
            
1698
            from App import App 
1699
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1700
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1701
        finally:
1702
            # Close the db connection
1703
            conn.close()
1704

    
1705
        return res
1706

    
1707
    '''
1708
        @brief      insert NominalDiameter table
1709
        @author     kyouho
1710
        @date       2018.07.16
1711
    '''
1712
    def insertNomialPipeSize(self, pipeSizes):
1713
        try:
1714
            # Creates or opens a file called mydb with a SQLite3 DB
1715
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1716
            conn = sqlite3.connect(dbPath)
1717
            # Get a cursor object
1718
            cursor = conn.cursor()
1719
            for pipeSize in pipeSizes:
1720
                sql = pipeSize.toSql()
1721
                if type(sql) is list and len(sql) == 1:
1722
                    cursor.execute(sql[0][0], sql[0][1])
1723

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

    
1734
    '''
1735
        @brief      delete NominalDiameter table
1736
        @author     kyouho
1737
        @date       2018.07.16
1738
    '''
1739
    def deleteNomialPipeSize(self):
1740
        try:
1741
            dbPath = os.path.join(self.getCurrentProject().getPath(), 'db', AppDocData.DATABASE)
1742
            conn = sqlite3.connect(dbPath)
1743
            cursor = conn.cursor()
1744
            sql = "DELETE FROM NominalDiameter"
1745
            try:
1746
                cursor.execute(sql)
1747
                conn.commit()
1748
            except Exception as ex:
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
            conn.close()
1752

    
1753
    '''
1754
        @brief      convert inch to metric
1755
        @author     kyouho
1756
        @date       2018.07.09
1757
    '''
1758
    def convertInchToMetric(self, inch):
1759
        result = ''
1760
        try:
1761
            # Creates or opens a file called mydb with a SQLite3 DB
1762
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1763
            conn = sqlite3.connect(dbPath)
1764
            # Get a cursor object
1765
            cursor = conn.cursor()
1766
            
1767
            sql = "select MetricStr from NominalDiameter WHERE InchStr = ?"
1768
            param = (inch,)
1769
            cursor.execute(sql, param)
1770
            rows = cursor.fetchall()
1771

    
1772
            if rows:
1773
                result = rows[0][0]
1774
            # Catch the exception
1775
        except Exception as ex:
1776
            # Roll back any change if something goes wrong
1777
            conn.rollback()
1778
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1779
        finally:
1780
            # Close the db connection
1781
            conn.close()
1782

    
1783
        return result
1784

    
1785
    '''
1786
        @brief      get Color MaxUID
1787
        @author     kyouho
1788
        @date       2018.07.03
1789
    '''
1790
    def getMaxColorUID(self):
1791
        result = 0
1792

    
1793
        try:
1794
            # Creates or opens a file called mydb with a SQLite3 DB
1795
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1796
            conn = sqlite3.connect(dbPath)
1797
            # Get a cursor object
1798
            cursor = conn.cursor()
1799

    
1800
            sql = "select MAX(UID) from Colors"
1801
            cursor.execute(sql)
1802
            rows = cursor.fetchall()
1803

    
1804
            result = rows[0][0]
1805
            # Catch the exception
1806
        except Exception as ex:
1807
            # Roll back any change if something goes wrong
1808
            conn.rollback()
1809
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1810
        finally:
1811
            # Close the db connection
1812
            conn.close()
1813

    
1814
        return result
1815

    
1816
    '''
1817
        @brief      insert Color property
1818
        @author     kyouho
1819
        @date       2018.07.09
1820
    '''
1821
    def setPropertyColor(self, _color):
1822
        try:
1823
            # Creates or opens a file called mydb with a SQLite3 DB
1824
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1825
            conn = sqlite3.connect(dbPath)
1826
            # Get a cursor object
1827
            cursor = conn.cursor()
1828
            sql = "INSERT INTO Colors(UID, RED, GREEN, BLUE, PROPERTY, VALUE) VALUES(?,?,?,?,?,?)"
1829
            param = (_color.index, _color.red, _color.green, _color.blue, _color._property, _color.value)
1830
            cursor.execute(sql, param)
1831
            conn.commit()
1832
            # Catch the exception
1833
        except Exception as ex:
1834
            # Roll back any change if something goes wrong
1835
            conn.rollback()
1836
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1837
        finally:
1838
            # Close the db connection
1839
            conn.close()
1840

    
1841
    '''
1842
        @brief      delete Color property
1843
        @author     kyouho
1844
        @date       2018.07.09
1845
    '''
1846
    def deletePropertyColor(self, property):
1847
        try:
1848
            # Creates or opens a file called mydb with a SQLite3 DB
1849
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1850
            conn = sqlite3.connect(dbPath)
1851
            # Get a cursor object
1852
            cursor = conn.cursor()
1853

    
1854
            sql = "DELETE FROM Colors WHERE PROPERTY = '{}'".format(property)
1855
            cursor.execute(sql)
1856
            conn.commit()
1857
            # Catch the exception
1858
        except Exception as ex:
1859
            # Roll back any change if something goes wrong
1860
            conn.rollback()
1861
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1862
        finally:
1863
            # Close the db connection
1864
            conn.close()
1865

    
1866
    '''
1867
        @brief      get Fluid Code
1868
        @author     kyouho
1869
        @date       2018.07.03
1870
        @history    kyouho 2018.07.04 kyouho 2018.07.04 forCheckLineNumber get only code
1871
    '''
1872
    def getFluidCodeData(self, forCheckLineNumber = False):
1873
        from FluidCodeData import FluidCodeData
1874
        result = []
1875

    
1876
        try:
1877
            # Creates or opens a file called mydb with a SQLite3 DB
1878
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1879
            conn = sqlite3.connect(dbPath)
1880
            # Get a cursor object
1881
            cursor = conn.cursor()
1882

    
1883
            sql = 'select uid, code, description from FluidCode order by length(code) DESC'
1884
            cursor.execute(sql)
1885
            rows = cursor.fetchall()
1886
            for row in rows:
1887
                data = FluidCodeData(row[0], row[1], row[2])
1888
                if forCheckLineNumber:
1889
                    result.append(data.code)
1890
                else:
1891
                    result.append(data)
1892
            # Catch the exception
1893
        except Exception as ex:
1894
            # Roll back any change if something goes wrong
1895
            conn.rollback()
1896
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1897
        finally:
1898
            # Close the db connection
1899
            conn.close()
1900

    
1901
        return result
1902

    
1903
    '''
1904
        @brief      get Symbol Attribute
1905
        @author     kyouho
1906
        @date       2018.07.18
1907
    '''
1908
    def checkAttribute(self, attr):
1909
        try:
1910
            # Creates or opens a file called mydb with a SQLite3 DB
1911
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1912
            conn = sqlite3.connect(dbPath)
1913
            # Get a cursor object
1914
            cursor = conn.cursor()
1915

    
1916
            sql = 'select UID from SymbolAttribute where UID = ?'
1917
            param = (attr,)
1918
            cursor.execute(sql, param)
1919
            rows = cursor.fetchall()
1920
            if len(rows):
1921
                return True
1922
            else:
1923
                return False
1924
            # Catch the exception
1925
        except Exception as ex:
1926
            # Roll back any change if something goes wrong
1927
            conn.rollback()
1928
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1929
        finally:
1930
            # Close the db connection
1931
            conn.close()
1932

    
1933
        return False
1934

    
1935
    '''
1936
        @brief      get Symbol Attribute
1937
        @author     kyouho
1938
        @date       2018.07.18
1939
        @history    humkyung 2018.10.13 load expression
1940
    '''
1941
    def getSymbolAttribute(self, _type):
1942
        import uuid
1943
        from SymbolAttr import SymbolAttr
1944

    
1945
        result = []
1946

    
1947
        try:
1948
            # Creates or opens a file called mydb with a SQLite3 DB
1949
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1950
            conn = sqlite3.connect(dbPath)
1951
            # Get a cursor object
1952
            cursor = conn.cursor()
1953

    
1954
            sql = 'select a.UID, a.Attribute, a.DisplayAttribute, a.AttributeType, a.[AttrAt], a.[Expression], a.[index], a.[Target], a.[Property] from SymbolAttribute a inner join SymbolType t on a.SymbolType_UID = t.UID and t.type = ? order by a.[index]'
1955
            param = (_type,)
1956
            cursor.execute(sql, param)
1957
            rows = cursor.fetchall()
1958
            for row in rows:
1959
                attr = SymbolAttr()
1960
                attr.UID = uuid.UUID(row[0], version=4)
1961
                attr.Attribute = row[1]
1962
                attr.DisplayAttribute = row[2]
1963
                attr.AttributeType = row[3]
1964
                attr.AttrAt = row[4]
1965
                attr.Expression = row[5]
1966
                attr.Target = row[7]
1967
                attr.IsProp = row[8]
1968
                result.append(attr)
1969
            # Catch the exception
1970
        except Exception as ex:
1971
            from App import App 
1972

    
1973
            # Roll back any change if something goes wrong
1974
            conn.rollback()
1975

    
1976
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1977
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1978
        finally:
1979
            # Close the db connection
1980
            conn.close()
1981

    
1982
        return result
1983

    
1984
    '''
1985
        @brief      get Symbol Attribute by UID
1986
        @author     kyouho
1987
        @date       2018.08.17
1988
        @history    humkyung 2018.10.13 load expression
1989
    '''
1990
    def getSymbolAttributeByUID(self, UID):
1991
        from SymbolAttr import SymbolAttr
1992

    
1993
        res = None
1994

    
1995
        try:
1996
            # Creates or opens a file called mydb with a SQLite3 DB
1997
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1998
            conn = sqlite3.connect(dbPath)
1999
            # Get a cursor object
2000
            cursor = conn.cursor()
2001

    
2002
            sql = 'select Attribute, DisplayAttribute, AttributeType, AttrAt, Expression, Target, Property from SymbolAttribute where uid = "{}"'.format(UID)
2003
            cursor.execute(sql)
2004
            rows = cursor.fetchall()
2005
            if len(rows):
2006
                res = SymbolAttr()
2007
                res.UID = UID
2008
                res.Attribute = rows[0][0]
2009
                res.DisplayAttribute = rows[0][1]
2010
                res.AttributeType = rows[0][2]
2011
                res.AttrAt = rows[0][3]
2012
                res.Expression = rows[0][4]
2013
                res.Target = rows[0][5]
2014
                res.IsProp = row[0][6]
2015
            # Catch the exception
2016
        except Exception as ex:
2017
            from App import App
2018

    
2019
            # Roll back any change if something goes wrong
2020
            conn.rollback()
2021

    
2022
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2023
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2024
        finally:
2025
            # Close the db connection
2026
            conn.close()
2027

    
2028
        return res
2029

    
2030
    '''
2031
        @brief      save symbol attributes
2032
        @author     humkyung
2033
        @date       2018.08.14
2034
        @history    humkyung 2018.10.13 save expression
2035
    '''
2036
    def saveSymbolAttributes(self, type, attrs):
2037
        try:
2038
            # Creates or opens a file called mydb with a SQLite3 DB
2039
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2040
            conn = sqlite3.connect(dbPath)
2041
            # Get a cursor object
2042
            cursor = conn.cursor()
2043

    
2044
            sql = 'delete from SymbolAttribute where SymbolType_UID = ?'
2045
            param = (type,)
2046
            cursor.execute(sql, param)
2047

    
2048
            for attr in attrs:
2049
                sql = 'insert into SymbolAttribute(UID, SymbolType_UID, Attribute, DisplayAttribute, AttributeType, AttrAt, Expression, Target, [index]) values(?, ?, ?, ?, ?, ?, ?, ?, ?)'
2050
                attr.insert(1, type)
2051
                param = tuple(attr)
2052
                cursor.execute(sql, param)
2053

    
2054
            conn.commit()
2055
            # Catch the exception
2056
        except Exception as ex:
2057
            # Roll back any change if something goes wrong
2058
            conn.rollback()
2059
            
2060
            from App import App 
2061
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2062
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2063
        finally:
2064
            # Close the db connection
2065
            conn.close()
2066

    
2067
    '''
2068
        @brief      save symbol attributes
2069
        @author     humkyung
2070
        @date       2018.08.14
2071
    '''
2072
    def saveLineAttributes(self, attrs):
2073
        try:
2074
            # Creates or opens a file called mydb with a SQLite3 DB
2075
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2076
            conn = sqlite3.connect(dbPath)
2077
            # Get a cursor object
2078
            cursor = conn.cursor()
2079

    
2080
            sql = 'delete from LineProperties'
2081
            cursor.execute(sql)
2082

    
2083
            for attr in attrs:
2084
                sql = 'insert into LineProperties(UID, Name, DisplayName, Type, LimitNumber, [index]) values(?, ?, ?, ?, ?, ?)'
2085
                param = tuple(attr)
2086
                cursor.execute(sql, param)
2087

    
2088
            conn.commit()
2089

    
2090
            self._lineNoProperties = None
2091
            # Catch the exception
2092
        except Exception as ex:
2093
            # Roll back any change if something goes wrong
2094
            conn.rollback()
2095
            
2096
            from App import App 
2097
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2098
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2099
        finally:
2100
            # Close the db connection
2101
            conn.close()
2102

    
2103
    '''
2104
        @brief      get symbol type id
2105
        @author     kyouho
2106
        @date       2018.08.17
2107
    '''
2108
    def getSymbolTypeId(self, symbolType):
2109
        result = []
2110

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

    
2118
            sql = 'select UID from SymbolType where Type = ?'
2119
            param = (symbolType,)
2120
            cursor.execute(sql, param)
2121
            rows = cursor.fetchall()
2122
            
2123
            if len(rows):
2124
                result = rows[0][0]
2125
            else:
2126
                result = -1
2127
            # Catch the exception
2128
        except Exception as ex:
2129
            # Roll back any change if something goes wrong
2130
            conn.rollback()
2131
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2132
        finally:
2133
            # Close the db connection
2134
            conn.close()
2135

    
2136
        return result
2137

    
2138
    '''
2139
        @brief      get Code Table Data
2140
        @author     kyouho
2141
        @date       2018.07.10
2142
    '''
2143
    def getCodeTable(self, property, forCheckLineNumber = False):
2144
        result = []
2145
        try:
2146
            # Creates or opens a file called mydb with a SQLite3 DB
2147
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2148
            conn = sqlite3.connect(dbPath)
2149
            # Get a cursor object
2150
            cursor = conn.cursor()
2151

    
2152
            if property.upper().replace(' ','') == "NOMINALDIAMETER" and forCheckLineNumber:
2153
                sql = 'select InchStr, MetricStr from [{}] order by Metric ASC'.format(property)
2154
                cursor.execute(sql)
2155
                rows = cursor.fetchall()
2156
                for index in range(2):
2157
                    for row in rows:
2158
                        if row[index] != '' and result.count(row[index].replace("'", '"')) == 0:
2159
                            result.append(row[index].replace("'", '"'))
2160
            else:
2161
                sql = "select name from sqlite_master where type='table'"# AND name={}".format(property)
2162
                cursor.execute(sql)
2163
                rows = cursor.fetchall()
2164
                if property in [name[0] for name in rows]:
2165
                    sql = 'select uid, code, description, Allowables from [{}] order by length(code) DESC'.format(property)
2166
                    cursor.execute(sql)
2167
                    rows = cursor.fetchall()
2168
                    for row in rows:
2169
                        if forCheckLineNumber:
2170
                            data = row[1]
2171
                        else:
2172
                            data = (row[0], row[1], row[2], row[3])
2173
                        result.append(data)
2174
                else:
2175
                    result = None
2176
            # Catch the exception
2177
        except Exception as ex:
2178
            from App import App 
2179

    
2180
            # Roll back any change if something goes wrong
2181
            conn.rollback()
2182
            
2183
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2184
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2185
        finally:
2186
            # Close the db connection
2187
            conn.close()
2188

    
2189
        return result
2190

    
2191
    '''
2192
        @brief      Set Common Code Data
2193
        @author     kyouho
2194
        @date       2018.07.12
2195
    '''
2196
    def saveCommonCodeData(self, tableName, datas):
2197
        import uuid
2198

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

    
2206
            for data in datas:
2207
                uid,code,description,allowables = data[0],data[1],data[2],data[3]
2208
                if not uid:
2209
                    sql = "insert or replace into {}(UID, CODE, DESCRIPTION, ALLOWABLES) values(?, ?, ?, ?)".format(tableName)
2210
                    param = (str(uuid.uuid4()), data[1], data[2], data[3])
2211
                elif uid == '-1':
2212
                    sql = 'delete from {} where uid=?'.format(tableName) 
2213
                    param = (data[-1],)
2214
                else:
2215
                    sql = "update {} SET CODE=?, DESCRIPTION=?, ALLOWABLES=? WHERE UID = ?".format(tableName)
2216
                    param = (data[1], data[2], data[3], data[0])
2217
                cursor.execute(sql, param)
2218

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

    
2230
    '''
2231
        @brief      Set Common Code Data
2232
        @author     kyouho
2233
        @date       2018.07.12
2234
    '''
2235
    def deleteCommonCodeData(self, datas):
2236
        try:
2237
            # Creates or opens a file called mydb with a SQLite3 DB
2238
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2239
            conn = sqlite3.connect(dbPath)
2240
            # Get a cursor object
2241
            cursor = conn.cursor()
2242

    
2243
            for data in datas:
2244
                uid = data[0]
2245
                tableName = data[1]
2246

    
2247
                if uid:
2248
                    sql = "delete from {} where UID = ?".format(tableName)
2249
                    param = (uid,)
2250
                    cursor.execute(sql, param)
2251

    
2252
                cursor.execute(sql, param)
2253

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

    
2265
    '''
2266
        @brief      delete data list
2267
        @author     kyouho
2268
        @date       2018.08.16
2269
    '''
2270
    def deleteDataList(self, tableName, UID):
2271
        try:
2272
            # Creates or opens a file called mydb with a SQLite3 DB
2273
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2274
            conn = sqlite3.connect(dbPath)
2275
            # Get a cursor object
2276
            cursor = conn.cursor()
2277

    
2278
            sql = 'delete from {} where UID = {}'.format(tableName, UID)
2279
            
2280
            cursor.execute(sql)
2281

    
2282
            conn.commit()
2283

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

    
2293
    def getDocumentNameList(self):
2294
        '''
2295
            @brief      get documentName list
2296
            @author     euisung
2297
            @date       2018.12.11
2298
        '''
2299
        result = []
2300

    
2301
        try:
2302
            # Creates or opens a file called mydb with a SQLite3 DB
2303
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2304
            conn = sqlite3.connect(dbPath)
2305
            # Get a cursor object
2306
            cursor = conn.cursor()
2307

    
2308
            sql = 'select DISTINCT(PNID_NO) from LINE_DATA_LIST'
2309
            cursor.execute(sql)
2310
            sql = 'select DISTINCT(PNID_NO) from EQUIPMENT_DATA_LIST'
2311
            cursor.execute(sql)
2312
            sql = 'select DISTINCT(PNID_NO) from INSTRUMENT_DATA_LIST'
2313
            cursor.execute(sql)
2314
            sql = 'select DISTINCT(PNID_NO) from NOTE_DATA_LIST'
2315
            cursor.execute(sql)
2316
            sql = 'select DISTINCT(PNID_NO) from VALVE_DATA_LIST'
2317
            cursor.execute(sql)
2318

    
2319
            rows = cursor.fetchall()
2320
            for row in rows:
2321
                result.append(row[0])
2322

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

    
2334
        return result
2335

    
2336

    
2337
    '''
2338
        @brief      get line documentName list
2339
        @author     kyouho
2340
        @date       2018.08.13
2341
    '''
2342
    def getLineDocumentNameList(self):
2343
        result = []
2344

    
2345
        try:
2346
            # Creates or opens a file called mydb with a SQLite3 DB
2347
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2348
            conn = sqlite3.connect(dbPath)
2349
            # Get a cursor object
2350
            cursor = conn.cursor()
2351

    
2352
            sql = 'select DISTINCT(PNID_NO) from LINE_DATA_LIST'
2353

    
2354
            cursor.execute(sql)
2355
            rows = cursor.fetchall()
2356
            for row in rows:
2357
                result.append(row[0])
2358
        # Catch the exception
2359
        except Exception as ex:
2360
            # Roll back any change if something goes wrong
2361
            conn.rollback()
2362
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2363
        finally:
2364
            # Close the db connection
2365
            conn.close()
2366

    
2367
        return result
2368

    
2369
    '''
2370
        @brief      get line documentName list
2371
        @author     kyouho
2372
        @date       2018.08.14
2373
    '''
2374
    def getEquipDocumentNameList(self):
2375
        result = []
2376

    
2377
        try:
2378
            # Creates or opens a file called mydb with a SQLite3 DB
2379
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2380
            conn = sqlite3.connect(dbPath)
2381
            # Get a cursor object
2382
            cursor = conn.cursor()
2383

    
2384
            sql = 'select DISTINCT(PNID_NO) from EQUIPMENT_DATA_LIST'
2385

    
2386
            cursor.execute(sql)
2387
            rows = cursor.fetchall()
2388
            for row in rows:
2389
                result.append(row[0])
2390
        # Catch the exception
2391
        except Exception as ex:
2392
            # Roll back any change if something goes wrong
2393
            conn.rollback()
2394
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2395
        finally:
2396
            # Close the db connection
2397
            conn.close()
2398

    
2399
        return result
2400

    
2401

    
2402
    '''
2403
        @brief      get line data list
2404
        @author     kyouho
2405
        @date       2018.08.13
2406
    '''
2407
    def getLineDataList(self, docName = None):
2408
        result = []
2409

    
2410
        try:
2411
            # Creates or opens a file called mydb with a SQLite3 DB
2412
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2413
            conn = sqlite3.connect(dbPath)
2414
            # Get a cursor object
2415
            cursor = conn.cursor()
2416

    
2417
            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'
2418
            if docName is not None:
2419
                sql += " where PNID_NO = '{}'".format(docName)
2420

    
2421
            cursor.execute(sql)
2422
            #columnName = list(map(lambda x: x[0].upper(), cursor.description))
2423
            rows = cursor.fetchall()
2424
            for row in rows:
2425
                data = []
2426
                for index in range(len(cursor.description)):
2427
                    data.append(row[index])
2428
                result.append(data)
2429
        # Catch the exception
2430
        except Exception as ex:
2431
            # Roll back any change if something goes wrong
2432
            conn.rollback()
2433
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2434
        finally:
2435
            # Close the db connection
2436
            conn.close()
2437

    
2438
        return result
2439

    
2440
    '''
2441
        @brief      set line data list
2442
        @author     kyouho
2443
        @date       2018.08.13
2444
    '''
2445
    def setLineDataList(self, dataLists):
2446
        try:
2447
            # Creates or opens a file called mydb with a SQLite3 DB
2448
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2449
            conn = sqlite3.connect(dbPath)
2450
            # Get a cursor object
2451
            cursor = conn.cursor()
2452
            
2453
            for data in dataLists:
2454
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2455
                param = tuple(data)
2456
                cursor.execute(sql, param)
2457

    
2458
            conn.commit()
2459

    
2460
        # Catch the exception
2461
        except Exception as ex:
2462
            # Roll back any change if something goes wrong
2463
            conn.rollback()
2464
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2465
        finally:
2466
            # Close the db connection
2467
            conn.close()
2468

    
2469
    '''
2470
        @brief      delete line data list
2471
        @author     kyouho
2472
        @date       2018.08.13
2473
    '''
2474
    def deleteLineDataList(self, removeUID):
2475
        try:
2476
            # Creates or opens a file called mydb with a SQLite3 DB
2477
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2478
            conn = sqlite3.connect(dbPath)
2479
            # Get a cursor object
2480
            cursor = conn.cursor()
2481
            
2482
            for uid in removeUID:
2483
                sql = "delete from LINE_DATA_LIST where uid = '{}'".format(uid)
2484
                cursor.execute(sql)
2485

    
2486
            conn.commit()
2487

    
2488
        # Catch the exception
2489
        except Exception as ex:
2490
            # Roll back any change if something goes wrong
2491
            conn.rollback()
2492
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2493
        finally:
2494
            # Close the db connection
2495
            conn.close()
2496

    
2497
    '''
2498
        @brief      delete line data list
2499
        @author     kyouho
2500
        @date       2018.08.13
2501
    '''
2502
    def deleteLineDataList_LineNo(self, removeUID):
2503
        try:
2504
            # Creates or opens a file called mydb with a SQLite3 DB
2505
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2506
            conn = sqlite3.connect(dbPath)
2507
            # Get a cursor object
2508
            cursor = conn.cursor()
2509
            
2510
            for uid in removeUID:
2511
                sql = "delete from LINE_DATA_LIST where LINE_NO = ?"
2512
                param = (uid,)
2513
                cursor.execute(sql, param)
2514

    
2515
            conn.commit()
2516

    
2517
        # Catch the exception
2518
        except Exception as ex:
2519
            # Roll back any change if something goes wrong
2520
            conn.rollback()
2521
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2522
        finally:
2523
            # Close the db connection
2524
            conn.close()
2525

    
2526
    '''
2527
        @brief      delete equip data list
2528
        @author     kyouho
2529
        @date       2018.08.14
2530
    '''
2531
    def deleteEquipDataList(self, removeUID):
2532
        try:
2533
            # Creates or opens a file called mydb with a SQLite3 DB
2534
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2535
            conn = sqlite3.connect(dbPath)
2536
            # Get a cursor object
2537
            cursor = conn.cursor()
2538
            
2539
            for uid in removeUID:
2540
                sql = "delete from EQUIPMENT_DATA_LIST where uid = '{}'".format(uid)
2541
                cursor.execute(sql)
2542

    
2543
            conn.commit()
2544

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

    
2554
    '''
2555
        @brief      delete inst data list
2556
        @author     kyouho
2557
        @date       2018.08.14
2558
    '''
2559
    def deleteInstDataList(self, removeUID):
2560
        try:
2561
            # Creates or opens a file called mydb with a SQLite3 DB
2562
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2563
            conn = sqlite3.connect(dbPath)
2564
            # Get a cursor object
2565
            cursor = conn.cursor()
2566
            
2567
            for uid in removeUID:
2568
                sql = "delete from INSTRUMENT_DATA_LIST where uid = '{}'".format(uid)
2569
                cursor.execute(sql)
2570

    
2571
            conn.commit()
2572

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

    
2582
    '''
2583
        @brief      delete note data list
2584
        @author     kyouho
2585
        @date       2018.10.10
2586
    '''
2587
    def deleteNoteDataList(self, removeUID):
2588
        try:
2589
            # Creates or opens a file called mydb with a SQLite3 DB
2590
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2591
            conn = sqlite3.connect(dbPath)
2592
            # Get a cursor object
2593
            cursor = conn.cursor()
2594
            
2595
            for uid in removeUID:
2596
                sql = "delete from NOTE_DATA_LIST where uid = '{}'".format(uid)
2597
                cursor.execute(sql)
2598

    
2599
            conn.commit()
2600

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

    
2610
    '''
2611
        @brief      get equipment data list
2612
        @author     humkyung
2613
        @date       2018.05.03
2614
    '''
2615
    def getEquipmentDataList(self, docName = None):
2616
        result = []
2617
        try:
2618
            # Creates or opens a file called mydb with a SQLite3 DB
2619
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2620
            conn = sqlite3.connect(dbPath)
2621
            # Get a cursor object
2622
            cursor = conn.cursor()
2623

    
2624
            sql = 'select a.*,C.Attribute,B.Value  from EQUIPMENT_DATA_LIST a left join Attributes B on a.UID=B.Components_UID ' \
2625
                                                                             'left join SymbolAttribute C on B.SymbolAttribute_UID=C.UID'
2626
            if docName is not None:
2627
                sql += " where PNID_NO = '{}'".format(docName)
2628

    
2629
            cursor.execute(sql)
2630
            col_names = [desc[0] for desc in cursor.description]    # get coloumn name
2631
            rows = cursor.fetchall()
2632
            for row in rows:
2633
                matches = [res for res in result if res['UID']==row[0]]
2634
                if matches:
2635
                    matches[0][row[len(row)-2]] = row[len(row)-1]
2636
                else:
2637
                    data = dict(zip(col_names[:-2], row[:-2]))
2638
                    if row[len(row)-2] is not None:
2639
                        data[row[len(row)-2]] = row[len(row)-1]
2640
                    result.append(data)
2641
        # Catch the exception
2642
        except Exception as ex:
2643
            from App import App 
2644

    
2645
            # Roll back any change if something goes wrong
2646
            conn.rollback()
2647
            
2648
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2649
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2650
        finally:
2651
            # Close the db connection
2652
            conn.close()
2653

    
2654
        return result
2655

    
2656
    def get_valve_data_list(self, docName = None):
2657
        """
2658
        @brief      get valve data list
2659
        @author     humkyung
2660
        @date       2018.10.11
2661
        """
2662

    
2663
        result = []
2664
        try:
2665
            # Creates or opens a file called mydb with a SQLite3 DB
2666
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2667
            conn = sqlite3.connect(dbPath)
2668
            # Get a cursor object
2669
            cursor = conn.cursor()
2670

    
2671
            sql = 'select a.UID,a.ITEM_NO,a.PNID_NO,a.MainSize,a.SubSize,c.Attribute,b.Value from VALVE_DATA_LIST a left join Attributes b on a.uid=b.Components_UID ' \
2672
                  'left join SymbolAttribute c on b.SymbolAttribute_UID=c.UID'
2673
            if docName is not None:
2674
                sql += " where PNID_NO = '{}'".format(docName)
2675

    
2676
            cursor.execute(sql)
2677
            rows = cursor.fetchall()
2678
            for row in rows:
2679
                matches = [res for res in result if res['UID'] == row[0]]
2680
                if matches:
2681
                    matches[0][row[5]] = row[6]
2682
                else:
2683
                    data = {'UID':row[0], 'ITEM_NO':row[1], 'PNID_NO':row[2], 'MainSize':row[3], 'SubSize':row[4]}
2684
                    data[row[5]] = row[6]
2685
                    result.append(data)
2686

    
2687
        # Catch the exception
2688
        except Exception as ex:
2689
            from App import App 
2690

    
2691
            # Roll back any change if something goes wrong
2692
            conn.rollback()
2693
            
2694
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2695
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2696
        finally:
2697
            # Close the db connection
2698
            conn.close()
2699

    
2700
        return result
2701

    
2702
    '''
2703
        @brief      get instrument data list
2704
        @author     kyouho
2705
        @date       2018.08.14
2706
    '''
2707
    def getInstrumentDataList(self, docName = None):
2708
        result = []
2709
        try:
2710
            # Creates or opens a file called mydb with a SQLite3 DB
2711
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2712
            conn = sqlite3.connect(dbPath)
2713
            # Get a cursor object
2714
            cursor = conn.cursor()
2715

    
2716
            #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'
2717
            sql = 'select * from INSTRUMENT_DATA_LIST'
2718
            if docName is not None:
2719
                sql += " where PNID_NO = '{}'".format(docName)
2720

    
2721
            cursor.execute(sql)
2722
            rows = cursor.fetchall()
2723
            for row in rows:
2724
                data = []
2725
                for index in range(len(cursor.description)): 
2726
                    data.append(row[index])
2727
                result.append(data)
2728
        # Catch the exception
2729
        except Exception as ex:
2730
            # Roll back any change if something goes wrong
2731
            conn.rollback()
2732
            from App import App
2733

    
2734
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2735
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2736
        finally:
2737
            # Close the db connection
2738
            conn.close()
2739

    
2740
        return result
2741

    
2742
    '''
2743
        @brief      get Note data list
2744
        @author     kyouho
2745
        @date       2018.10.10
2746
    '''
2747
    def getNoteDataList(self, docName = None):
2748
        result = []
2749
        try:
2750
            # Creates or opens a file called mydb with a SQLite3 DB
2751
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2752
            conn = sqlite3.connect(dbPath)
2753
            # Get a cursor object
2754
            cursor = conn.cursor()
2755

    
2756
            sql = 'select UID, NOTE_NO, DESCRIPTION, PNID_NO from NOTE_DATA_LIST'
2757
            if docName is not None:
2758
                sql += " where PNID_NO = '{}'".format(docName)
2759

    
2760
            sql += ' ORDER BY NOTE_NO ASC'
2761
            cursor.execute(sql)
2762
            rows = cursor.fetchall()
2763
            for row in rows:
2764
                data = []
2765
                for index in range(len(cursor.description)): 
2766
                    data.append(row[index])
2767
                result.append(data)
2768
        # Catch the exception
2769
        except Exception as ex:
2770
            # Roll back any change if something goes wrong
2771
            conn.rollback()
2772
            from App import App
2773

    
2774
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2775
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2776
        finally:
2777
            # Close the db connection
2778
            conn.close()
2779

    
2780
        return result
2781

    
2782
    def saveToDatabase(self, items):
2783
        """ save given items to database """
2784
        try:
2785
            # Creates or opens a file called mydb with a SQLite3 DB
2786
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2787
            conn = sqlite3.connect(dbPath, isolation_level=None)
2788
            # Get a cursor object
2789
            cursor = conn.cursor()
2790

    
2791
            # delete all datas of current drawing
2792
            pidNo = self.activeDrawing.name
2793
            sql = "delete from LINE_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2794
            cursor.execute(sql)
2795
            sql = "delete from EQUIPMENT_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2796
            cursor.execute(sql)
2797
            sql = "delete from VALVE_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2798
            cursor.execute(sql)
2799
            sql = "delete from INSTRUMENT_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2800
            cursor.execute(sql)
2801
            sql = "delete from NOTE_DATA_LIST where PNID_NO = '{}'".format(pidNo)
2802
            cursor.execute(sql)
2803
            sql = "delete from TitleBlockValues where Drawings_UID = '{}'".format(pidNo)
2804
            cursor.execute(sql)
2805

    
2806
            # delete ports
2807
            sql = "delete from Ports where Components_UID in (select UID from Components where Drawings_UID = (select UID from Drawings where Name= '{}'))".format(pidNo)
2808
            cursor.execute(sql)
2809

    
2810
            # delete Attributes
2811
            sql = "delete from Attributes where Components_UID in (select UID from Components where Drawings_UID = (select UID from Drawings where Name= '{}'))".format(pidNo)
2812
            cursor.execute(sql)
2813

    
2814
            # delete Components 
2815
            sql = "delete from Components where Drawings_UID = (select UID from Drawings where Name= '{}')".format(pidNo)
2816
            cursor.execute(sql)
2817

    
2818
            # delete Vendor Package
2819
            sql = "delete from VendorPackages where Drawings_UID = '{}'".format(pidNo)
2820
            cursor.execute(sql)
2821

    
2822
            for item in items:
2823
                sql = item.toSql()
2824
                if type(sql) is list:
2825
                    for item in sql:
2826
                        if item is not None and 2 == len(item):
2827
                            cursor.execute(item[0], item[1])
2828
                else:
2829
                    if sql is not None and 2 == len(sql):
2830
                        cursor.execute(sql[0], sql[1])
2831

    
2832
            conn.commit()
2833
        # Catch the exception
2834
        except Exception as ex:
2835
            from App import App
2836
            # Roll back any change if something goes wrong
2837
            conn.rollback()
2838

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

    
2846
    '''
2847
        @brief      set equipment data list
2848
        @author     humkyung
2849
        @date       2018.05.03
2850
    '''
2851
    def setEquipmentDataList(self, dataList):
2852
        try:
2853
            # Creates or opens a file called mydb with a SQLite3 DB
2854
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2855
            conn = sqlite3.connect(dbPath)
2856
            # Get a cursor object
2857
            cursor = conn.cursor()
2858

    
2859
            for data in dataList:
2860
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2861
                param = tuple(data)
2862
                cursor.execute(sql, param)
2863
            conn.commit()
2864
        # Catch the exception
2865
        except Exception as ex:
2866
            # Roll back any change if something goes wrong
2867
            conn.rollback()
2868
            from App import App
2869

    
2870
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2871
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2872
        finally:
2873
            # Close the db connection
2874
            conn.close()
2875

    
2876
    '''
2877
        @brief      set instrumnet data list
2878
        @author     kyoyho
2879
        @date       2018.08.14
2880
    '''
2881
    def setInstrumentDataList(self, dataList):
2882
        try:
2883
            # Creates or opens a file called mydb with a SQLite3 DB
2884
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2885
            conn = sqlite3.connect(dbPath)
2886
            # Get a cursor object
2887
            cursor = conn.cursor()
2888

    
2889
            for data in dataList:
2890
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2891
                param = tuple(data)
2892
                cursor.execute(sql, param)
2893
            conn.commit()
2894

    
2895
        # Catch the exception
2896
        except Exception as ex:
2897
            # Roll back any change if something goes wrong
2898
            conn.rollback()
2899
            from App import App
2900

    
2901
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2902
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2903
        finally:
2904
            # Close the db connection
2905
            conn.close()
2906

    
2907
    '''
2908
        @brief      set Note data list
2909
        @author     kyoyho
2910
        @date       2018.10.10
2911
    '''
2912
    def setNoteDataList(self, dataList):
2913
        try:
2914
            # Creates or opens a file called mydb with a SQLite3 DB
2915
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2916
            conn = sqlite3.connect(dbPath)
2917
            # Get a cursor object
2918
            cursor = conn.cursor()
2919

    
2920
            for data in dataList:
2921
                sql = "insert or replace into NOTE_DATA_LIST(UID, NOTE_NO, DESCRIPTION, PNID_NO) values(?, ?, ?, ?)"
2922
                param = tuple(data)
2923
                cursor.execute(sql, param)
2924
            conn.commit()
2925

    
2926
        # Catch the exception
2927
        except Exception as ex:
2928
            # Roll back any change if something goes wrong
2929
            conn.rollback()
2930
            from App import App
2931

    
2932
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2933
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2934
        finally:
2935
            # Close the db connection
2936
            conn.close()
2937

    
2938
    def getDrawings(self):
2939
        """
2940
        @brief      get drawings
2941
        @author     humkyung
2942
        @date       2018.11.03
2943
        """
2944

    
2945
        res = []
2946
        try:
2947
            xmlList = [xml.replace('.xml', '') for xml in os.listdir(AppDocData.instance().getCurrentProject().getTempPath()) if xml.find('.xml') is not -1]
2948

    
2949
            # Creates or opens a file called mydb with a SQLite3 DB
2950
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2951
            conn = sqlite3.connect(dbPath)
2952
            # Get a cursor object
2953
            cursor = conn.cursor()
2954

    
2955
            sql = 'select UID,[NAME],[DATETIME] from Drawings'
2956
            cursor.execute(sql)
2957
            rows = cursor.fetchall()
2958
            for row in rows:
2959
                for xml in xmlList:
2960
                    if row[1].replace('.png', '') == xml:
2961
                        res.append([row[0], row[1], row[2]])
2962
                        break
2963

    
2964
        # Catch the exception
2965
        except Exception as ex:
2966
            # Roll back any change if something goes wrong
2967
            conn.rollback()
2968
            from App import App
2969

    
2970
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2971
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2972
        finally:
2973
            # Close the db connection
2974
            conn.close()
2975

    
2976
        return res
2977

    
2978
    def saveDrawings(self, drawings):
2979
        """
2980
        @brief      save drawings
2981
        @author     humkyung
2982
        @date       2018.11.03
2983
        """
2984

    
2985
        import uuid
2986

    
2987
        try:
2988
            # Creates or opens a file called mydb with a SQLite3 DB
2989
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2990
            conn = sqlite3.connect(dbPath)
2991
            # Get a cursor object
2992
            cursor = conn.cursor()
2993

    
2994
            for drawing in drawings:
2995
                if not drawing[0]:
2996
                    sql = 'insert or replace into Drawings(UID, [NAME], [DATETIME]) values(?, ?, ?)'
2997
                    param = tuple([str(uuid.uuid4()), drawing[1], ''])
2998
                else:
2999
                    sql = 'insert or replace into Drawings(UID, [NAME], [DATETIME]) values(?, ?, ?)'
3000
                    param = tuple(drawing)
3001

    
3002
                cursor.execute(sql, param)
3003
            conn.commit()
3004

    
3005
        # Catch the exception
3006
        except Exception as ex:
3007
            # Roll back any change if something goes wrong
3008
            conn.rollback()
3009
            from App import App
3010

    
3011
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3012
            App.mainWnd().addMessage.emit(MessageType.Error, message)
3013
        finally:
3014
            # Close the db connection
3015
            conn.close()
3016

    
3017
    '''
3018
        @brief  get IsOriginDetect ComboBox Items
3019
    '''
3020
    def getIsOriginDetectComboBoxItems(self):
3021
        return [("원본 도면", 0), ("텍스트 제거 도면", 1)]
3022

    
3023
    '''
3024
        @brief  get IsOriginDetect ComboBox Items
3025
    '''
3026
    def getOcrOptionComboBoxItems(self):
3027
        return [("OCR 미적용", 0), ("일반 심볼", 1), ("Instrument 계통", 2)]
3028
    
3029
    '''
3030
        @brief      Return Symbol Type Items
3031
        @author     Jeongwoo
3032
        @date       18.04.20
3033
        @history    18.05.08    Jeongwoo type index changed
3034
    '''
3035
    def getSymbolTypeList(self):
3036
        symbolTypeList = []
3037

    
3038
        try:
3039
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3040

    
3041
            conn = sqlite3.connect(dbPath)
3042
            cursor = conn.cursor()
3043
            sql = 'SELECT * FROM SymbolType ORDER BY type ASC'
3044
            try:
3045
                cursor.execute(sql)
3046
                rows = cursor.fetchall()
3047
                for row in rows:
3048
                    symbolTypeList.append((row[0], row[1], row[2])) # UID, category, type
3049
            except Exception as ex:
3050
                from App import App
3051

    
3052
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3053
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3054
        finally:
3055
            conn.close()
3056

    
3057
        return symbolTypeList
3058

    
3059
    '''
3060
        @brief      Get Symbol Category by Symbol Type
3061
        @author     Jeongwoo
3062
        @date       2018.05.09
3063
    '''
3064
    def getSymbolCategoryByType(self, type):
3065
        category = None
3066
        try:
3067
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
3068
            conn = sqlite3.connect(dbPath)
3069
            cursor = conn.cursor()
3070
            sql = 'SELECT Category FROM SymbolType WHERE type = "' + type + '"'
3071
            cursor.execute(sql)
3072
            rows = cursor.fetchall()
3073
            if rows is not None and len(rows) > 0:
3074
                category = rows[0][0]
3075
        except Exception as ex:
3076
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
3077
        finally:
3078
            conn.close()
3079

    
3080
        return category
3081

    
3082
    '''
3083
        @brief      Check Symbol Type is included in 'Equipment' Category
3084
        @author     Jeongwoo
3085
        @date       2018.05.09
3086
    '''
3087
    def isEquipmentType(self, type):
3088
        category = self.getSymbolCategoryByType(type)
3089
        return (category is not None and category == 'Equipment')
3090

    
3091
    '''
3092
        @brief      Return Symbol Type Items with "None"
3093
        @author     Jeongwoo
3094
        @date       18.04.06
3095
        @history    Seperate SymbolTypeList and "None"
3096
    '''
3097
    def getSymbolTypeComboBoxItems(self):
3098
        symbolTypeList = self.getSymbolTypeList()
3099
        symbolTypeList.insert(0, ('None', 'None', 'None'))
3100

    
3101
        return symbolTypeList
3102

    
3103
    '''
3104
        @brief  get Base Symbol ComboBox Items
3105
    '''
3106
    def getBaseSymbolComboBoxItems(self, type = None):
3107
        bsymbolNameList = self.getSymbolNameListByType(type)
3108
        bsymbolNameList.sort()
3109
        bsymbolNameList.insert(0, "None")
3110
        return bsymbolNameList
3111

    
3112
    '''
3113
        @brief  get Additional Symbol ComboBox Items
3114
    '''
3115
    def getAdditionalSymbolComboBoxItems(self):
3116
        asymbolNameList = self.getSymbolNameList()
3117
        asymbolNameList.sort()
3118
        asymbolNameList.insert(0, "None")
3119
        return asymbolNameList
3120

    
3121
    '''
3122
        @brief  get Additional Symbol's default direction ComboBox Items
3123
    '''
3124
    def getDefaultSymbolDirectionComboBoxItems(self):
3125
        return [("UP", 0), ("DOWN", 2), ("LEFT", 3), ("RIGHT", 1)]
3126
    
3127
    '''
3128
        @brief  getter of activeDrawing
3129
        @author humkyung
3130
        @date   2018.07.07
3131
    '''
3132
    @property
3133
    def activeDrawing(self):
3134
        return self._activeDrawing
3135

    
3136
    '''
3137
        @brief  setter of activeDrawing
3138
        @author humkyung
3139
        @date   2018.07.07
3140
    '''
3141
    @activeDrawing.setter
3142
    def activeDrawing(self, value):
3143
        self._activeDrawing = value
3144

    
3145
    def getColNames(self, table):
3146
        """
3147
        return column names of given table and attribute names if tabe is VALVE_DATA_LIST or EQUIPMET_DATA_LIST
3148
        """
3149
        res = None
3150
        try:
3151
            # Creates or opens a file called mydb with a SQLite3 DB
3152
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3153
            conn = sqlite3.connect(dbPath)
3154
            cursor = conn.execute('select * from {}'.format(table))
3155
            res = [col_name[0] for col_name in cursor.description]
3156

    
3157
            if table == 'EQUIPMET_DATA_LIST' or table == 'VALVE_DATA_LIST':
3158
                sql = 'select distinct c.Attribute from {} a left join Attributes b on a.uid=b.Components_UID ' \
3159
                                                            'left join SymbolAttribute c on b.SymbolAttribute_UID=c.UID where c.Attribute is not NULL'.format(table)
3160
                cursor = conn.execute(sql)
3161
                rows = cursor.fetchall()
3162
                for row in rows:
3163
                    res.append(row[0])
3164
        # Catch the exception
3165
        except Exception as ex:
3166
            # Roll back any change if something goes wrong
3167
            conn.rollback()
3168
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
3169
        finally:
3170
            # Close the db connection
3171
            conn.close()
3172

    
3173
        return res
3174
    
3175
    def add_column_into_table(self, table, columnName):
3176
        '''
3177
            @brief  add column into table
3178
            @author euisung
3179
            @date   2019.03.13
3180
        '''
3181
        err = False
3182
        try:
3183
            # Creates or opens a file called mydb with a SQLite3 DB
3184
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3185
            conn = sqlite3.connect(dbPath)
3186
            # Get a cursor object
3187
            cursor = conn.cursor()
3188
            sql = "alter table {} add {}".format(table, columnName)
3189
            cursor.execute(sql)
3190

    
3191
            conn.commit()
3192

    
3193
        # Catch the exception
3194
        except Exception as ex:
3195
            # Roll back any change if something goes wrong
3196
            conn.rollback()
3197
            err = True
3198
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
3199
        finally:
3200
            # Close the db connection
3201
            conn.close()
3202
            return (True if not err else False)
3203

    
3204
    def edit_column_Name_in_table(self, table, columnName, newColName):
3205
        '''
3206
            @brief  edit column into table
3207
            @author euisung
3208
            @date   2019.03.13
3209
        '''
3210
        err = False
3211
        colNames = AppDocData.instance().getColNames(table)
3212

    
3213
        for index in range(len(colNames)):
3214
            if colNames[index] == columnName:
3215
                colNames[index] = newColName
3216
                break
3217

    
3218
        try:
3219
            # Creates or opens a file called mydb with a SQLite3 DB
3220
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3221
            conn = sqlite3.connect(dbPath)
3222
            # Get a cursor object
3223
            cursor = conn.cursor()
3224
            sql = "ALTER TABLE {} RENAME TO {}".format(table, table + '_orig')
3225
            cursor.execute(sql)
3226
            value = []
3227
            for colName in colNames:
3228
                value.append(colName + ' TEXT')
3229
            sql = "CREATE TABLE {}({}, CONSTRAINT '{}_PK' PRIMARY KEY('UID'))".format(table, ','.join(value), table)
3230
            cursor.execute(sql)
3231
            sql = "INSERT INTO {} SELECT * FROM {}".format(table, table + '_orig')
3232
            cursor.execute(sql)
3233
            sql = "DROP TABLE {}".format(table + '_orig')
3234
            cursor.execute(sql)
3235

    
3236
            conn.commit()
3237

    
3238
        # Catch the exception
3239
        except Exception as ex:
3240
            # Roll back any change if something goes wrong
3241
            conn.rollback()
3242
            err = True
3243
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
3244
        finally:
3245
            # Close the db connection
3246
            conn.close()
3247
            return (True if not err else False)
3248

    
3249
    '''
3250
        @brief  getter of OCRData
3251
        @author humkyung
3252
        @date   2018.11.19
3253
    '''
3254
    @property
3255
    def OCRData(self):
3256
        if self._OCRData is None:
3257
            configs = self.getConfigs('Text Recognition', 'OCR Data')
3258
            self._OCRData = configs[0].value if 1 == len(configs) else 'eng'
3259

    
3260
        return self._OCRData
3261

    
3262
    '''
3263
        @brief  setter of OCRData
3264
        @author humkyung
3265
        @date   2018.11.19
3266
    '''
3267
    @OCRData.setter
3268
    def OCRData(self, value):
3269
        self._OCRData = value
클립보드 이미지 추가 (최대 크기: 500 MB)