프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / DTI_PID / AppDocData.py @ a655d25c

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

1
# coding: utf-8
2
"""
3
    This is document data(SDI) class
4
"""
5
import sys
6
import os
7
import sqlite3
8
import datetime
9
from 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
from enum import Enum
22

    
23
from SingletonInstance import SingletonInstane
24
import Project
25
import SymbolBase
26
import symbol
27
from EquipmentData import EquipmentData
28

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

    
49
    def getQImageOnRect(self, rect = None):
50
        image = ImageQt(self.getPyImageOnRect(rect))
51
        return image.convertToFormat(QImage.Format_RGBA8888)
52

    
53
class Config:
54
    def __init__(self, section, key, value):
55
        self.section = section
56
        self.key = key
57
        self.value = value
58

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

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

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

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

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

    
103
        self._areas = []
104
        self.equipments = []
105
        self.lineNos = []
106
        self.lines = []
107
        self.texts = []
108
        self.symbols = []
109
        self._colors = None
110
        self._lineTypes = None
111
        self._lineTypeConfigs = None
112
        self._activeDrawing = None
113
        self._hmbTable = None
114

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

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

    
139
    '''
140
        @brief      Get DB file path in ProgramData
141
        @author     Jeongwoo
142
        @date       2018.06.27
143
        @history    2018.06.29  Jeongwoo    Change method to get template db path
144
    '''
145
    def getTemplateDbPath(self):
146
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
147
        templateDbPath = os.path.join(path, 'Template.db')
148
        return templateDbPath
149

    
150
    '''
151
        @brief  getter of colors 
152
        @author humkyung
153
        @date   2018.06.18
154
    '''
155
    @property
156
    def colors(self):
157
        if self._colors is None:
158
            self._colors = []
159
            try:
160
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath() , 'ITI_PID.db')
161

    
162
                conn = sqlite3.connect(dbPath)
163
                cursor = conn.cursor()
164
                sql = 'SELECT UID,RED,GREEN,BLUE FROM Colors'
165
                cursor.execute(sql)
166
                rows = cursor.fetchall()
167
                for row in rows:
168
                    self._colors.append(Color(int(row[0]), int(row[1]), int(row[2]), int(row[3])))
169
            # Catch the exception
170
            except Exception as ex:
171
                # Roll back any change if something goes wrong
172
                conn.rollback()
173

    
174
                from App import App 
175
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
176
                App.mainWnd().addMessage.emit(MessageType.Error, message)
177
            finally:
178
                conn.close()
179

    
180
        return self._colors
181

    
182
    '''
183
        @brief  setter of colors
184
        @author humkyung
185
        @date   2018.06.18
186
    '''
187
    @colors.setter
188
    def colors(self, value):
189
        self._colors = value
190

    
191
    '''
192
        @brief      set image file path
193
        @author     humkyung
194
        @date       2018.07.30
195
    '''
196
    def setImgFilePath(self, path):
197
        self._imgFilePath = path
198
        self.imgName = os.path.splitext(os.path.basename(self._imgFilePath))[0]
199

    
200
    '''
201
        @brief      getter of imgSrc
202
        @author     humkyung
203
        @date       2018.07.30
204
    '''
205
    @property
206
    def imgSrc(self):
207
        import cv2
208

    
209
        if self._imgSrc is None and self._imgFilePath is not None and os.path.isfile(self._imgFilePath):
210
            self._imgSrc = cv2.cvtColor(cv2.imread(self._imgFilePath), cv2.COLOR_BGR2GRAY)
211
            blur = cv2.GaussianBlur(self._imgSrc , (5,5),0)
212
            self._imgSrc = cv2.threshold(self._imgSrc , 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
213
        
214
        return self._imgSrc
215

    
216
    '''
217
        @brief      setter of imgSrc
218
        @author     humkyung
219
        @date       2018.07.30
220
    '''
221
    @imgSrc.setter
222
    def imgSrc(self, value):
223
        self._imgSrc = value
224

    
225
    '''
226
        @brief      reset imgSrc
227
        @author     humkyung
228
        @date       2018.07.30
229
    '''
230
    def resetImgSrc(self):
231
        self._imgSrc = None
232

    
233
    '''
234
        @brief  getter of line type configs
235
        @author humkyung
236
        @date   2018.06.28
237
    '''
238
    @property
239
    def lineTypeConfigs(self):
240
        from PyQt5.QtCore import Qt
241

    
242
        if self._lineTypeConfigs is None:
243
            self._lineTypeConfigs = []
244

    
245
            styleMap = [('SolidLine', Qt.SolidLine), ('DashLine', Qt.DashLine), ('DotLine', Qt.DotLine), ('DashDotLine', Qt.DashDotLine), 
246
                ('DashDotDotLine', Qt.DashDotDotLine), ('CustomDashLine', Qt.CustomDashLine)]
247

    
248
            configs = self.getConfigs('LineTypes')
249
            for config in configs:
250
                width, _style = config.value.split(',')
251
                matches = [param for param in styleMap if param[0] == _style]
252
                style = matches[0][1] if matches else Qt.SolidLine
253
                self._lineTypeConfigs.append((config.key, int(width), style))
254
        
255
        return self._lineTypeConfigs
256

    
257
    '''
258
        @brief  setter of line type configs
259
        @author humkyung
260
        @date   2018.06.28
261
    '''
262
    @lineTypeConfigs.setter
263
    def lineTypeConfigs(self, value):
264
        self._lineTypeConfigs = value
265

    
266
    '''
267
        @brief      getter of hmb table
268
        @author     humkyung
269
        @date       2018.07.16
270
    '''
271
    @property
272
    def hmbTable(self):
273
        from HMBTable import HMBTable
274

    
275
        if self._hmbTable is None:
276
            self._hmbTable = HMBTable()
277
            self._hmbTable.loadData()
278
        
279
        return self._hmbTable
280

    
281
    '''
282
        @brief      setter of hmb table
283
        @author     humkyung
284
        @date       2018.07.16
285
    '''
286
    @hmbTable.setter
287
    def hmbTable(self, value):
288
        self._hmbTable = value
289

    
290
    '''
291
        @brief  get line type config of given line type
292
        @author humkyung
293
        @date   2018.06.28
294
    '''
295
    def getLineTypeConfig(self, lineType):
296
        from PyQt5.QtCore import Qt
297

    
298
        matches = [config for config in self.lineTypeConfigs if config[0] == lineType]
299
        return matches[0] if matches else (lineType, 5, Qt.SolidLine)        
300

    
301
    def setCurrentPidSource(self, image):
302
        self.imgWidth, self.imgHeight = image.size
303

    
304
        self.currentPidSource = Source(image)
305

    
306
    def getCurrentPidSource(self):
307
        return self.currentPidSource
308

    
309
    '''
310
        @brief      Check if Exist data or not, Moved from SG_DbHelper
311
        @author     Jeongwoo
312
        @date       2018.05.03
313
    '''
314
    def isExistData(self, fieldName, data):
315
        rows = None
316
        try:
317
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
318

    
319
            conn = sqlite3.connect(dbPath)
320
            cursor = conn.cursor()
321
            sql = ""
322
            if isinstance(data, str):
323
                sql = "SELECT * FROM Symbol WHERE " + fieldName + " = '"+ data +"'"
324
            else:
325
                sql = "SELECT * FROM Symbol WHERE " + fieldName + " = "+ str(data) +""
326
            cursor.execute(sql)
327
            rows = cursor.fetchall()
328
        # Catch the exception
329
        except Exception as ex:
330
            # Roll back any change if something goes wrong
331
            conn.rollback()
332
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
333
        finally:
334
            conn.close()
335
            if rows is not None and len(rows) > 0:
336
                return True
337
            else:
338
                return False
339

    
340
    '''
341
        @brief      Check if exist file name or not, Moved from SG_DbHelper
342
        @author     Jeongwoo
343
        @date       2018.05.03
344
    '''
345
    def isExistFileName(self, name):
346
        rows = None
347
        try:
348
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
349
            conn = sqlite3.connect(dbPath)
350
            cursor = conn.cursor()
351
            sql = "SELECT * FROM Symbol WHERE name = '"+ name +"'"
352
            cursor.execute(sql)
353
            rows = cursor.fetchall()
354
        # Catch the exception
355
        except Exception as ex:
356
            # Roll back any change if something goes wrong
357
            conn.rollback()
358
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
359
        finally:
360
            conn.close()
361
            if rows is not None and len(rows) > 0:
362
                return True
363
            else:
364
                return False
365

    
366
    '''
367
        @brief      Insert new symbol into Symbol Table, Moved from SG_DbHelper
368
        @author     Jeongwoo
369
        @date       2018.05.03
370
    '''
371
    def insertSymbol(self, symbol):
372
        isAdded = False
373
        try:
374
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
375
            conn = sqlite3.connect(dbPath)
376
            
377
            INSERT_SYMBOL_SQL = '''
378
                INSERT INTO Symbol(name, type, threshold, minMatchPoint, isDetectOrigin, rotationCount, ocrOption, isContainChild, originalPoint, connectionPoint, baseSymbol, additionalSymbol, isExceptDetect, hasInstrumentLabel) 
379
                VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
380
            '''
381

    
382
            cursor = conn.cursor()
383
            query = ( symbol.getName(), symbol.getType(), symbol.getThreshold()
384
                           , symbol.getMinMatchCount(), symbol.getIsDetectOnOrigin(), symbol.getRotationCount()
385
                           , symbol.getOcrOption(), symbol.getIsContainChild()
386
                           , symbol.getOriginalPoint(), symbol.getConnectionPoint()
387
                           , symbol.getBaseSymbol(), symbol.getAdditionalSymbol(), symbol.getIsExceptDetect(), symbol.getHasInstrumentLabel())
388
            cursor.execute(INSERT_SYMBOL_SQL, query)
389
            conn.commit()
390
            isAdded = True
391
        # Catch the exception
392
        except Exception as ex:
393
            # Roll back any change if something goes wrong
394
            conn.rollback()
395
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
396
        finally:
397
            conn.close()
398
            return (isAdded, symbol.getType(), symbol.getName(), symbol.getPath())
399

    
400
    '''
401
        @brief      Update symbol in Symbol Table, Moved from SG_DbHelper
402
        @author     Jeongwoo
403
        @date       2018.05.03
404
    '''
405
    def updateSymbol(self, symbol):
406
        isUpdated = False
407
        try:
408
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
409
            conn = sqlite3.connect(dbPath)
410
            
411
            UPDATE_SYMBOL_SQL = '''
412
                UPDATE Symbol
413
                SET
414
                    name = ?, type = ?, threshold = ?, minMatchPoint = ?, isDetectOrigin = ?,
415
                    rotationCount = ?, ocrOption = ?, isContainChild = ?, originalPoint = ?, connectionPoint = ?,
416
                    baseSymbol = ?, additionalSymbol = ?, isExceptDetect = ?, hasInstrumentLabel = ?
417
                WHERE uid = ?
418
            '''
419
            
420
            cursor = conn.cursor()
421
            query = (symbol.getName(), symbol.getType(), symbol.getThreshold()
422
                           , symbol.getMinMatchCount(), symbol.getIsDetectOnOrigin(), symbol.getRotationCount()
423
                           , symbol.getOcrOption(), symbol.getIsContainChild()
424
                           , symbol.getOriginalPoint(), symbol.getConnectionPoint()
425
                           , symbol.getBaseSymbol(), symbol.getAdditionalSymbol(), symbol.getIsExceptDetect(), symbol.getHasInstrumentLabel(), symbol.getUid())
426
            cursor.execute(UPDATE_SYMBOL_SQL, query)
427
            conn.commit()
428
            isUpdated = True
429
        # Catch the exception
430
        except Exception as ex:
431
            # Roll back any change if something goes wrong
432
            conn.rollback()
433
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
434
        finally:
435
            conn.close()
436
            return (isUpdated, symbol.getType(), symbol.getName(), symbol.getPath())
437

    
438
    '''
439
        @brief      Get Detecting Target Symbol List (Field 'isExceptDetect' == False(0))
440
        @author     Jeongwoo
441
        @date       18.04.24
442
        @history    humkyung 2018.06.28 select symbol order by threshold descending
443
    '''
444
    def getTargetSymbolList(self):
445
        targetSymbolList = []
446

    
447
        try:
448
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
449

    
450
            conn = sqlite3.connect(dbPath)
451
            cursor = conn.cursor()
452
            sql = 'SELECT * FROM Symbol WHERE isExceptDetect = 0 order by threshold desc'
453
            try:
454
                cursor.execute(sql)
455
                rows = cursor.fetchall()
456
                for row in rows:
457
                    sym = symbol.SymbolBase(row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11], row[12], row[13], row[14], row[0]) ## uid is last item
458
                    targetSymbolList.append(sym)
459
            except Exception as ex:
460
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
461
        finally:
462
            conn.close()
463

    
464
        return targetSymbolList
465

    
466
    '''
467
        @brief  build application database
468
        @author humkyung
469
        @date   2018.04.20
470
    '''
471
    def buildAppDatabase(self):
472
        try:
473
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
474
            appDatabaseFilePath = os.path.join(path, 'App.db')
475

    
476
            # Creates or opens a file called mydb with a SQLite3 DB
477
            conn = sqlite3.connect(appDatabaseFilePath)
478
            # Get a cursor object
479
            cursor = conn.cursor()
480

    
481
            sqlFiles = ['App.Configuration.sql', 'App.Styles.sql']
482
            for sqlFile in sqlFiles:
483
                filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', sqlFile)
484
                try:
485
                    file = QFile(filePath)
486
                    file.open(QFile.ReadOnly)
487
                    sql = file.readAll()
488
                    sql = str(sql, encoding='utf8')
489
                    cursor.executescript(sql)
490
                finally:
491
                    file.close()
492
            conn.commit()
493
        # Catch the exception
494
        except Exception as ex:
495
            # Roll back any change if something goes wrong
496
            conn.rollback()
497
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
498
        finally:
499
            # Close the db connection
500
            conn.close()
501

    
502
    '''
503
        @brief  load app style
504
        @author humkyung
505
        @date   2018.04.20
506
    '''
507
    def loadAppStyle(self):
508
        style = 'Fusion'
509

    
510
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
511
        if not os.path.exists(path): os.makedirs(path)
512

    
513
        self.buildAppDatabase()
514
        try:
515
            appDatabaseFilePath = os.path.join(path, 'App.db')
516
            # Creates or opens a file called mydb with a SQLite3 DB
517
            conn = sqlite3.connect(appDatabaseFilePath)
518
            # Get a cursor object
519
            cursor = conn.cursor()
520

    
521
            sql = "select Value from Configuration where Section='App' and Key='Style'" 
522
            cursor.execute(sql)
523
            rows = cursor.fetchall()
524
            style = rows[0][0] if 1 == len(rows) else 'Fusion'
525
        # Catch the exception
526
        except Exception as ex:
527
            # Roll back any change if something goes wrong
528
            conn.rollback()
529
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
530
        finally:
531
            # Close the db connection
532
            conn.close()
533

    
534
        return style
535

    
536
    '''
537
        @brief  load app styles and then return a list
538
        @author humkyung
539
        @date   2018.04.20
540
    '''
541
    def loadAppStyles(self):
542
        styles = []
543

    
544
        try:
545
            self.buildAppDatabase()
546

    
547
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
548
            appDatabaseFilePath = os.path.join(path, 'App.db')
549

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

    
555
            sql = 'select UID,Value from Styles'
556
            cursor.execute(sql)
557
            rows = cursor.fetchall()
558
            for row in rows: styles.append(row[1])
559
            if 0 == len(rows): rows.append('fusion')
560
        # Catch the exception
561
        except Exception as ex:
562
            # Roll back any change if something goes wrong
563
            conn.rollback()
564
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
565
        finally:
566
            # Close the db connection
567
            conn.close()
568

    
569
        return styles
570

    
571
    '''
572
        @brief  Set current Project
573
        @history    2018.06.27  Jeongwoo    If DB file is not, copy DB file from ProgramData
574
    '''
575
    def setCurrentProject(self, project):
576
        self.project = project
577
        self.makeChildDir()
578
        try:
579
            # Creates or opens a file called mydb with a SQLite3 DB
580
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath() , "ITI_PID.db")
581
            
582
            if not os.path.isfile(dbPath):
583
                templatePath = self.getTemplateDbPath()
584
                templateFile = QFile(templatePath)
585
                templateFile.copy(dbPath)
586
            else:
587
                try:
588
                    conn = sqlite3.connect(dbPath)
589
                    # Get a cursor object
590
                    cursor = conn.cursor()
591

    
592
                    fileNames = os.listdir(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts'))
593
                    for fileName in fileNames:
594
                        if fileName.endswith(".sql") and (1 == len(os.path.splitext(fileName)[0].split('.'))):
595
                            try:
596
                                file = QFile(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', fileName))
597
                                file.open(QFile.ReadOnly)
598
                                sql = file.readAll()
599
                                sql = str(sql, encoding='utf8')
600
                                cursor.executescript(sql)
601
                            finally:
602
                                file.close()
603
                    conn.commit()
604
                except Exception as ex:
605
                    print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
606
                finally:
607
                    conn.close()
608
        # Catch the exception
609
        except Exception as ex:
610
            # Roll back any change if something goes wrong
611
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
612
        finally:
613
            pass
614

    
615
    '''
616
        @brief      Make Directory
617
        @author     Jeongwoo
618
        @date       18.05.08
619
        @history    humkyung 2018.06.19 make 'Tile' directory
620
                    humkyung 2018.07.09 make drawing folder if not exists
621
    '''
622
    def makeChildDir(self):
623
        project = AppDocData.instance().getCurrentProject()
624
        dbDir = project.getDbFilePath()
625
        if not os.path.exists(dbDir):
626
            os.makedirs(dbDir)
627
        imgDir = project.getImageFilePath()
628
        if not os.path.exists(imgDir):
629
            os.makedirs(imgDir)
630
        svgDir = project.getSvgFilePath()
631
        if not os.path.exists(svgDir):
632
            os.makedirs(svgDir)
633
        outputDir = project.getOutputPath()
634
        if not os.path.exists(outputDir):
635
            os.makedirs(outputDir)
636
        tempDir = project.getTempPath()
637
        if not os.path.exists(tempDir):
638
            os.makedirs(tempDir)
639
        drawingPath = project.getDrawingFilePath()
640
        if not os.path.exists(drawingPath):
641
            os.makedirs(drawingPath)
642
        
643
        path = os.path.join(tempDir, 'Tile')
644
        if not os.path.exists(path):
645
            os.makedirs(path)
646

    
647
    '''
648
        @brief  Get current Project
649
    '''
650
    def getCurrentProject(self):
651
        return self.project
652

    
653
    '''
654
        @brief      return project database path
655
        @history    humkyung 2018.04.19 return Project.db in Program Data folder instead of PROJECT_DB_PATH variable
656
    '''
657
    def getPrjDatabasePath(self):
658
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
659
        if not os.path.exists(path): os.makedirs(path)
660

    
661
        prjDatabaseFilePath = os.path.join(path, 'Project.db')
662
        try:
663
            # Creates or opens a file called mydb with a SQLite3 DB
664
            conn = sqlite3.connect(prjDatabaseFilePath)
665
            # Get a cursor object
666
            cursor = conn.cursor()
667

    
668
            filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', 'Project.Projects.sql')
669
            try:
670
                file = QFile(filePath)
671
                file.open(QFile.ReadOnly)
672
                sql = file.readAll()
673
                sql = str(sql, encoding='utf8')
674
                cursor.executescript(sql)
675
            finally:
676
                file.close()
677
            conn.commit()
678
        # Catch the exception
679
        except Exception as ex:
680
            # Roll back any change if something goes wrong
681
            conn.rollback()
682
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
683
        finally:
684
            # Close the db connection
685
            conn.close()
686
        
687
        return prjDatabaseFilePath
688

    
689
    '''
690
        @brief  return line properties
691
        @author humkyung
692
        @date   2018.04.09
693
    '''
694
    def getLineProperties(self):
695
        res = []
696
        try:
697
            # Creates or opens a file called mydb with a SQLite3 DB
698
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
699
            db = sqlite3.connect(dbPath)
700
            # Get a cursor object
701
            cursor = db.cursor()
702

    
703
            sql = "select UID, Name, DisplayName, Type, LimitNumber, [index] from LineProperties order by [index]" 
704
            cursor.execute(sql)
705
            rows = cursor.fetchall()
706
            for row in rows:
707
                res.append((row[0], row[1], row[2], row[3], row[4], row[5]))
708
        # Catch the exception
709
        except Exception as ex:
710
            # Roll back any change if something goes wrong
711
            db.rollback()
712
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
713
        finally:
714
            # Close the db connection
715
            db.close()
716

    
717
        return res
718

    
719
    '''
720
        @brief  return line properties
721
        @author humkyung
722
        @date   2018.04.09
723
    '''
724
    def getLinePropertiesByUID(self, UID):
725
        res = []
726
        try:
727
            # Creates or opens a file called mydb with a SQLite3 DB
728
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
729
            db = sqlite3.connect(dbPath)
730
            # Get a cursor object
731
            cursor = db.cursor()
732

    
733
            sql = "select UID, Name, DisplayName, Type, LimitNumber, [index] from LineProperties where uid = '{}'".format(UID)
734
            cursor.execute(sql)
735
            rows = cursor.fetchall()
736
            for row in rows:
737
                res.append((row[0], row[1], row[2], row[3], row[4], row[5]))
738
        # Catch the exception
739
        except Exception as ex:
740
            # Roll back any change if something goes wrong
741
            db.rollback()
742
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
743
        finally:
744
            # Close the db connection
745
            db.close()
746

    
747
        return res
748

    
749
    '''
750
        @brief  return line types 
751
        @author humkyung
752
        @date   2018.06.27
753
    '''
754
    def getLineTypes(self):
755
        res = []
756
        try:
757
            # Creates or opens a file called mydb with a SQLite3 DB
758
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
759
            db = sqlite3.connect(dbPath)
760
            # Get a cursor object
761
            cursor = db.cursor()
762

    
763
            sql = "select Name from LineTypes order by Name" 
764
            cursor.execute(sql)
765
            rows = cursor.fetchall()
766
            for row in rows:
767
                res.append(row[0])
768
        # Catch the exception
769
        except Exception as ex:
770
            # Roll back any change if something goes wrong
771
            db.rollback()
772
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
773
        finally:
774
            # Close the db connection
775
            db.close()
776

    
777
        return res
778

    
779
    '''
780
        @brief      Insert New Project Info
781
        @author     Jeongwoo
782
        @date       2018.04.06
783
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
784
    '''
785
    def insertProjectInfo(self, dir):
786
        try:
787
            prjDatabaseFilePath = self.getPrjDatabasePath()
788
            conn = sqlite3.connect(prjDatabaseFilePath)
789
            folderName = dir.split('/')[-1]
790
            if folderName:
791
                nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
792
                sql = "INSERT INTO Projects(Name, Path, CreatedDate, UpdatedDate) VALUES('" + folderName + "', '" + dir + "', '" + nowDate + "', '" + nowDate + "')"
793
                cur = conn.cursor()
794
                cur.execute(sql)
795
                conn.commit()
796
            else:
797
                print("Empty folder name")
798
        except Exception as ex:
799
            # Roll back any change if something goes wrong
800
            conn.rollback()
801
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
802
        finally:
803
            conn.close()
804

    
805
    '''
806
        @brief      Update Project UpdatedDate Field
807
        @author     Jeongwoo
808
        @date       2018.04.06
809
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
810
    '''
811
    def updateProjectUpdatedDate(self, id):
812
        try:
813
            prjDatabaseFilePath = self.getPrjDatabasePath()
814
            conn = sqlite3.connect(prjDatabaseFilePath)
815
            nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
816
            sql = '''
817
                UPDATE Projects
818
                SET UpdatedDate = ?
819
                WHERE Id = ?
820
            '''
821
            cur = conn.cursor()
822
            cur.execute(sql, (nowDate, id))
823
            conn.commit()
824
        except Exception as ex:
825
            # Roll back any change if something goes wrong
826
            conn.rollback()
827
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
828
        finally:
829
            conn.close()
830

    
831
    '''
832
        @brief  get project list from database
833
        @history    humkyung 2018.04.18 add only project which's project exists
834
    '''
835
    def getProjectList(self):
836
        from Project import Project
837

    
838
        projectList = []
839

    
840
        try:
841
            conn = sqlite3.connect(self.getPrjDatabasePath())
842
            cursor = conn.cursor()
843
            sql = 'SELECT id,name,path,createddate,updateddate  FROM Projects ORDER BY UpdatedDate DESC'
844
            try:
845
                cursor.execute(sql)
846
                rows = cursor.fetchall()
847
                for row in rows:
848
                    if os.path.isdir(row[2]):   # check if folder exists
849
                        projectList.append(Project(row[0], row[1], row[2], row[3], row[4]))
850
            except Exception as ex:
851
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
852
        finally:
853
            conn.close()
854

    
855
        return projectList
856

    
857
    '''
858
        @brief  get sliding window size
859
        @author humkyung
860
    '''
861
    def getSlidingWindowSize(self):
862
        res = [10,10]
863
        try:
864
            configs = self.getConfigs('Sliding Window')
865
            for config in configs:
866
                if config.key == 'Width':
867
                    res[0] = int(config.value)
868
                elif config.key == 'Height':
869
                    res[1] = int(config.value)
870
        # Catch the exception
871
        except Exception as ex:
872
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
873
        
874
        return res
875

    
876
    '''
877
        @brief  get line no configuration
878
        @author humkyung
879
        @date   2018.04.16
880
    '''
881
    def getLineNoConfiguration(self):
882
        res = None
883
        try:
884
            # Creates or opens a file called mydb with a SQLite3 DB
885
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
886
            conn = sqlite3.connect(dbPath)
887
            # Get a cursor object
888
            cursor = conn.cursor()
889

    
890
            delimiter = None
891
            sql = "select * from configuration where section='Line No' and key='Delimiter"
892
            cursor.execute(sql)
893
            rows = cursor.fetchall()
894
            if len(rows) == 1:
895
                delimiter = rows[0][2]
896

    
897
            if delimiter is not None:
898
                sql = "select * from configuration where section='Line No' and key='Configuration'"
899
                cursor.execute(sql)
900
                rows = cursor.fetchall()
901
                if len(rows) == 1:
902
                    res = rows[0][2].split(delimiter)
903
        # Catch the exception
904
        except Exception as ex:
905
            # Roll back any change if something goes wrong
906
            conn.rollback()
907
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
908
        finally:
909
            # Close the db connection
910
            conn.close()
911
        
912
        return res
913

    
914
    '''
915
        @brief  get area list
916
        @author humkyung
917
    '''
918
    def getAreaList(self):
919
        from Area import Area
920

    
921
        if len(self._areas) == 0:
922
            try:
923
                # Creates or opens a file called mydb with a SQLite3 DB
924
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
925
                conn = sqlite3.connect(dbPath)
926
                # Get a cursor object
927
                cursor = conn.cursor()
928

    
929
                sql = "select * from configuration where section='Area'"
930
                cursor.execute(sql)
931
                rows = cursor.fetchall()
932
                for row in rows:
933
                    name = row[1]
934
                    area = Area(name)
935
                    area.parse(row[2])
936
                    self._areas.append(area)
937
            # Catch the exception
938
            except Exception as ex:
939
                # Roll back any change if something goes wrong
940
                conn.rollback()
941
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
942
            finally:
943
                # Close the db connection
944
                conn.close()
945
        
946
        return self._areas 
947

    
948
    '''
949
        @brief  get area of given name
950
        @author humkyung
951
        @date   2018.04.07
952
    '''
953
    def getArea(self, name):
954
        areas = self.getAreaList()
955
        matches = [area for area in areas if area.name==name]
956
        if 1 == len(matches): return matches[0]
957

    
958
        return None
959

    
960
    '''
961
        @brief  get configurations
962
        @author humkyung
963
        @date   2018.04.16
964
        @history kyouho 2018.07.09 change query method
965
    '''
966
    def getConfigs(self, section, key=None):
967
        res = []
968

    
969
        try:
970
            # Creates or opens a file called mydb with a SQLite3 DB
971
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
972
            conn = sqlite3.connect(dbPath)
973
            # Get a cursor object
974
            cursor = conn.cursor()
975

    
976
            if key is not None:
977
                sql = "select * from configuration where section=? and key=?"
978
                param = (section, key)
979
            else:
980
                sql = "select * from configuration where section=?"
981
                param = (section,)
982

    
983
            cursor.execute(sql, param)
984
            rows = cursor.fetchall()
985
            for row in rows:
986
                res.append(Config(row[0], row[1], row[2]))
987
        # Catch the exception
988
        except Exception as ex:
989
            # Roll back any change if something goes wrong
990
            conn.rollback()
991
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
992
        finally:
993
            # Close the db connection
994
            conn.close()
995

    
996
        return res
997

    
998
    '''
999
        @brief      save configurations
1000
        @author     humkyung
1001
        @date       2018.04.16
1002
        @history    humkyung 2018.07.03 replace ' with " if value has '
1003
                    kyouho 2018.07.09 change query method
1004
    '''
1005
    def saveConfigs(self, configs):
1006
        try:
1007
            # Creates or opens a file called mydb with a SQLite3 DB
1008
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
1009
            conn = sqlite3.connect(dbPath)
1010
            # Get a cursor object
1011
            cursor = conn.cursor()
1012

    
1013
            for config in configs:
1014
                value = config.value
1015
                if type(value) is str and "'" in value:
1016
                    value = value.replace("'", "''")
1017

    
1018
                sql = "insert or replace into configuration values(?,?,?)"
1019
                param = (config.section, config.key, value)
1020

    
1021
                cursor.execute(sql, param)
1022
            conn.commit()
1023
        # Catch the exception
1024
        except Exception as ex:
1025
            # Roll back any change if something goes wrong
1026
            conn.rollback()
1027
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1028
        finally:
1029
            # Close the db connection
1030
            conn.close()
1031

    
1032
    '''
1033
        @brief  delete configurations
1034
        @author humkyung
1035
        @date   2018.06.29
1036
    '''
1037
    def deleteConfigs(self, section, key=None):
1038
        try:
1039
            # Creates or opens a file called mydb with a SQLite3 DB
1040
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
1041
            conn = sqlite3.connect(dbPath)
1042
            # Get a cursor object
1043
            cursor = conn.cursor()
1044

    
1045
            if key is not None:
1046
                sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
1047
            else:
1048
                sql = "delete from configuration where section='{}'".format(section)
1049
            cursor.execute(sql)
1050

    
1051
            conn.commit()
1052
        # Catch the exception
1053
        except Exception as ex:
1054
            # Roll back any change if something goes wrong
1055
            conn.rollback()
1056
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1057
        finally:
1058
            # Close the db connection
1059
            conn.close()
1060

    
1061
    '''
1062
        @brief      set area list
1063
        @history    humkyung 2018.05.18 round area coordinate and dimension before saving
1064
    '''
1065
    def setAreaList(self, areas):
1066
        for area in areas:
1067
            matches = [x for x in self._areas if x.name==area.name]
1068
            if 1 == len(matches):
1069
                matches[0].x = area.x
1070
                matches[0].y = area.y
1071
                matches[0].width = area.width
1072
                matches[0].height = area.height
1073
            elif 0 == len(matches):
1074
                self._areas.append(area)
1075

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

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

    
1087
            conn.commit()
1088
        # Catch the exception
1089
        except Exception as ex:
1090
            # Roll back any change if something goes wrong
1091
            conn.rollback()
1092
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1093
        finally:
1094
            # Close the db connection
1095
            conn.close()
1096
            
1097
    '''
1098
        @brief  get symbol name list
1099
    '''
1100
    def getSymbolNameList(self):
1101
        symbolNametList = []
1102

    
1103
        try:
1104
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
1105

    
1106
            conn = sqlite3.connect(dbPath)
1107
            cursor = conn.cursor()
1108
            sql = 'SELECT * FROM SymbolName'
1109
            try:
1110
                cursor.execute(sql)
1111
                rows = cursor.fetchall()
1112
                for row in rows:
1113
                    symbolNametList.append(row[2]) # Name String
1114
            except Exception as ex:
1115
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1116
        finally:
1117
            conn.close()
1118

    
1119
        return symbolNametList
1120

    
1121
    '''
1122
        @brief      get symbol name list by symbol Type
1123
        @author     Jeongwoo
1124
        @date       18.04.06
1125
        @history    .
1126
    '''
1127
    def getSymbolNameListByType(self, type):
1128
        symbolNametList = []
1129

    
1130
        try:
1131
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
1132

    
1133
            conn = sqlite3.connect(dbPath)
1134
            cursor = conn.cursor()
1135
            sql = ''
1136
            if type is not None:
1137
                sql = 'SELECT * FROM SymbolName WHERE type = "' + type + '"'
1138
                try:
1139
                    cursor.execute(sql)
1140
                    rows = cursor.fetchall()
1141
                    for row in rows:
1142
                        symbolNametList.append(row[2]) # Name String
1143
                except Exception as ex:
1144
                    print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1145
        finally:
1146
            conn.close()
1147

    
1148
        return symbolNametList
1149

    
1150
    '''
1151
        @brief  delete added symbol data
1152
    '''
1153
    def deleteSymbol(self, fileName):
1154
        ret = False
1155
        try:
1156
            dbPath = self.getCurrentProject().getPath() + "/db/ITI_PID.db"
1157
            conn = sqlite3.connect(dbPath)
1158
            cursor = conn.cursor()
1159
            sql = "DELETE FROM Symbol WHERE name = ?"
1160
            try:
1161
                cursor.execute(sql, (fileName,))
1162
                conn.commit()
1163
                ret = True
1164
            except Exception as ex:
1165
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1166
                ret = False
1167
        finally:
1168
            conn.close()
1169
            return (ret, fileName)
1170
        
1171
    '''
1172
        @brief  get symbol name
1173
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1174
    '''
1175
    def getSymbolByQuery(self, fieldName, param):
1176
        ret = None
1177

    
1178
        try:
1179
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
1180
            conn = sqlite3.connect(dbPath)
1181
            cursor = conn.cursor()
1182
            sql = 'SELECT * FROM Symbol WHERE ' + fieldName + ' = "' + param + '"'
1183
            try:
1184
                cursor.execute(sql)
1185
                rows = cursor.fetchall()
1186
                if rows is not None and len(rows) > 0:
1187
                    symbolTuple = rows[0]
1188
                    ret = symbol.SymbolBase(symbolTuple[1], symbolTuple[2], symbolTuple[3]
1189
                                            , symbolTuple[4], symbolTuple[5], symbolTuple[6], symbolTuple[7], symbolTuple[8]
1190
                                            , symbolTuple[9], symbolTuple[10], symbolTuple[11], symbolTuple[12], symbolTuple[13], symbolTuple[14], symbolTuple[0]) ## uid is last item
1191
                    #ret = symbol.SymbolBase(symbolTuple[1], symbolTuple[2], symbolTuple[3], symbolTuple[4]
1192
                    #                        , symbolTuple[5], symbolTuple[6], symbolTuple[7], symbolTuple[8], symbolTuple[9]
1193
                    #                        , symbolTuple[10], symbolTuple[11], symbolTuple[12], symbolTuple[13], symbolTuple[14], symbolTuple[0]) ## uid is last item
1194
            except Exception as ex:
1195
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1196
        finally:
1197
            conn.close()
1198

    
1199
        return ret
1200

    
1201
    '''
1202
        @brief  get symbol name list
1203
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1204
    '''
1205
    def getSymbolListByQuery(self, fieldName=None, param=None):
1206
        ret = []
1207

    
1208
        try:
1209
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1210
            conn = sqlite3.connect(dbPath)
1211
            cursor = conn.cursor()
1212
            if fieldName is not None and param is not None:
1213
                sql = 'SELECT * FROM Symbol WHERE ' + fieldName + ' = "' + param + '"'
1214
            else:
1215
                sql = 'SELECT * FROM Symbol'
1216
            try:
1217
                cursor.execute(sql)
1218
                rows = cursor.fetchall()
1219
                if rows is not None and len(rows) > 0:
1220
                    for symbolTuple in rows:
1221
                        sym = symbol.SymbolBase(symbolTuple[1], symbolTuple[2], symbolTuple[3], symbolTuple[4]
1222
                                                , symbolTuple[5], symbolTuple[6], symbolTuple[7], symbolTuple[8], symbolTuple[9]
1223
                                                , symbolTuple[10], symbolTuple[11], symbolTuple[12], symbolTuple[13], symbolTuple[14], symbolTuple[0]) ## uid is last item
1224
                        ret.append(sym)
1225
            except Exception as ex:
1226
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1227
        finally:
1228
            conn.close()
1229

    
1230
        return ret
1231

    
1232
    '''
1233
        @brief      get NominalDiameter
1234
        @author     humkyung
1235
        @date       2018.04.20
1236
        @history    humkyung 2018.04.24 read MetricStr column and set size unit
1237
                    kyouho 2018.07.04 forCheckLineNumber get only inch or metric
1238
                    kyouho 2018.07.16 edit query order by code
1239
    '''
1240
    def getNomialPipeSizeData(self, forCheckLineNumber = False, orderStr = "CODE"):
1241
        res = []
1242
        try:
1243
            configs = self.getConfigs('Line No', 'Size Unit')
1244
            sizeUnit = configs[0].value if 1 == len(configs) else 'Metric'
1245

    
1246
            # Creates or opens a file called mydb with a SQLite3 DB
1247
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1248
            conn = sqlite3.connect(dbPath)
1249
            # Get a cursor object
1250
            cursor = conn.cursor()
1251

    
1252
            sql = "select Code,Metric,Inch,InchStr,MetricStr from NominalDiameter ORDER BY {} ASC".format(orderStr)
1253
            cursor.execute(sql)
1254
            rows = cursor.fetchall()
1255
            for row in rows:
1256
                pipeSize = NominalPipeSize(row[0], float(row[1]) if row[1] is not None else None, float(row[2]) if row[2] is not None else None, row[3], row[4])
1257
                pipeSize.sizeUnit = sizeUnit
1258
                if forCheckLineNumber:
1259
                    if sizeUnit == 'Inch' and pipeSize.inchStr:
1260
                        res.append(pipeSize.inchStr)
1261
                    elif sizeUnit == 'Metric' and pipeSize.metricStr:
1262
                        res.append(pipeSize.metricStr)
1263
                else:
1264
                    res.append(pipeSize)
1265
                
1266
        # Catch the exception
1267
        except Exception as ex:
1268
            # Roll back any change if something goes wrong
1269
            conn.rollback()
1270
            
1271
            from App import App 
1272
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1273
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1274
        finally:
1275
            # Close the db connection
1276
            conn.close()
1277

    
1278
        return res
1279

    
1280
    '''
1281
        @brief      insert NominalDiameter table
1282
        @author     kyouho
1283
        @date       2018.07.16
1284
    '''
1285
    def insertNomialPipeSize(self, pipeSizes):
1286
        try:
1287
            # Creates or opens a file called mydb with a SQLite3 DB
1288
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1289
            conn = sqlite3.connect(dbPath)
1290
            # Get a cursor object
1291
            cursor = conn.cursor()
1292
            sql = "INSERT INTO NominalDiameter(Code, Metric, Inch, InchStr, MetricStr) VALUES(?,?,?,?,?)"
1293
            for pipeSize in pipeSizes:
1294
                param = (pipeSize.code, pipeSize.metric, pipeSize.inch, pipeSize.inchStr, pipeSize.metricStr)
1295
                cursor.execute(sql, param)
1296
            conn.commit()
1297
            # Catch the exception
1298
        except Exception as ex:
1299
            # Roll back any change if something goes wrong
1300
            conn.rollback()
1301
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1302
        finally:
1303
            # Close the db connection
1304
            conn.close()
1305

    
1306

    
1307
    '''
1308
        @brief      delete NominalDiameter table
1309
        @author     kyouho
1310
        @date       2018.07.16
1311
    '''
1312
    def deleteNomialPipeSize(self):
1313
        try:
1314
            dbPath = self.getCurrentProject().getPath() + "/db/ITI_PID.db"
1315
            conn = sqlite3.connect(dbPath)
1316
            cursor = conn.cursor()
1317
            sql = "DELETE FROM NominalDiameter"
1318
            try:
1319
                cursor.execute(sql)
1320
                conn.commit()
1321
            except Exception as ex:
1322
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1323
        finally:
1324
            conn.close()
1325
    
1326

    
1327

    
1328

    
1329
    '''
1330
        @brief      convert inch to metric
1331
        @author     kyouho
1332
        @date       2018.07.09
1333
    '''
1334
    def convertInchToMetric(self, inch):
1335
        result = ''
1336
        try:
1337
            # Creates or opens a file called mydb with a SQLite3 DB
1338
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1339
            conn = sqlite3.connect(dbPath)
1340
            # Get a cursor object
1341
            cursor = conn.cursor()
1342
            
1343
            sql = "select MetricStr from NominalDiameter WHERE InchStr = ?"
1344
            param = (inch,)
1345
            cursor.execute(sql, param)
1346
            rows = cursor.fetchall()
1347

    
1348
            if rows:
1349
                result = rows[0][0]
1350
            # Catch the exception
1351
        except Exception as ex:
1352
            # Roll back any change if something goes wrong
1353
            conn.rollback()
1354
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1355
        finally:
1356
            # Close the db connection
1357
            conn.close()
1358

    
1359
        return result
1360

    
1361
    '''
1362
        @brief      get Color MaxUID
1363
        @author     kyouho
1364
        @date       2018.07.03
1365
    '''
1366
    def getMaxColorUID(self):
1367
        result = 0
1368

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

    
1376
            sql = "select MAX(UID) from Colors"
1377
            cursor.execute(sql)
1378
            rows = cursor.fetchall()
1379

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

    
1390
        return result
1391

    
1392
    '''
1393
        @brief      insert Color property
1394
        @author     kyouho
1395
        @date       2018.07.09
1396
    '''
1397
    def setPropertyColor(self, _color):
1398
        try:
1399
            # Creates or opens a file called mydb with a SQLite3 DB
1400
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1401
            conn = sqlite3.connect(dbPath)
1402
            # Get a cursor object
1403
            cursor = conn.cursor()
1404
            sql = "INSERT INTO Colors(UID, RED, GREEN, BLUE, PROPERTY, VALUE) VALUES(?,?,?,?,?,?)"
1405
            param = (_color.index, _color.red, _color.green, _color.blue, _color._property, _color.value)
1406
            cursor.execute(sql, param)
1407
            conn.commit()
1408
            # Catch the exception
1409
        except Exception as ex:
1410
            # Roll back any change if something goes wrong
1411
            conn.rollback()
1412
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1413
        finally:
1414
            # Close the db connection
1415
            conn.close()
1416

    
1417
    '''
1418
        @brief      delete Color property
1419
        @author     kyouho
1420
        @date       2018.07.09
1421
    '''
1422
    def deletePropertyColor(self, property):
1423
        try:
1424
            # Creates or opens a file called mydb with a SQLite3 DB
1425
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1426
            conn = sqlite3.connect(dbPath)
1427
            # Get a cursor object
1428
            cursor = conn.cursor()
1429

    
1430
            sql = "DELETE FROM Colors WHERE PROPERTY = '{}'".format(property)
1431
            cursor.execute(sql)
1432
            conn.commit()
1433
            # Catch the exception
1434
        except Exception as ex:
1435
            # Roll back any change if something goes wrong
1436
            conn.rollback()
1437
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1438
        finally:
1439
            # Close the db connection
1440
            conn.close()
1441

    
1442
    '''
1443
        @brief      get Fluid Code
1444
        @author     kyouho
1445
        @date       2018.07.03
1446
        @history    kyouho 2018.07.04 kyouho 2018.07.04 forCheckLineNumber get only code
1447
    '''
1448
    def getFluidCodeData(self, forCheckLineNumber = False):
1449
        from FluidCodeData import FluidCodeData
1450
        result = []
1451

    
1452
        try:
1453
            # Creates or opens a file called mydb with a SQLite3 DB
1454
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1455
            conn = sqlite3.connect(dbPath)
1456
            # Get a cursor object
1457
            cursor = conn.cursor()
1458

    
1459
            sql = 'select uid, code, description from FluidCode order by length(code) DESC'
1460
            cursor.execute(sql)
1461
            rows = cursor.fetchall()
1462
            for row in rows:
1463
                data = FluidCodeData(row[0], row[1], row[2])
1464
                if forCheckLineNumber:
1465
                    result.append(data.code)
1466
                else:
1467
                    result.append(data)
1468
            # Catch the exception
1469
        except Exception as ex:
1470
            # Roll back any change if something goes wrong
1471
            conn.rollback()
1472
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1473
        finally:
1474
            # Close the db connection
1475
            conn.close()
1476

    
1477
        return result
1478

    
1479
    '''
1480
        @brief      get Symbol Attribute
1481
        @author     kyouho
1482
        @date       2018.07.18
1483
    '''
1484
    def checkAttribute(self, attr):
1485
        try:
1486
            # Creates or opens a file called mydb with a SQLite3 DB
1487
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1488
            conn = sqlite3.connect(dbPath)
1489
            # Get a cursor object
1490
            cursor = conn.cursor()
1491

    
1492
            sql = 'select UID from SymbolAttribute where UID = ?'
1493
            param = (attr,)
1494
            cursor.execute(sql, param)
1495
            rows = cursor.fetchall()
1496
            if len(rows):
1497
                return True
1498
            else:
1499
                return False
1500
            # Catch the exception
1501
        except Exception as ex:
1502
            # Roll back any change if something goes wrong
1503
            conn.rollback()
1504
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1505
        finally:
1506
            # Close the db connection
1507
            conn.close()
1508

    
1509
        return False
1510

    
1511
    '''
1512
        @brief      get Symbol Attribute
1513
        @author     kyouho
1514
        @date       2018.07.18
1515
    '''
1516
    def getSymbolAttribute(self, _type):
1517
        result = []
1518

    
1519
        try:
1520
            # Creates or opens a file called mydb with a SQLite3 DB
1521
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1522
            conn = sqlite3.connect(dbPath)
1523
            # Get a cursor object
1524
            cursor = conn.cursor()
1525

    
1526
            sql = 'select a.UID, a.Attribute, a.DisplayAttribute, a.AttributeType, a.[index] from SymbolAttribute a inner join SymbolType t on a.SymbolType = t.id and t.type = ? order by a.[index]'
1527
            param = (_type,)
1528
            cursor.execute(sql, param)
1529
            rows = cursor.fetchall()
1530
            for row in rows:
1531
                result.append((row[0], row[1], row[2], row[3]))
1532
            # Catch the exception
1533
        except Exception as ex:
1534
            from App import App 
1535

    
1536
            # Roll back any change if something goes wrong
1537
            conn.rollback()
1538

    
1539
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1540
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1541
        finally:
1542
            # Close the db connection
1543
            conn.close()
1544

    
1545
        return result
1546

    
1547
    '''
1548
        @brief      get Symbol Attribute by UID
1549
        @author     kyouho
1550
        @date       2018.08.17
1551
    '''
1552
    def getSymbolAttributeByUID(self, UID):
1553
        result = None
1554

    
1555
        try:
1556
            # Creates or opens a file called mydb with a SQLite3 DB
1557
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1558
            conn = sqlite3.connect(dbPath)
1559
            # Get a cursor object
1560
            cursor = conn.cursor()
1561

    
1562
            sql = 'select Attribute, DisplayAttribute, AttributeType from SymbolAttribute where uid = "{}"'.format(UID)
1563
            cursor.execute(sql)
1564
            rows = cursor.fetchall()
1565
            if len(rows):
1566
                result = (rows[0][0], rows[0][1], rows[0][2])
1567
            # Catch the exception
1568
        except Exception as ex:
1569
            from App import App
1570

    
1571
            # Roll back any change if something goes wrong
1572
            conn.rollback()
1573

    
1574
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1575
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1576
        finally:
1577
            # Close the db connection
1578
            conn.close()
1579

    
1580
        return result
1581

    
1582
    '''
1583
        @brief      save symbol attributes
1584
        @author     humkyung
1585
        @date       2018.08.14
1586
    '''
1587
    def saveSymbolAttributes(self, type, attrs):
1588
        try:
1589
            # Creates or opens a file called mydb with a SQLite3 DB
1590
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1591
            conn = sqlite3.connect(dbPath)
1592
            # Get a cursor object
1593
            cursor = conn.cursor()
1594

    
1595
            sql = 'delete from SymbolAttribute where SymbolType = ?'
1596
            param = (type,)
1597
            cursor.execute(sql, param)
1598

    
1599
            for attr in attrs:
1600
                sql = 'insert into SymbolAttribute(UID, SymbolType, Attribute, DisplayAttribute, AttributeType, [index]) values(?, ?, ?, ?, ?, ?)'
1601
                attr.insert(1, type)
1602
                param = tuple(attr)
1603
                cursor.execute(sql, param)
1604

    
1605
            conn.commit()
1606
            # Catch the exception
1607
        except Exception as ex:
1608
            # Roll back any change if something goes wrong
1609
            conn.rollback()
1610
            
1611
            from App import App 
1612
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1613
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1614
        finally:
1615
            # Close the db connection
1616
            conn.close()
1617

    
1618
    '''
1619
        @brief      save symbol attributes
1620
        @author     humkyung
1621
        @date       2018.08.14
1622
    '''
1623
    def saveLineAttributes(self, attrs):
1624
        try:
1625
            # Creates or opens a file called mydb with a SQLite3 DB
1626
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1627
            conn = sqlite3.connect(dbPath)
1628
            # Get a cursor object
1629
            cursor = conn.cursor()
1630

    
1631
            sql = 'delete from LineProperties'
1632
            cursor.execute(sql)
1633

    
1634
            for attr in attrs:
1635
                sql = 'insert into LineProperties(UID, Name, DisplayName, Type, LimitNumber, [index]) values(?, ?, ?, ?, ?, ?)'
1636
                param = tuple(attr)
1637
                cursor.execute(sql, param)
1638

    
1639
            conn.commit()
1640
            # Catch the exception
1641
        except Exception as ex:
1642
            # Roll back any change if something goes wrong
1643
            conn.rollback()
1644
            
1645
            from App import App 
1646
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1647
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1648
        finally:
1649
            # Close the db connection
1650
            conn.close()
1651

    
1652
    '''
1653
        @brief      get symbol type id
1654
        @author     kyouho
1655
        @date       2018.08.17
1656
    '''
1657
    def getSymbolTypeId(self, symbolType):
1658
        result = []
1659

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

    
1667
            sql = 'select id from SymbolType where type = ?'
1668
            param = (symbolType,)
1669
            cursor.execute(sql, param)
1670
            rows = cursor.fetchall()
1671
            
1672
            if len(rows):
1673
                result = rows[0][0]
1674
            else:
1675
                result = -1
1676
            # Catch the exception
1677
        except Exception as ex:
1678
            # Roll back any change if something goes wrong
1679
            conn.rollback()
1680
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1681
        finally:
1682
            # Close the db connection
1683
            conn.close()
1684

    
1685
        return result
1686

    
1687
    '''
1688
        @brief      get Code Table Data
1689
        @author     kyouho
1690
        @date       2018.07.10
1691
    '''
1692
    def getCodeTable(self, property, forCheckLineNumber = False):
1693
        result = []
1694
        try:
1695
            # Creates or opens a file called mydb with a SQLite3 DB
1696
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1697
            conn = sqlite3.connect(dbPath)
1698
            # Get a cursor object
1699
            cursor = conn.cursor()
1700

    
1701
            if property.upper().replace(' ','') == "NOMINALDIAMETER" and forCheckLineNumber:
1702
                sql = 'select InchStr, MetricStr from [{}] order by Metric ASC'.format(property)
1703
                cursor.execute(sql)
1704
                rows = cursor.fetchall()
1705
                for index in range(2):
1706
                    for row in rows:
1707
                        if row[index] != '' and result.count(row[index].replace("'", '"')) == 0:
1708
                            result.append(row[index].replace("'", '"'))
1709
            else:
1710
                sql = 'select uid, code, description from [{}] order by length(code) DESC'.format(property)
1711
                cursor.execute(sql)
1712
                rows = cursor.fetchall()
1713
                for row in rows:
1714
                    if forCheckLineNumber:
1715
                        data = row[1]
1716
                    else:
1717
                        data = (row[0], row[1], row[2])
1718
                    result.append(data)
1719
            # Catch the exception
1720
        except Exception as ex:
1721
            # Roll back any change if something goes wrong
1722
            conn.rollback()
1723
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1724
        finally:
1725
            # Close the db connection
1726
            conn.close()
1727

    
1728
        return result
1729

    
1730
    '''
1731
        @brief      Set Common Code Data
1732
        @author     kyouho
1733
        @date       2018.07.12
1734
    '''
1735
    def setCommonCodeData(self, tableName, datas):
1736
        try:
1737
            # Creates or opens a file called mydb with a SQLite3 DB
1738
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1739
            conn = sqlite3.connect(dbPath)
1740
            # Get a cursor object
1741
            cursor = conn.cursor()
1742

    
1743
            for data in datas:
1744
                uid = data[0]
1745
                if not uid:
1746
                    sql = "insert or replace into {}(UID, CODE, DESCRIPTION) values(lower(hex(randomblob(16))), ?, ?)".format(tableName)
1747
                    param = (data[1], data[2])
1748
                else:
1749
                    sql = "update {} SET CODE=?, DESCRIPTION=? WHERE UID = ?".format(tableName)
1750
                    param = (data[1], data[2], data[0])
1751
                cursor.execute(sql, param)
1752

    
1753
            conn.commit()
1754
        
1755
        # Catch the exception
1756
        except Exception as ex:
1757
            # Roll back any change if something goes wrong
1758
            conn.rollback()
1759
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1760
        finally:
1761
            # Close the db connection
1762
            conn.close()
1763

    
1764
    '''
1765
        @brief      Set Common Code Data
1766
        @author     kyouho
1767
        @date       2018.07.12
1768
    '''
1769
    def deleteCommonCodeData(self, datas):
1770
        try:
1771
            # Creates or opens a file called mydb with a SQLite3 DB
1772
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1773
            conn = sqlite3.connect(dbPath)
1774
            # Get a cursor object
1775
            cursor = conn.cursor()
1776

    
1777
            for data in datas:
1778
                uid = data[0]
1779
                tableName = data[1]
1780

    
1781
                if uid:
1782
                    sql = "delete from {} where UID = ?".format(tableName)
1783
                    param = (uid,)
1784
                    cursor.execute(sql, param)
1785

    
1786
                cursor.execute(sql, param)
1787

    
1788
            conn.commit()
1789
        
1790
        # Catch the exception
1791
        except Exception as ex:
1792
            # Roll back any change if something goes wrong
1793
            conn.rollback()
1794
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1795
        finally:
1796
            # Close the db connection
1797
            conn.close()
1798

    
1799
    '''
1800
        @brief      delete data list
1801
        @author     kyouho
1802
        @date       2018.08.16
1803
    '''
1804
    def deleteDataList(self, tableName, UID):
1805
        try:
1806
            # Creates or opens a file called mydb with a SQLite3 DB
1807
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1808
            conn = sqlite3.connect(dbPath)
1809
            # Get a cursor object
1810
            cursor = conn.cursor()
1811

    
1812
            sql = 'delete from {} where UID = {}'.format(tableName, UID)
1813
            
1814
            cursor.execute(sql)
1815

    
1816
            conn.commit()
1817

    
1818
        # Catch the exception
1819
        except Exception as ex:
1820
            # Roll back any change if something goes wrong
1821
            conn.rollback()
1822
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1823
        finally:
1824
            # Close the db connection
1825
            conn.close()
1826

    
1827

    
1828
    '''
1829
        @brief      get line documentName list
1830
        @author     kyouho
1831
        @date       2018.08.13
1832
    '''
1833
    def getLineDocumentNameList(self):
1834
        result = []
1835

    
1836
        try:
1837
            # Creates or opens a file called mydb with a SQLite3 DB
1838
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1839
            conn = sqlite3.connect(dbPath)
1840
            # Get a cursor object
1841
            cursor = conn.cursor()
1842

    
1843
            sql = 'select DISTINCT(PNID_NO) from LINE_DATA_LIST'
1844

    
1845
            cursor.execute(sql)
1846
            rows = cursor.fetchall()
1847
            for row in rows:
1848
                result.append(row[0])
1849
        # Catch the exception
1850
        except Exception as ex:
1851
            # Roll back any change if something goes wrong
1852
            conn.rollback()
1853
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1854
        finally:
1855
            # Close the db connection
1856
            conn.close()
1857

    
1858
        return result
1859

    
1860
    '''
1861
        @brief      get line documentName list
1862
        @author     kyouho
1863
        @date       2018.08.14
1864
    '''
1865
    def getEquipDocumentNameList(self):
1866
        result = []
1867

    
1868
        try:
1869
            # Creates or opens a file called mydb with a SQLite3 DB
1870
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1871
            conn = sqlite3.connect(dbPath)
1872
            # Get a cursor object
1873
            cursor = conn.cursor()
1874

    
1875
            sql = 'select DISTINCT(PNID_NO) from EQUIPMENT_DATA_LIST'
1876

    
1877
            cursor.execute(sql)
1878
            rows = cursor.fetchall()
1879
            for row in rows:
1880
                result.append(row[0])
1881
        # Catch the exception
1882
        except Exception as ex:
1883
            # Roll back any change if something goes wrong
1884
            conn.rollback()
1885
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1886
        finally:
1887
            # Close the db connection
1888
            conn.close()
1889

    
1890
        return result
1891

    
1892

    
1893
    '''
1894
        @brief      get line data list
1895
        @author     kyouho
1896
        @date       2018.08.13
1897
    '''
1898
    def getLineDataList(self, docName = None):
1899
        result = []
1900

    
1901
        try:
1902
            # Creates or opens a file called mydb with a SQLite3 DB
1903
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1904
            conn = sqlite3.connect(dbPath)
1905
            # Get a cursor object
1906
            cursor = conn.cursor()
1907

    
1908
            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'
1909
            if docName is not None:
1910
                sql += " where PNID_NO = '{}'".format(docName)
1911

    
1912
            cursor.execute(sql)
1913
            #columnName = list(map(lambda x: x[0].upper(), cursor.description))
1914
            rows = cursor.fetchall()
1915
            for row in rows:
1916
                data = []
1917
                for index in range(len(cursor.description)):
1918
                    data.append(row[index])
1919
                result.append(data)
1920
        # Catch the exception
1921
        except Exception as ex:
1922
            # Roll back any change if something goes wrong
1923
            conn.rollback()
1924
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1925
        finally:
1926
            # Close the db connection
1927
            conn.close()
1928

    
1929
        return result
1930

    
1931
    '''
1932
        @brief      set line data list
1933
        @author     kyouho
1934
        @date       2018.08.13
1935
    '''
1936
    def setLineDataList(self, dataLists):
1937
        try:
1938
            # Creates or opens a file called mydb with a SQLite3 DB
1939
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1940
            conn = sqlite3.connect(dbPath)
1941
            # Get a cursor object
1942
            cursor = conn.cursor()
1943
            
1944
            for data in dataLists:
1945
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
1946
                param = tuple(data)
1947
                cursor.execute(sql, param)
1948

    
1949
            conn.commit()
1950

    
1951
        # Catch the exception
1952
        except Exception as ex:
1953
            # Roll back any change if something goes wrong
1954
            conn.rollback()
1955
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1956
        finally:
1957
            # Close the db connection
1958
            conn.close()
1959

    
1960
    '''
1961
        @brief      delete line data list
1962
        @author     kyouho
1963
        @date       2018.08.13
1964
    '''
1965
    def deleteLineDataList(self, removeUID):
1966
        try:
1967
            # Creates or opens a file called mydb with a SQLite3 DB
1968
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1969
            conn = sqlite3.connect(dbPath)
1970
            # Get a cursor object
1971
            cursor = conn.cursor()
1972
            
1973
            for uid in removeUID:
1974
                sql = "delete from LINE_DATA_LIST where uid = '{}'".format(uid)
1975
                cursor.execute(sql)
1976

    
1977
            conn.commit()
1978

    
1979
        # Catch the exception
1980
        except Exception as ex:
1981
            # Roll back any change if something goes wrong
1982
            conn.rollback()
1983
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1984
        finally:
1985
            # Close the db connection
1986
            conn.close()
1987

    
1988
    '''
1989
        @brief      delete line data list
1990
        @author     kyouho
1991
        @date       2018.08.13
1992
    '''
1993
    def deleteLineDataList_LineNo(self, removeUID):
1994
        try:
1995
            # Creates or opens a file called mydb with a SQLite3 DB
1996
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1997
            conn = sqlite3.connect(dbPath)
1998
            # Get a cursor object
1999
            cursor = conn.cursor()
2000
            
2001
            for uid in removeUID:
2002
                sql = "delete from LINE_DATA_LIST where LINE_NO = ?"
2003
                param = (uid,)
2004
                cursor.execute(sql, param)
2005

    
2006
            conn.commit()
2007

    
2008
        # Catch the exception
2009
        except Exception as ex:
2010
            # Roll back any change if something goes wrong
2011
            conn.rollback()
2012
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2013
        finally:
2014
            # Close the db connection
2015
            conn.close()
2016

    
2017
    '''
2018
        @brief      delete equip data list
2019
        @author     kyouho
2020
        @date       2018.08.14
2021
    '''
2022
    def deleteEquipDataList(self, removeUID):
2023
        try:
2024
            # Creates or opens a file called mydb with a SQLite3 DB
2025
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2026
            conn = sqlite3.connect(dbPath)
2027
            # Get a cursor object
2028
            cursor = conn.cursor()
2029
            
2030
            for uid in removeUID:
2031
                sql = "delete from EQUIPMENT_DATA_LIST where uid = '{}'".format(uid)
2032
                cursor.execute(sql)
2033

    
2034
            conn.commit()
2035

    
2036
        # Catch the exception
2037
        except Exception as ex:
2038
            # Roll back any change if something goes wrong
2039
            conn.rollback()
2040
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2041
        finally:
2042
            # Close the db connection
2043
            conn.close()
2044

    
2045
    '''
2046
        @brief      delete inst data list
2047
        @author     kyouho
2048
        @date       2018.08.14
2049
    '''
2050
    def deleteInstDataList(self, removeUID):
2051
        try:
2052
            # Creates or opens a file called mydb with a SQLite3 DB
2053
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2054
            conn = sqlite3.connect(dbPath)
2055
            # Get a cursor object
2056
            cursor = conn.cursor()
2057
            
2058
            for uid in removeUID:
2059
                sql = "delete from INSTRUMENT_DATA_LIST where uid = '{}'".format(uid)
2060
                cursor.execute(sql)
2061

    
2062
            conn.commit()
2063

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

    
2073
    '''
2074
        @brief      get equipment data list
2075
        @author     humkyung
2076
        @date       2018.05.03
2077
    '''
2078
    def getEquipmentDataList(self, docName = None):
2079
        result = []
2080
        try:
2081
            # Creates or opens a file called mydb with a SQLite3 DB
2082
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2083
            conn = sqlite3.connect(dbPath)
2084
            # Get a cursor object
2085
            cursor = conn.cursor()
2086

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

    
2091
            cursor.execute(sql)
2092
            rows = cursor.fetchall()
2093
            for row in rows:
2094
                data = []
2095
                for index in range(len(cursor.description)): 
2096
                    data.append(row[index])
2097
                result.append(data)
2098
        # Catch the exception
2099
        except Exception as ex:
2100
            from App import App 
2101

    
2102
            # Roll back any change if something goes wrong
2103
            conn.rollback()
2104
            
2105
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2106
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2107
        finally:
2108
            # Close the db connection
2109
            conn.close()
2110

    
2111
        return result
2112

    
2113
    '''
2114
        @brief      get instrument data list
2115
        @author     kyouho
2116
        @date       2018.08.14
2117
    '''
2118
    def getInstrumentDataList(self, docName = None):
2119
        result = []
2120
        try:
2121
            # Creates or opens a file called mydb with a SQLite3 DB
2122
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2123
            conn = sqlite3.connect(dbPath)
2124
            # Get a cursor object
2125
            cursor = conn.cursor()
2126

    
2127
            sql = 'select UID, ITEM_NO, SERVICE, FLOW_RATE, PRESSURE, TEMPERATURE, TPYE, RANGE, NOR_LEVEL_MM, NOR_LEVEL_PERCENT, DEL_PRESS, SHUT_OFF, LOCATION, PNID_NO, REV from INSTRUMENT_DATA_LIST'
2128
            if docName is not None:
2129
                sql += " where PNID_NO = '{}'".format(docName)
2130

    
2131
            cursor.execute(sql)
2132
            rows = cursor.fetchall()
2133
            for row in rows:
2134
                data = []
2135
                for index in range(len(cursor.description)): 
2136
                    data.append(row[index])
2137
                result.append(data)
2138
        # Catch the exception
2139
        except Exception as ex:
2140
            # Roll back any change if something goes wrong
2141
            conn.rollback()
2142
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2143
        finally:
2144
            # Close the db connection
2145
            conn.close()
2146

    
2147
        return result
2148

    
2149
    '''
2150
        @brief      set equipment data list
2151
        @author     humkyung
2152
        @date       2018.05.03
2153
    '''
2154
    def setEquipmentDataList(self, dataList):
2155
        try:
2156
            # Creates or opens a file called mydb with a SQLite3 DB
2157
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2158
            conn = sqlite3.connect(dbPath)
2159
            # Get a cursor object
2160
            cursor = conn.cursor()
2161

    
2162
            for data in dataList:
2163
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2164
                param = tuple(data)
2165
                cursor.execute(sql, param)
2166
            conn.commit()
2167
        # Catch the exception
2168
        except Exception as ex:
2169
            # Roll back any change if something goes wrong
2170
            conn.rollback()
2171
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2172
        finally:
2173
            # Close the db connection
2174
            conn.close()
2175

    
2176
    '''
2177
        @brief      set instrumnet data list
2178
        @author     kyoyho
2179
        @date       2018.08.14
2180
    '''
2181
    def setInstrumentDataList(self, dataList):
2182
        try:
2183
            # Creates or opens a file called mydb with a SQLite3 DB
2184
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2185
            conn = sqlite3.connect(dbPath)
2186
            # Get a cursor object
2187
            cursor = conn.cursor()
2188

    
2189
            for data in dataList:
2190
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2191
                param = tuple(data)
2192
                cursor.execute(sql, param)
2193
            conn.commit()
2194

    
2195
        # Catch the exception
2196
        except Exception as ex:
2197
            # Roll back any change if something goes wrong
2198
            conn.rollback()
2199
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2200
        finally:
2201
            # Close the db connection
2202
            conn.close()
2203

    
2204
    '''
2205
        @brief  get IsOriginDetect ComboBox Items
2206
    '''
2207
    def getIsOriginDetectComboBoxItems(self):
2208
        return [("원본 도면", 0), ("텍스트 제거 도면", 1)]
2209

    
2210
    '''
2211
        @brief  get IsOriginDetect ComboBox Items
2212
    '''
2213
    def getOcrOptionComboBoxItems(self):
2214
        return [("OCR 미적용", 0), ("일반 심볼", 1), ("Instrument 계통", 2)]
2215
    
2216
    '''
2217
        @brief      Return Symbol Type Items
2218
        @author     Jeongwoo
2219
        @date       18.04.20
2220
        @history    18.05.08    Jeongwoo type index changed
2221
    '''
2222
    def getSymbolTypeList(self):
2223
        symbolTypeList = []
2224

    
2225
        try:
2226
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2227

    
2228
            conn = sqlite3.connect(dbPath)
2229
            cursor = conn.cursor()
2230
            sql = 'SELECT * FROM SymbolType ORDER BY type ASC'
2231
            try:
2232
                cursor.execute(sql)
2233
                rows = cursor.fetchall()
2234
                for row in rows:
2235
                    symbolTypeList.append((row[0], row[1], row[2])) # UID, category, type
2236
            except Exception as ex:
2237
                from App import App
2238

    
2239
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2240
                App.mainWin().addMessage(MessageType.Error, message)
2241
        finally:
2242
            conn.close()
2243

    
2244
        return symbolTypeList
2245

    
2246
    '''
2247
        @brief      Get Symbol Category by Symbol Type
2248
        @author     Jeongwoo
2249
        @date       2018.05.09
2250
    '''
2251
    def getSymbolCategoryByType(self, type):
2252
        category = None
2253
        try:
2254
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
2255
            conn = sqlite3.connect(dbPath)
2256
            cursor = conn.cursor()
2257
            sql = 'SELECT category FROM SymbolType WHERE type = "' + type + '"'
2258
            cursor.execute(sql)
2259
            rows = cursor.fetchall()
2260
            if rows is not None and len(rows) > 0:
2261
                category = rows[0][0]
2262
        except Exception as ex:
2263
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2264
        finally:
2265
            conn.close()
2266

    
2267
        return category
2268

    
2269
    '''
2270
        @brief      Check Symbol Type is included in 'Equipment' Category
2271
        @author     Jeongwoo
2272
        @date       2018.05.09
2273
    '''
2274
    def isEquipmentType(self, type):
2275
        category = self.getSymbolCategoryByType(type)
2276
        return (category is not None and category == 'Equipment')
2277

    
2278
    '''
2279
        @brief      Return Symbol Type Items with "None"
2280
        @author     Jeongwoo
2281
        @date       18.04.06
2282
        @history    Seperate SymbolTypeList and "None"
2283
    '''
2284
    def getSymbolTypeComboBoxItems(self):
2285
        symbolTypeList = self.getSymbolTypeList()
2286
        symbolTypeList.insert(0, ('None', 'None', 'None'))
2287

    
2288
        return symbolTypeList
2289

    
2290
    '''
2291
        @brief  get Base Symbol ComboBox Items
2292
    '''
2293
    def getBaseSymbolComboBoxItems(self, type = None):
2294
        bsymbolNameList = self.getSymbolNameListByType(type)
2295
        bsymbolNameList.sort()
2296
        bsymbolNameList.insert(0, "None")
2297
        return bsymbolNameList
2298

    
2299
    '''
2300
        @brief  get Additional Symbol ComboBox Items
2301
    '''
2302
    def getAdditionalSymbolComboBoxItems(self):
2303
        asymbolNameList = self.getSymbolNameList()
2304
        asymbolNameList.sort()
2305
        asymbolNameList.insert(0, "None")
2306
        return asymbolNameList
2307

    
2308
    '''
2309
        @brief  get Additional Symbol's default direction ComboBox Items
2310
    '''
2311
    def getDefaultSymbolDirectionComboBoxItems(self):
2312
        return [("UP", 0), ("DOWN", 2), ("LEFT", 3), ("RIGHT", 1)]
2313
    
2314
    '''
2315
        @brief  getter of activeDrawing
2316
        @author humkyung
2317
        @date   2018.07.07
2318
    '''
2319
    @property
2320
    def activeDrawing(self):
2321
        return self._activeDrawing
2322

    
2323
    '''
2324
        @brief  setter of activeDrawing
2325
        @author humkyung
2326
        @date   2018.07.07
2327
    '''
2328
    @activeDrawing.setter
2329
    def activeDrawing(self, value):
2330
        self._activeDrawing = value