프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / DTI_PID / AppDocData.py @ c4d659da

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

1
# coding: utf-8
2

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

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

    
21
from SingletonInstance import SingletonInstane
22
import Project
23
import SymbolBase
24
import symbol
25
from EquipmentData import EquipmentData
26

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

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

    
51
class Area:
52
    def __init__(self):
53
        self.name = None
54
        self.x = None
55
        self.y = None
56
        self.width = None
57
        self.height = None
58
    
59
    '''
60
        @brief  parse area
61
        @author humkyung
62
        @date   2018.06.29
63
    '''
64
    def parse(self, strArea):
65
        import re
66

    
67
        found = re.findall('\d+', strArea)
68
        if len(found) == 4:
69
            self.x = int(found[0])
70
            self.y = int(found[1])
71
            self.width = int(found[2])
72
            self.height = int(found[3])
73

    
74
    '''
75
        @brief  to string
76
        @author humkyung
77
        @date   2018.06.30
78
    '''
79
    def toString(self):
80
        return '({},{}),({},{})'.format(self.x, self.y, self.width, self.height)
81
        
82
    '''
83
        @brief  clone an object
84
    '''
85
    def clone(self):
86
        clone = Area()
87
        clone.x = self.x
88
        clone.y = self.y
89
        clone.width = self.width
90
        clone.height = self.height
91

    
92
class Config:
93
    def __init__(self, section, key, value):
94
        self.section = section
95
        self.key = key
96
        self.value = value
97

    
98
class NominalPipeSize:
99
    def __init__(self, code, metric, inch, inchStr, metricStr):
100
        self.code = code
101
        self.metric = metric
102
        self.inch = inch
103
        self.inchStr = inchStr
104
        self.metricStr = metricStr
105
        self.sizeUnit = 'Metric'
106

    
107
    '''
108
        @brief  return size value string
109
        @author humkyung
110
        @date   2018.04.24
111
    '''
112
    def sizeValue(self):
113
        return self.inchStr if 'Inch' == self.sizeUnit else self.metricStr
114

    
115
'''
116
    @brief  Pipe color class
117
'''
118
class Color:
119
    def __init__(self, index, red, green, blue):
120
        self.index = index
121
        self.red = red
122
        self.green = green
123
        self.blue = blue
124

    
125
'''
126
    @brief      MessageType
127
    @author     humkyung 
128
    @date       2018.07.31
129
'''
130
class MessageType(Enum):
131
    Normal = 1
132
    Error = 2
133

    
134
class AppDocData(SingletonInstane):
135
    def __init__(self):
136
        self._imgFilePath = None
137
        self.imgName = None
138
        self.imgWidth = 0
139
        self.imgHeight = 0
140
        self._imgSrc = None
141

    
142
        self._areas = []
143
        self.equipments = []
144
        #self.equipmentDataList = []
145
        self.lineNos = []
146
        self.lines = []
147
        self.symbols = []
148
        self._colors = None
149
        self._lineTypes = None
150
        self._lineTypeConfigs = None
151
        self._activeDrawing = None
152
        self._hmbTable = None
153

    
154
    '''
155
        @brief      Get DB file path in ProgramData
156
        @author     Jeongwoo
157
        @date       2018.06.27
158
        @history    2018.06.29  Jeongwoo    Change method to get template db path
159
    '''
160
    def getTemplateDbPath(self):
161
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
162
        templateDbPath = os.path.join(path, 'Template.db')
163
        return templateDbPath
164

    
165
    '''
166
        @brief  getter of colors 
167
        @author humkyung
168
        @date   2018.06.18
169
    '''
170
    @property
171
    def colors(self):
172
        if self._colors is None:
173
            self._colors = []
174
            try:
175
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath() , 'ITI_PID.db')
176

    
177
                conn = sqlite3.connect(dbPath)
178
                cursor = conn.cursor()
179
                sql = 'SELECT UID,RED,GREEN,BLUE FROM Colors'
180
                cursor.execute(sql)
181
                rows = cursor.fetchall()
182
                for row in rows:
183
                    self._colors.append(Color(int(row[0]), int(row[1]), int(row[2]), int(row[3])))
184
            # Catch the exception
185
            except Exception as ex:
186
                # Roll back any change if something goes wrong
187
                conn.rollback()
188

    
189
                from App import App 
190
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
191
                App.mainWnd().addMessage.emit(MessageType.Error, message)
192
            finally:
193
                conn.close()
194

    
195
        return self._colors
196

    
197
    '''
198
        @brief  setter of colors
199
        @author humkyung
200
        @date   2018.06.18
201
    '''
202
    @colors.setter
203
    def colors(self, value):
204
        self._colors = value
205

    
206
    '''
207
        @brief      set image file path
208
        @author     humkyung
209
        @date       2018.07.30
210
    '''
211
    def setImgFilePath(self, path):
212
        self._imgFilePath = path
213
        self.imgName = os.path.splitext(os.path.basename(self._imgFilePath))[0]
214

    
215
    '''
216
        @brief      getter of imgSrc
217
        @author     humkyung
218
        @date       2018.07.30
219
    '''
220
    @property
221
    def imgSrc(self):
222
        import cv2
223

    
224
        if self._imgSrc is None and self._imgFilePath is not None and os.path.isfile(self._imgFilePath):
225
            self._imgSrc = cv2.cvtColor(cv2.imread(self._imgFilePath), cv2.COLOR_BGR2GRAY)
226
            blur = cv2.GaussianBlur(self._imgSrc , (5,5),0)
227
            self._imgSrc = cv2.threshold(self._imgSrc , 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
228
        
229
        return self._imgSrc
230

    
231
    '''
232
        @brief      setter of imgSrc
233
        @author     humkyung
234
        @date       2018.07.30
235
    '''
236
    @imgSrc.setter
237
    def imgSrc(self, value):
238
        self._imgSrc = value
239

    
240
    '''
241
        @brief      reset imgSrc
242
        @author     humkyung
243
        @date       2018.07.30
244
    '''
245
    def resetImgSrc(self):
246
        self._imgSrc = None
247

    
248
    '''
249
        @brief  getter of line type configs
250
        @author humkyung
251
        @date   2018.06.28
252
    '''
253
    @property
254
    def lineTypeConfigs(self):
255
        from PyQt5.QtCore import Qt
256

    
257
        if self._lineTypeConfigs is None:
258
            self._lineTypeConfigs = []
259

    
260
            styleMap = [('SolidLine', Qt.SolidLine), ('DashLine', Qt.DashLine), ('DotLine', Qt.DotLine), ('DashDotLine', Qt.DashDotLine), 
261
                ('DashDotDotLine', Qt.DashDotDotLine), ('CustomDashLine', Qt.CustomDashLine)]
262

    
263
            configs = self.getConfigs('LineTypes')
264
            for config in configs:
265
                width, _style = config.value.split(',')
266
                matches = [param for param in styleMap if param[0] == _style]
267
                style = matches[0][1] if matches else Qt.SolidLine
268
                self._lineTypeConfigs.append((config.key, int(width), style))
269
        
270
        return self._lineTypeConfigs
271

    
272
    '''
273
        @brief  setter of line type configs
274
        @author humkyung
275
        @date   2018.06.28
276
    '''
277
    @lineTypeConfigs.setter
278
    def lineTypeConfigs(self, value):
279
        self._lineTypeConfigs = value
280

    
281
    '''
282
        @brief      getter of hmb table
283
        @author     humkyung
284
        @date       2018.07.16
285
    '''
286
    @property
287
    def hmbTable(self):
288
        from HMBTable import HMBTable
289

    
290
        if self._hmbTable is None:
291
            self._hmbTable = HMBTable()
292
            self._hmbTable.loadData()
293
        
294
        return self._hmbTable
295

    
296
    '''
297
        @brief      setter of hmb table
298
        @author     humkyung
299
        @date       2018.07.16
300
    '''
301
    @hmbTable.setter
302
    def hmbTable(self, value):
303
        self._hmbTable = value
304

    
305
    '''
306
        @brief  get line type config of given line type
307
        @author humkyung
308
        @date   2018.06.28
309
    '''
310
    def getLineTypeConfig(self, lineType):
311
        from PyQt5.QtCore import Qt
312

    
313
        matches = [config for config in self.lineTypeConfigs if config[0] == lineType]
314
        return matches[0] if matches else (lineType, 5, Qt.SolidLine)        
315

    
316
    def setCurrentPidSource(self, image):
317
        self.imgWidth, self.imgHeight = image.size
318

    
319
        self.currentPidSource = Source(image)
320

    
321
    def getCurrentPidSource(self):
322
        return self.currentPidSource
323

    
324
    '''
325
        @brief      Check if Exist data or not, Moved from SG_DbHelper
326
        @author     Jeongwoo
327
        @date       2018.05.03
328
    '''
329
    def isExistData(self, fieldName, data):
330
        rows = None
331
        try:
332
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
333

    
334
            conn = sqlite3.connect(dbPath)
335
            cursor = conn.cursor()
336
            sql = ""
337
            if isinstance(data, str):
338
                sql = "SELECT * FROM Symbol WHERE " + fieldName + " = '"+ data +"'"
339
            else:
340
                sql = "SELECT * FROM Symbol WHERE " + fieldName + " = "+ str(data) +""
341
            cursor.execute(sql)
342
            rows = cursor.fetchall()
343
        # Catch the exception
344
        except Exception as ex:
345
            # Roll back any change if something goes wrong
346
            conn.rollback()
347
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
348
        finally:
349
            conn.close()
350
            if rows is not None and len(rows) > 0:
351
                return True
352
            else:
353
                return False
354

    
355
    '''
356
        @brief      Check if exist file name or not, Moved from SG_DbHelper
357
        @author     Jeongwoo
358
        @date       2018.05.03
359
    '''
360
    def isExistFileName(self, name):
361
        rows = None
362
        try:
363
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
364
            conn = sqlite3.connect(dbPath)
365
            cursor = conn.cursor()
366
            sql = "SELECT * FROM Symbol WHERE name = '"+ name +"'"
367
            cursor.execute(sql)
368
            rows = cursor.fetchall()
369
        # Catch the exception
370
        except Exception as ex:
371
            # Roll back any change if something goes wrong
372
            conn.rollback()
373
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
374
        finally:
375
            conn.close()
376
            if rows is not None and len(rows) > 0:
377
                return True
378
            else:
379
                return False
380

    
381
    '''
382
        @brief      Insert new symbol into Symbol Table, Moved from SG_DbHelper
383
        @author     Jeongwoo
384
        @date       2018.05.03
385
    '''
386
    def insertSymbol(self, symbol):
387
        isAdded = False
388
        try:
389
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
390
            conn = sqlite3.connect(dbPath)
391
            
392
            INSERT_SYMBOL_SQL = '''
393
                INSERT INTO Symbol(name, type, threshold, minMatchPoint, isDetectOrigin, rotationCount, ocrOption, isContainChild, originalPoint, connectionPoint, baseSymbol, additionalSymbol, isExceptDetect, hasInstrumentLabel) 
394
                VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
395
            '''
396

    
397
            cursor = conn.cursor()
398
            query = ( symbol.getName(), symbol.getType(), symbol.getThreshold()
399
                           , symbol.getMinMatchCount(), symbol.getIsDetectOnOrigin(), symbol.getRotationCount()
400
                           , symbol.getOcrOption(), symbol.getIsContainChild()
401
                           , symbol.getOriginalPoint(), symbol.getConnectionPoint()
402
                           , symbol.getBaseSymbol(), symbol.getAdditionalSymbol(), symbol.getIsExceptDetect(), symbol.getHasInstrumentLabel())
403
            cursor.execute(INSERT_SYMBOL_SQL, query)
404
            conn.commit()
405
            isAdded = True
406
        # Catch the exception
407
        except Exception as ex:
408
            # Roll back any change if something goes wrong
409
            conn.rollback()
410
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
411
        finally:
412
            conn.close()
413
            return (isAdded, symbol.getType(), symbol.getName(), symbol.getPath())
414

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

    
453
    '''
454
        @brief      Get Detecting Target Symbol List (Field 'isExceptDetect' == False(0))
455
        @author     Jeongwoo
456
        @date       18.04.24
457
        @history    humkyung 2018.06.28 select symbol order by threshold descending
458
    '''
459
    def getTargetSymbolList(self):
460
        targetSymbolList = []
461

    
462
        try:
463
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
464

    
465
            conn = sqlite3.connect(dbPath)
466
            cursor = conn.cursor()
467
            sql = 'SELECT * FROM Symbol WHERE isExceptDetect = 0 order by threshold desc'
468
            try:
469
                cursor.execute(sql)
470
                rows = cursor.fetchall()
471
                for row in rows:
472
                    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
473
                    targetSymbolList.append(sym)
474
            except Exception as ex:
475
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
476
        finally:
477
            conn.close()
478

    
479
        return targetSymbolList
480

    
481
    '''
482
        @brief  build application database
483
        @author humkyung
484
        @date   2018.04.20
485
    '''
486
    def buildAppDatabase(self):
487
        try:
488
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
489
            appDatabaseFilePath = os.path.join(path, 'App.db')
490

    
491
            # Creates or opens a file called mydb with a SQLite3 DB
492
            conn = sqlite3.connect(appDatabaseFilePath)
493
            # Get a cursor object
494
            cursor = conn.cursor()
495

    
496
            sqlFiles = ['App.Configuration.sql', 'App.Styles.sql']
497
            for sqlFile in sqlFiles:
498
                filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', sqlFile)
499
                try:
500
                    file = QFile(filePath)
501
                    file.open(QFile.ReadOnly)
502
                    sql = file.readAll()
503
                    sql = str(sql, encoding='utf8')
504
                    cursor.executescript(sql)
505
                finally:
506
                    file.close()
507
            conn.commit()
508
        # Catch the exception
509
        except Exception as ex:
510
            # Roll back any change if something goes wrong
511
            conn.rollback()
512
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
513
        finally:
514
            # Close the db connection
515
            conn.close()
516

    
517
    '''
518
        @brief  load app style
519
        @author humkyung
520
        @date   2018.04.20
521
    '''
522
    def loadAppStyle(self):
523
        style = 'Fusion'
524

    
525
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
526
        if not os.path.exists(path): os.makedirs(path)
527

    
528
        self.buildAppDatabase()
529
        try:
530
            appDatabaseFilePath = os.path.join(path, 'App.db')
531
            # Creates or opens a file called mydb with a SQLite3 DB
532
            conn = sqlite3.connect(appDatabaseFilePath)
533
            # Get a cursor object
534
            cursor = conn.cursor()
535

    
536
            sql = "select Value from Configuration where Section='App' and Key='Style'" 
537
            cursor.execute(sql)
538
            rows = cursor.fetchall()
539
            style = rows[0][0] if 1 == len(rows) else 'Fusion'
540
        # Catch the exception
541
        except Exception as ex:
542
            # Roll back any change if something goes wrong
543
            conn.rollback()
544
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
545
        finally:
546
            # Close the db connection
547
            conn.close()
548

    
549
        return style
550

    
551
    '''
552
        @brief  load app styles and then return a list
553
        @author humkyung
554
        @date   2018.04.20
555
    '''
556
    def loadAppStyles(self):
557
        styles = []
558

    
559
        try:
560
            self.buildAppDatabase()
561

    
562
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
563
            appDatabaseFilePath = os.path.join(path, 'App.db')
564

    
565
            # Creates or opens a file called mydb with a SQLite3 DB
566
            conn = sqlite3.connect(appDatabaseFilePath)
567
            # Get a cursor object
568
            cursor = conn.cursor()
569

    
570
            sql = 'select UID,Value from Styles'
571
            cursor.execute(sql)
572
            rows = cursor.fetchall()
573
            for row in rows: styles.append(row[1])
574
            if 0 == len(rows): rows.append('fusion')
575
        # Catch the exception
576
        except Exception as ex:
577
            # Roll back any change if something goes wrong
578
            conn.rollback()
579
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
580
        finally:
581
            # Close the db connection
582
            conn.close()
583

    
584
        return styles
585

    
586
    '''
587
        @brief  Set current Project
588
        @history    2018.06.27  Jeongwoo    If DB file is not, copy DB file from ProgramData
589
    '''
590
    def setCurrentProject(self, project):
591
        self.project = project
592
        self.makeChildDir()
593
        try:
594
            # Creates or opens a file called mydb with a SQLite3 DB
595
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath() , "ITI_PID.db")
596
            
597
            if not os.path.isfile(dbPath):
598
                templatePath = self.getTemplateDbPath()
599
                templateFile = QFile(templatePath)
600
                templateFile.copy(dbPath)
601
            else:
602
                try:
603
                    conn = sqlite3.connect(dbPath)
604
                    # Get a cursor object
605
                    cursor = conn.cursor()
606

    
607
                    fileNames = os.listdir(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts'))
608
                    for fileName in fileNames:
609
                        if fileName.endswith(".sql") and (1 == len(os.path.splitext(fileName)[0].split('.'))):
610
                            try:
611
                                file = QFile(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', fileName))
612
                                file.open(QFile.ReadOnly)
613
                                sql = file.readAll()
614
                                sql = str(sql, encoding='utf8')
615
                                cursor.executescript(sql)
616
                            finally:
617
                                file.close()
618
                    conn.commit()
619
                except Exception as ex:
620
                    print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
621
                finally:
622
                    conn.close()
623
        # Catch the exception
624
        except Exception as ex:
625
            # Roll back any change if something goes wrong
626
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
627
        finally:
628
            pass
629

    
630
    '''
631
        @brief      Make Directory
632
        @author     Jeongwoo
633
        @date       18.05.08
634
        @history    humkyung 2018.06.19 make 'Tile' directory
635
                    humkyung 2018.07.09 make drawing folder if not exists
636
    '''
637
    def makeChildDir(self):
638
        project = AppDocData.instance().getCurrentProject()
639
        dbDir = project.getDbFilePath()
640
        if not os.path.exists(dbDir):
641
            os.makedirs(dbDir)
642
        imgDir = project.getImageFilePath()
643
        if not os.path.exists(imgDir):
644
            os.makedirs(imgDir)
645
        svgDir = project.getSvgFilePath()
646
        if not os.path.exists(svgDir):
647
            os.makedirs(svgDir)
648
        outputDir = project.getOutputPath()
649
        if not os.path.exists(outputDir):
650
            os.makedirs(outputDir)
651
        tempDir = project.getTempPath()
652
        if not os.path.exists(tempDir):
653
            os.makedirs(tempDir)
654
        drawingPath = project.getDrawingFilePath()
655
        if not os.path.exists(drawingPath):
656
            os.makedirs(drawingPath)
657
        
658
        path = os.path.join(tempDir, 'Tile')
659
        if not os.path.exists(path):
660
            os.makedirs(path)
661

    
662
    '''
663
        @brief  Get current Project
664
    '''
665
    def getCurrentProject(self):
666
        return self.project
667

    
668
    '''
669
        @brief      return project database path
670
        @history    humkyung 2018.04.19 return Project.db in Program Data folder instead of PROJECT_DB_PATH variable
671
    '''
672
    def getPrjDatabasePath(self):
673
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
674
        if not os.path.exists(path): os.makedirs(path)
675

    
676
        prjDatabaseFilePath = os.path.join(path, 'Project.db')
677
        try:
678
            # Creates or opens a file called mydb with a SQLite3 DB
679
            conn = sqlite3.connect(prjDatabaseFilePath)
680
            # Get a cursor object
681
            cursor = conn.cursor()
682

    
683
            filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', 'Project.Projects.sql')
684
            try:
685
                file = QFile(filePath)
686
                file.open(QFile.ReadOnly)
687
                sql = file.readAll()
688
                sql = str(sql, encoding='utf8')
689
                cursor.executescript(sql)
690
            finally:
691
                file.close()
692
            conn.commit()
693
        # Catch the exception
694
        except Exception as ex:
695
            # Roll back any change if something goes wrong
696
            conn.rollback()
697
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
698
        finally:
699
            # Close the db connection
700
            conn.close()
701
        
702
        return prjDatabaseFilePath
703

    
704
    '''
705
        @brief  return line properties
706
        @author humkyung
707
        @date   2018.04.09
708
    '''
709
    def getLineProperties(self):
710
        res = []
711
        try:
712
            # Creates or opens a file called mydb with a SQLite3 DB
713
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
714
            db = sqlite3.connect(dbPath)
715
            # Get a cursor object
716
            cursor = db.cursor()
717

    
718
            sql = "select Name from LineProperties order by Name" 
719
            cursor.execute(sql)
720
            rows = cursor.fetchall()
721
            for row in rows:
722
                res.append(row[0])
723
        # Catch the exception
724
        except Exception as ex:
725
            # Roll back any change if something goes wrong
726
            db.rollback()
727
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
728
        finally:
729
            # Close the db connection
730
            db.close()
731

    
732
        return res
733

    
734
    '''
735
        @brief  return line types 
736
        @author humkyung
737
        @date   2018.06.27
738
    '''
739
    def getLineTypes(self):
740
        res = []
741
        try:
742
            # Creates or opens a file called mydb with a SQLite3 DB
743
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
744
            db = sqlite3.connect(dbPath)
745
            # Get a cursor object
746
            cursor = db.cursor()
747

    
748
            sql = "select Name from LineTypes order by Name" 
749
            cursor.execute(sql)
750
            rows = cursor.fetchall()
751
            for row in rows:
752
                res.append(row[0])
753
        # Catch the exception
754
        except Exception as ex:
755
            # Roll back any change if something goes wrong
756
            db.rollback()
757
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
758
        finally:
759
            # Close the db connection
760
            db.close()
761

    
762
        return res
763

    
764
    '''
765
        @brief      Insert New Project Info
766
        @author     Jeongwoo
767
        @date       2018.04.06
768
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
769
    '''
770
    def insertProjectInfo(self, dir):
771
        try:
772
            prjDatabaseFilePath = self.getPrjDatabasePath()
773
            conn = sqlite3.connect(prjDatabaseFilePath)
774
            folderName = dir.split('/')[-1]
775
            if folderName:
776
                nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
777
                sql = "INSERT INTO Projects(Name, Path, CreatedDate, UpdatedDate) VALUES('" + folderName + "', '" + dir + "', '" + nowDate + "', '" + nowDate + "')"
778
                cur = conn.cursor()
779
                cur.execute(sql)
780
                conn.commit()
781
            else:
782
                print("Empty folder name")
783
        except Exception as ex:
784
            # Roll back any change if something goes wrong
785
            conn.rollback()
786
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
787
        finally:
788
            conn.close()
789

    
790
    '''
791
        @brief      Update Project UpdatedDate Field
792
        @author     Jeongwoo
793
        @date       2018.04.06
794
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
795
    '''
796
    def updateProjectUpdatedDate(self, id):
797
        try:
798
            prjDatabaseFilePath = self.getPrjDatabasePath()
799
            conn = sqlite3.connect(prjDatabaseFilePath)
800
            nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
801
            sql = '''
802
                UPDATE Projects
803
                SET UpdatedDate = ?
804
                WHERE Id = ?
805
            '''
806
            cur = conn.cursor()
807
            cur.execute(sql, (nowDate, id))
808
            conn.commit()
809
        except Exception as ex:
810
            # Roll back any change if something goes wrong
811
            conn.rollback()
812
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
813
        finally:
814
            conn.close()
815

    
816
    '''
817
        @brief  get project list from database
818
        @history    humkyung 2018.04.18 add only project which's project exists
819
    '''
820
    def getProjectList(self):
821
        from Project import Project
822

    
823
        projectList = []
824

    
825
        try:
826
            conn = sqlite3.connect(self.getPrjDatabasePath())
827
            cursor = conn.cursor()
828
            sql = 'SELECT id,name,path,createddate,updateddate  FROM Projects ORDER BY UpdatedDate DESC'
829
            try:
830
                cursor.execute(sql)
831
                rows = cursor.fetchall()
832
                for row in rows:
833
                    if os.path.isdir(row[2]):   # check if folder exists
834
                        projectList.append(Project(row[0], row[1], row[2], row[3], row[4]))
835
            except Exception as ex:
836
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
837
        finally:
838
            conn.close()
839

    
840
        return projectList
841

    
842
    '''
843
        @brief  get sliding window size
844
        @author humkyung
845
    '''
846
    def getSlidingWindowSize(self):
847
        res = [10,10]
848
        try:
849
            configs = self.getConfigs('Sliding Window')
850
            for config in configs:
851
                if config.key == 'Width':
852
                    res[0] = int(config.value)
853
                elif config.key == 'Height':
854
                    res[1] = int(config.value)
855
        # Catch the exception
856
        except Exception as ex:
857
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
858
        
859
        return res
860

    
861
    '''
862
        @brief  get line no configuration
863
        @author humkyung
864
        @date   2018.04.16
865
    '''
866
    def getLineNoConfiguration(self):
867
        res = None
868
        try:
869
            # Creates or opens a file called mydb with a SQLite3 DB
870
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
871
            conn = sqlite3.connect(dbPath)
872
            # Get a cursor object
873
            cursor = conn.cursor()
874

    
875
            delimiter = None
876
            sql = "select * from configuration where section='Line No' and key='Delimiter"
877
            cursor.execute(sql)
878
            rows = cursor.fetchall()
879
            if len(rows) == 1:
880
                delimiter = rows[0][2]
881

    
882
            if delimiter is not None:
883
                sql = "select * from configuration where section='Line No' and key='Configuration'"
884
                cursor.execute(sql)
885
                rows = cursor.fetchall()
886
                if len(rows) == 1:
887
                    res = rows[0][2].split(delimiter)
888
        # Catch the exception
889
        except Exception as ex:
890
            # Roll back any change if something goes wrong
891
            conn.rollback()
892
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
893
        finally:
894
            # Close the db connection
895
            conn.close()
896
        
897
        return res
898

    
899
    '''
900
        @brief  get area list
901
        @author humkyung
902
    '''
903
    def getAreaList(self):
904
        if len(self._areas) == 0:
905
            try:
906
                # Creates or opens a file called mydb with a SQLite3 DB
907
                dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
908
                conn = sqlite3.connect(dbPath)
909
                # Get a cursor object
910
                cursor = conn.cursor()
911

    
912
                sql = "select * from configuration where section='Area'"
913
                cursor.execute(sql)
914
                rows = cursor.fetchall()
915
                for row in rows:
916
                    area = Area()
917
                    area.name = row[1]
918
                    area.parse(row[2])
919
                    self._areas.append(area)
920
            # Catch the exception
921
            except Exception as ex:
922
                # Roll back any change if something goes wrong
923
                conn.rollback()
924
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
925
            finally:
926
                # Close the db connection
927
                conn.close()
928
        
929
        return self._areas 
930

    
931
    '''
932
        @brief  get area of given name
933
        @author humkyung
934
        @date   2018.04.07
935
    '''
936
    def getArea(self, name):
937
        areas = self.getAreaList()
938
        matches = [area for area in areas if area.name==name]
939
        if 1 == len(matches): return matches[0]
940

    
941
        return None
942

    
943
    '''
944
        @brief  get configurations
945
        @author humkyung
946
        @date   2018.04.16
947
        @history kyouho 2018.07.09 change query method
948
    '''
949
    def getConfigs(self, section, key=None):
950
        res = []
951

    
952
        try:
953
            # Creates or opens a file called mydb with a SQLite3 DB
954
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
955
            conn = sqlite3.connect(dbPath)
956
            # Get a cursor object
957
            cursor = conn.cursor()
958

    
959
            if key is not None:
960
                sql = "select * from configuration where section=? and key=?"
961
                param = (section, key)
962
            else:
963
                sql = "select * from configuration where section=?"
964
                param = (section,)
965

    
966
            cursor.execute(sql, param)
967
            rows = cursor.fetchall()
968
            for row in rows:
969
                res.append(Config(row[0], row[1], row[2]))
970
        # Catch the exception
971
        except Exception as ex:
972
            # Roll back any change if something goes wrong
973
            conn.rollback()
974
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
975
        finally:
976
            # Close the db connection
977
            conn.close()
978

    
979
        return res
980

    
981
    '''
982
        @brief      save configurations
983
        @author     humkyung
984
        @date       2018.04.16
985
        @history    humkyung 2018.07.03 replace ' with " if value has '
986
                    kyouho 2018.07.09 change query method
987
    '''
988
    def saveConfigs(self, configs):
989
        try:
990
            # Creates or opens a file called mydb with a SQLite3 DB
991
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
992
            conn = sqlite3.connect(dbPath)
993
            # Get a cursor object
994
            cursor = conn.cursor()
995

    
996
            for config in configs:
997
                value = config.value
998
                if type(value) is str and "'" in value:
999
                    value = value.replace("'", "''")
1000

    
1001
                sql = "insert or replace into configuration values(?,?,?)"
1002
                param = (config.section, config.key, value)
1003

    
1004
                cursor.execute(sql, param)
1005
            conn.commit()
1006
        # Catch the exception
1007
        except Exception as ex:
1008
            # Roll back any change if something goes wrong
1009
            conn.rollback()
1010
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1011
        finally:
1012
            # Close the db connection
1013
            conn.close()
1014

    
1015
    '''
1016
        @brief  delete configurations
1017
        @author humkyung
1018
        @date   2018.06.29
1019
    '''
1020
    def deleteConfigs(self, section, key=None):
1021
        try:
1022
            # Creates or opens a file called mydb with a SQLite3 DB
1023
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
1024
            conn = sqlite3.connect(dbPath)
1025
            # Get a cursor object
1026
            cursor = conn.cursor()
1027

    
1028
            if key is not None:
1029
                sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
1030
            else:
1031
                sql = "delete from configuration where section='{}'".format(section)
1032
            cursor.execute(sql)
1033

    
1034
            conn.commit()
1035
        # Catch the exception
1036
        except Exception as ex:
1037
            # Roll back any change if something goes wrong
1038
            conn.rollback()
1039
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1040
        finally:
1041
            # Close the db connection
1042
            conn.close()
1043

    
1044
    '''
1045
        @brief      set area list
1046
        @history    humkyung 2018.05.18 round area coordinate and dimension before saving
1047
    '''
1048
    def setAreaList(self, areas):
1049
        for area in areas:
1050
            matches = [x for x in self._areas if x.name==area.name]
1051
            if 1 == len(matches):
1052
                matches[0].x = area.x
1053
                matches[0].y = area.y
1054
                matches[0].width = area.width
1055
                matches[0].height = area.height
1056
            elif 0 == len(matches):
1057
                self._areas.append(area)
1058

    
1059
        try:
1060
            # Creates or opens a file called mydb with a SQLite3 DB
1061
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
1062
            conn = sqlite3.connect(dbPath)
1063
            # Get a cursor object
1064
            cursor = conn.cursor()
1065

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

    
1070
            conn.commit()
1071
        # Catch the exception
1072
        except Exception as ex:
1073
            # Roll back any change if something goes wrong
1074
            conn.rollback()
1075
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1076
        finally:
1077
            # Close the db connection
1078
            conn.close()
1079
            
1080
    '''
1081
        @brief  get symbol name list
1082
    '''
1083
    def getSymbolNameList(self):
1084
        symbolNametList = []
1085

    
1086
        try:
1087
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
1088

    
1089
            conn = sqlite3.connect(dbPath)
1090
            cursor = conn.cursor()
1091
            sql = 'SELECT * FROM SymbolName'
1092
            try:
1093
                cursor.execute(sql)
1094
                rows = cursor.fetchall()
1095
                for row in rows:
1096
                    symbolNametList.append(row[2]) # Name String
1097
            except Exception as ex:
1098
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1099
        finally:
1100
            conn.close()
1101

    
1102
        return symbolNametList
1103

    
1104
    '''
1105
        @brief      get symbol name list by symbol Type
1106
        @author     Jeongwoo
1107
        @date       18.04.06
1108
        @history    .
1109
    '''
1110
    def getSymbolNameListByType(self, type):
1111
        symbolNametList = []
1112

    
1113
        try:
1114
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
1115

    
1116
            conn = sqlite3.connect(dbPath)
1117
            cursor = conn.cursor()
1118
            sql = ''
1119
            if type is not None:
1120
                sql = 'SELECT * FROM SymbolName WHERE type = "' + type + '"'
1121
                try:
1122
                    cursor.execute(sql)
1123
                    rows = cursor.fetchall()
1124
                    for row in rows:
1125
                        symbolNametList.append(row[2]) # Name String
1126
                except Exception as ex:
1127
                    print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1128
        finally:
1129
            conn.close()
1130

    
1131
        return symbolNametList
1132

    
1133
    '''
1134
        @brief  delete added symbol data
1135
    '''
1136
    def deleteSymbol(self, fileName):
1137
        ret = False
1138
        try:
1139
            dbPath = self.getCurrentProject().getPath() + "/db/ITI_PID.db"
1140
            conn = sqlite3.connect(dbPath)
1141
            cursor = conn.cursor()
1142
            sql = "DELETE FROM Symbol WHERE name = ?"
1143
            try:
1144
                cursor.execute(sql, (fileName,))
1145
                conn.commit()
1146
                ret = True
1147
            except Exception as ex:
1148
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1149
                ret = False
1150
        finally:
1151
            conn.close()
1152
            return (ret, fileName)
1153
        
1154
    '''
1155
        @brief  get symbol name
1156
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1157
    '''
1158
    def getSymbolByQuery(self, fieldName, param):
1159
        ret = None
1160

    
1161
        try:
1162
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
1163
            conn = sqlite3.connect(dbPath)
1164
            cursor = conn.cursor()
1165
            sql = 'SELECT * FROM Symbol WHERE ' + fieldName + ' = "' + param + '"'
1166
            try:
1167
                cursor.execute(sql)
1168
                rows = cursor.fetchall()
1169
                if rows is not None and len(rows) > 0:
1170
                    symbolTuple = rows[0]
1171
                    ret = symbol.SymbolBase(symbolTuple[1], symbolTuple[2], symbolTuple[3]
1172
                                            , symbolTuple[4], symbolTuple[5], symbolTuple[6], symbolTuple[7], symbolTuple[8]
1173
                                            , symbolTuple[9], symbolTuple[10], symbolTuple[11], symbolTuple[12], symbolTuple[13], symbolTuple[14], symbolTuple[0]) ## uid is last item
1174
                    #ret = symbol.SymbolBase(symbolTuple[1], symbolTuple[2], symbolTuple[3], symbolTuple[4]
1175
                    #                        , symbolTuple[5], symbolTuple[6], symbolTuple[7], symbolTuple[8], symbolTuple[9]
1176
                    #                        , symbolTuple[10], symbolTuple[11], symbolTuple[12], symbolTuple[13], symbolTuple[14], symbolTuple[0]) ## uid is last item
1177
            except Exception as ex:
1178
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1179
        finally:
1180
            conn.close()
1181

    
1182
        return ret
1183

    
1184
    '''
1185
        @brief  get symbol name list
1186
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1187
    '''
1188
    def getSymbolListByQuery(self, fieldName=None, param=None):
1189
        ret = []
1190

    
1191
        try:
1192
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1193
            conn = sqlite3.connect(dbPath)
1194
            cursor = conn.cursor()
1195
            if fieldName is not None and param is not None:
1196
                sql = 'SELECT * FROM Symbol WHERE ' + fieldName + ' = "' + param + '"'
1197
            else:
1198
                sql = 'SELECT * FROM Symbol'
1199
            try:
1200
                cursor.execute(sql)
1201
                rows = cursor.fetchall()
1202
                if rows is not None and len(rows) > 0:
1203
                    for symbolTuple in rows:
1204
                        sym = symbol.SymbolBase(symbolTuple[1], symbolTuple[2], symbolTuple[3], symbolTuple[4]
1205
                                                , symbolTuple[5], symbolTuple[6], symbolTuple[7], symbolTuple[8], symbolTuple[9]
1206
                                                , symbolTuple[10], symbolTuple[11], symbolTuple[12], symbolTuple[13], symbolTuple[14], symbolTuple[0]) ## uid is last item
1207
                        ret.append(sym)
1208
            except Exception as ex:
1209
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1210
        finally:
1211
            conn.close()
1212

    
1213
        return ret
1214

    
1215
    '''
1216
        @brief      get NominalDiameter
1217
        @author     humkyung
1218
        @date       2018.04.20
1219
        @history    humkyung 2018.04.24 read MetricStr column and set size unit
1220
                    kyouho 2018.07.04 forCheckLineNumber get only inch or metric
1221
                    kyouho 2018.07.16 edit query order by code
1222
    '''
1223
    def getNomialPipeSizeData(self, forCheckLineNumber = False, orderStr = "CODE"):
1224
        res = []
1225
        try:
1226
            configs = self.getConfigs('Line No', 'Size Unit')
1227
            sizeUnit = configs[0].value if 1 == len(configs) else 'Metric'
1228

    
1229
            # Creates or opens a file called mydb with a SQLite3 DB
1230
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1231
            conn = sqlite3.connect(dbPath)
1232
            # Get a cursor object
1233
            cursor = conn.cursor()
1234

    
1235
            sql = "select Code,Metric,Inch,InchStr,MetricStr from NominalDiameter ORDER BY {} ASC".format(orderStr)
1236
            cursor.execute(sql)
1237
            rows = cursor.fetchall()
1238
            for row in rows:
1239
                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])
1240
                pipeSize.sizeUnit = sizeUnit
1241
                if forCheckLineNumber:
1242
                    if sizeUnit == 'Inch' and pipeSize.inchStr:
1243
                        res.append(pipeSize.inchStr)
1244
                    elif sizeUnit == 'Metric' and pipeSize.metricStr:
1245
                        res.append(pipeSize.metricStr)
1246
                else:
1247
                    res.append(pipeSize)
1248
                
1249
        # Catch the exception
1250
        except Exception as ex:
1251
            # Roll back any change if something goes wrong
1252
            conn.rollback()
1253
            
1254
            from App import App 
1255
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1256
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1257
        finally:
1258
            # Close the db connection
1259
            conn.close()
1260

    
1261
        return res
1262

    
1263
    '''
1264
        @brief      insert NominalDiameter table
1265
        @author     kyouho
1266
        @date       2018.07.16
1267
    '''
1268
    def insertNomialPipeSize(self, pipeSizes):
1269
        try:
1270
            # Creates or opens a file called mydb with a SQLite3 DB
1271
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1272
            conn = sqlite3.connect(dbPath)
1273
            # Get a cursor object
1274
            cursor = conn.cursor()
1275
            sql = "INSERT INTO NominalDiameter(Code, Metric, Inch, InchStr, MetricStr) VALUES(?,?,?,?,?)"
1276
            for pipeSize in pipeSizes:
1277
                param = (pipeSize.code, pipeSize.metric, pipeSize.inch, pipeSize.inchStr, pipeSize.metricStr)
1278
                cursor.execute(sql, param)
1279
            conn.commit()
1280
            # Catch the exception
1281
        except Exception as ex:
1282
            # Roll back any change if something goes wrong
1283
            conn.rollback()
1284
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1285
        finally:
1286
            # Close the db connection
1287
            conn.close()
1288

    
1289

    
1290
    '''
1291
        @brief      delete NominalDiameter table
1292
        @author     kyouho
1293
        @date       2018.07.16
1294
    '''
1295
    def deleteNomialPipeSize(self):
1296
        try:
1297
            dbPath = self.getCurrentProject().getPath() + "/db/ITI_PID.db"
1298
            conn = sqlite3.connect(dbPath)
1299
            cursor = conn.cursor()
1300
            sql = "DELETE FROM NominalDiameter"
1301
            try:
1302
                cursor.execute(sql)
1303
                conn.commit()
1304
            except Exception as ex:
1305
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1306
        finally:
1307
            conn.close()
1308
    
1309

    
1310

    
1311

    
1312
    '''
1313
        @brief      convert inch to metric
1314
        @author     kyouho
1315
        @date       2018.07.09
1316
    '''
1317
    def convertInchToMetric(self, inch):
1318
        result = ''
1319
        try:
1320
            # Creates or opens a file called mydb with a SQLite3 DB
1321
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1322
            conn = sqlite3.connect(dbPath)
1323
            # Get a cursor object
1324
            cursor = conn.cursor()
1325
            
1326
            sql = "select MetricStr from NominalDiameter WHERE InchStr = ?"
1327
            param = (inch,)
1328
            cursor.execute(sql, param)
1329
            rows = cursor.fetchall()
1330

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

    
1342
        return result
1343

    
1344
    '''
1345
        @brief      get Color MaxUID
1346
        @author     kyouho
1347
        @date       2018.07.03
1348
    '''
1349
    def getMaxColorUID(self):
1350
        result = 0
1351

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

    
1359
            sql = "select MAX(UID) from Colors"
1360
            cursor.execute(sql)
1361
            rows = cursor.fetchall()
1362

    
1363
            result = rows[0][0]
1364
            # Catch the exception
1365
        except Exception as ex:
1366
            # Roll back any change if something goes wrong
1367
            conn.rollback()
1368
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1369
        finally:
1370
            # Close the db connection
1371
            conn.close()
1372

    
1373
        return result
1374

    
1375
    '''
1376
        @brief      insert Color property
1377
        @author     kyouho
1378
        @date       2018.07.09
1379
    '''
1380
    def setPropertyColor(self, _color):
1381
        try:
1382
            # Creates or opens a file called mydb with a SQLite3 DB
1383
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1384
            conn = sqlite3.connect(dbPath)
1385
            # Get a cursor object
1386
            cursor = conn.cursor()
1387
            sql = "INSERT INTO Colors(UID, RED, GREEN, BLUE, PROPERTY, VALUE) VALUES(?,?,?,?,?,?)"
1388
            param = (_color.index, _color.red, _color.green, _color.blue, _color._property, _color.value)
1389
            cursor.execute(sql, param)
1390
            conn.commit()
1391
            # Catch the exception
1392
        except Exception as ex:
1393
            # Roll back any change if something goes wrong
1394
            conn.rollback()
1395
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1396
        finally:
1397
            # Close the db connection
1398
            conn.close()
1399

    
1400
    '''
1401
        @brief      delete Color property
1402
        @author     kyouho
1403
        @date       2018.07.09
1404
    '''
1405
    def deletePropertyColor(self, property):
1406
        try:
1407
            # Creates or opens a file called mydb with a SQLite3 DB
1408
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1409
            conn = sqlite3.connect(dbPath)
1410
            # Get a cursor object
1411
            cursor = conn.cursor()
1412

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

    
1425
    '''
1426
        @brief      get Fluid Code
1427
        @author     kyouho
1428
        @date       2018.07.03
1429
        @history    kyouho 2018.07.04 kyouho 2018.07.04 forCheckLineNumber get only code
1430
    '''
1431
    def getFluidCodeData(self, forCheckLineNumber = False):
1432
        from FluidCodeData import FluidCodeData
1433
        result = []
1434

    
1435
        try:
1436
            # Creates or opens a file called mydb with a SQLite3 DB
1437
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1438
            conn = sqlite3.connect(dbPath)
1439
            # Get a cursor object
1440
            cursor = conn.cursor()
1441

    
1442
            sql = 'select uid, code, description from FluidCode order by length(code) DESC'
1443
            cursor.execute(sql)
1444
            rows = cursor.fetchall()
1445
            for row in rows:
1446
                data = FluidCodeData(row[0], row[1], row[2])
1447
                if forCheckLineNumber:
1448
                    result.append(data.code)
1449
                else:
1450
                    result.append(data)
1451
            # Catch the exception
1452
        except Exception as ex:
1453
            # Roll back any change if something goes wrong
1454
            conn.rollback()
1455
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1456
        finally:
1457
            # Close the db connection
1458
            conn.close()
1459

    
1460
        return result
1461

    
1462
    '''
1463
        @brief      get Symbol Attribute
1464
        @author     kyouho
1465
        @date       2018.07.18
1466
    '''
1467
    def checkAttribute(self, attr):
1468
        try:
1469
            # Creates or opens a file called mydb with a SQLite3 DB
1470
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1471
            conn = sqlite3.connect(dbPath)
1472
            # Get a cursor object
1473
            cursor = conn.cursor()
1474

    
1475
            sql = 'select attribute from SymbolAttribute where Attribute = ?'
1476
            param = (attr,)
1477
            cursor.execute(sql, param)
1478
            rows = cursor.fetchall()
1479
            if len(rows):
1480
                return True
1481
            else:
1482
                return False
1483
            # Catch the exception
1484
        except Exception as ex:
1485
            # Roll back any change if something goes wrong
1486
            conn.rollback()
1487
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1488
        finally:
1489
            # Close the db connection
1490
            conn.close()
1491

    
1492
        return False
1493

    
1494
    '''
1495
        @brief      get Symbol Attribute
1496
        @author     kyouho
1497
        @date       2018.07.18
1498
    '''
1499
    def getSymbolAttribute(self, _type):
1500
        result = []
1501

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

    
1509
            sql = 'select a.DisplayAttribute, a.Attribute, a.AttributeType from SymbolAttribute a inner join SymbolType t on a.SymbolType = t.id and t.type = ? order by attribute'
1510
            param = (_type,)
1511
            cursor.execute(sql, param)
1512
            rows = cursor.fetchall()
1513
            for row in rows:
1514
                result.append((row[0], row[1], row[2]))
1515
            # Catch the exception
1516
        except Exception as ex:
1517
            from App import App
1518

    
1519
            # Roll back any change if something goes wrong
1520
            conn.rollback()
1521

    
1522
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1523
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1524
        finally:
1525
            # Close the db connection
1526
            conn.close()
1527

    
1528
        return result
1529

    
1530
    '''
1531
        @brief      save symbol attributes
1532
        @author     humkyung
1533
        @date       2018.08.14
1534
    '''
1535
    def saveSymbolAttributes(self, type, attrs):
1536
        try:
1537
            # Creates or opens a file called mydb with a SQLite3 DB
1538
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1539
            conn = sqlite3.connect(dbPath)
1540
            # Get a cursor object
1541
            cursor = conn.cursor()
1542

    
1543
            sql = 'delete from SymbolAttribute where SymbolType = ?'
1544
            param = (type,)
1545
            cursor.execute(sql, param)
1546

    
1547
            for attr in attrs:
1548
                sql = 'insert into SymbolAttribute(SymbolType, Attribute) values(?,?)'
1549
                param = (type, attr)
1550
                cursor.execute(sql, param)
1551

    
1552
            conn.commit()
1553
            # Catch the exception
1554
        except Exception as ex:
1555
            # Roll back any change if something goes wrong
1556
            conn.rollback()
1557
            
1558
            from App import App 
1559
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1560
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1561
        finally:
1562
            # Close the db connection
1563
            conn.close()
1564

    
1565
    '''
1566
        @brief      get Code Table Data
1567
        @author     kyouho
1568
        @date       2018.07.10
1569
    '''
1570
    def getCodeTable(self, property, forCheckLineNumber = False):
1571
        result = []
1572
        try:
1573
            # Creates or opens a file called mydb with a SQLite3 DB
1574
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1575
            conn = sqlite3.connect(dbPath)
1576
            # Get a cursor object
1577
            cursor = conn.cursor()
1578

    
1579
            sql = 'select uid, code, description from {} order by length(code) DESC'.format(property)
1580
            cursor.execute(sql)
1581
            rows = cursor.fetchall()
1582
            for row in rows:
1583
                if forCheckLineNumber:
1584
                    data = row[1]
1585
                else:
1586
                    data = (row[0], row[1], row[2])
1587
                result.append(data)
1588
            # Catch the exception
1589
        except Exception as ex:
1590
            # Roll back any change if something goes wrong
1591
            conn.rollback()
1592
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1593
        finally:
1594
            # Close the db connection
1595
            conn.close()
1596

    
1597
        return result
1598

    
1599
    '''
1600
        @brief      Set Common Code Data
1601
        @author     kyouho
1602
        @date       2018.07.12
1603
    '''
1604
    def setCommonCodeData(self, tableName, datas):
1605
        try:
1606
            # Creates or opens a file called mydb with a SQLite3 DB
1607
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1608
            conn = sqlite3.connect(dbPath)
1609
            # Get a cursor object
1610
            cursor = conn.cursor()
1611

    
1612
            for data in datas:
1613
                uid = data[0]
1614
                if not uid:
1615
                    sql = "insert or replace into {}(UID, CODE, DESCRIPTION) values(lower(hex(randomblob(16))), ?, ?)".format(tableName)
1616
                    param = (data[1], data[2])
1617
                else:
1618
                    sql = "update {} SET CODE=?, DESCRIPTION=? WHERE UID = ?".format(tableName)
1619
                    param = (data[1], data[2], data[0])
1620
                cursor.execute(sql, param)
1621

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

    
1633
    '''
1634
        @brief      Set Common Code Data
1635
        @author     kyouho
1636
        @date       2018.07.12
1637
    '''
1638
    def deleteCommonCodeData(self, datas):
1639
        try:
1640
            # Creates or opens a file called mydb with a SQLite3 DB
1641
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1642
            conn = sqlite3.connect(dbPath)
1643
            # Get a cursor object
1644
            cursor = conn.cursor()
1645

    
1646
            for data in datas:
1647
                uid = data[0]
1648
                tableName = data[1]
1649

    
1650
                if uid:
1651
                    sql = "delete from {} where UID = ?".format(tableName)
1652
                    param = (uid,)
1653
                    cursor.execute(sql, param)
1654

    
1655
                cursor.execute(sql, param)
1656

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

    
1668
    '''
1669
        @brief      delete data list
1670
        @author     kyouho
1671
        @date       2018.08.16
1672
    '''
1673
    def deleteDataList(self, tableName, UID):
1674
        try:
1675
            # Creates or opens a file called mydb with a SQLite3 DB
1676
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1677
            conn = sqlite3.connect(dbPath)
1678
            # Get a cursor object
1679
            cursor = conn.cursor()
1680

    
1681
            sql = 'delete from {} where UID = {}'.format(tableName, UID)
1682
            
1683
            cursor.execute(sql)
1684

    
1685
            conn.commit()
1686

    
1687
        # Catch the exception
1688
        except Exception as ex:
1689
            # Roll back any change if something goes wrong
1690
            conn.rollback()
1691
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1692
        finally:
1693
            # Close the db connection
1694
            conn.close()
1695

    
1696

    
1697
    '''
1698
        @brief      get line documentName list
1699
        @author     kyouho
1700
        @date       2018.08.13
1701
    '''
1702
    def getLineDocumentNameList(self):
1703
        result = []
1704

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

    
1712
            sql = 'select DISTINCT(PNID_NO) from LINE_DATA_LIST'
1713

    
1714
            cursor.execute(sql)
1715
            rows = cursor.fetchall()
1716
            for row in rows:
1717
                result.append(row[0])
1718
        # Catch the exception
1719
        except Exception as ex:
1720
            # Roll back any change if something goes wrong
1721
            conn.rollback()
1722
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1723
        finally:
1724
            # Close the db connection
1725
            conn.close()
1726

    
1727
        return result
1728

    
1729
    '''
1730
        @brief      get line documentName list
1731
        @author     kyouho
1732
        @date       2018.08.14
1733
    '''
1734
    def getEquipDocumentNameList(self):
1735
        result = []
1736

    
1737
        try:
1738
            # Creates or opens a file called mydb with a SQLite3 DB
1739
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1740
            conn = sqlite3.connect(dbPath)
1741
            # Get a cursor object
1742
            cursor = conn.cursor()
1743

    
1744
            sql = 'select DISTINCT(PNID_NO) from EQUIPMENT_DATA_LIST'
1745

    
1746
            cursor.execute(sql)
1747
            rows = cursor.fetchall()
1748
            for row in rows:
1749
                result.append(row[0])
1750
        # Catch the exception
1751
        except Exception as ex:
1752
            # Roll back any change if something goes wrong
1753
            conn.rollback()
1754
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1755
        finally:
1756
            # Close the db connection
1757
            conn.close()
1758

    
1759
        return result
1760

    
1761

    
1762
    '''
1763
        @brief      get line data list
1764
        @author     kyouho
1765
        @date       2018.08.13
1766
    '''
1767
    def getLineDataList(self, docName = None):
1768
        result = []
1769

    
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
            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'
1778
            if docName is not None:
1779
                sql += " where PNID_NO = '{}'".format(docName)
1780

    
1781
            cursor.execute(sql)
1782
            #columnName = list(map(lambda x: x[0].upper(), cursor.description))
1783
            rows = cursor.fetchall()
1784
            for row in rows:
1785
                data = []
1786
                for index in range(len(cursor.description)):
1787
                    data.append(row[index])
1788
                result.append(data)
1789
        # Catch the exception
1790
        except Exception as ex:
1791
            # Roll back any change if something goes wrong
1792
            conn.rollback()
1793
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1794
        finally:
1795
            # Close the db connection
1796
            conn.close()
1797

    
1798
        return result
1799

    
1800
    '''
1801
        @brief      set line data list
1802
        @author     kyouho
1803
        @date       2018.08.13
1804
    '''
1805
    def setLineDataList(self, dataLists):
1806
        try:
1807
            # Creates or opens a file called mydb with a SQLite3 DB
1808
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1809
            conn = sqlite3.connect(dbPath)
1810
            # Get a cursor object
1811
            cursor = conn.cursor()
1812
            
1813
            for data in dataLists:
1814
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
1815
                param = tuple(data)
1816
                cursor.execute(sql, param)
1817

    
1818
            conn.commit()
1819

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

    
1829
    '''
1830
        @brief      delete line data list
1831
        @author     kyouho
1832
        @date       2018.08.13
1833
    '''
1834
    def deleteLineDataList(self, removeUID):
1835
        try:
1836
            # Creates or opens a file called mydb with a SQLite3 DB
1837
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1838
            conn = sqlite3.connect(dbPath)
1839
            # Get a cursor object
1840
            cursor = conn.cursor()
1841
            
1842
            for uid in removeUID:
1843
                sql = "delete from LINE_DATA_LIST where uid = '{}'".format(uid)
1844
                cursor.execute(sql)
1845

    
1846
            conn.commit()
1847

    
1848
        # Catch the exception
1849
        except Exception as ex:
1850
            # Roll back any change if something goes wrong
1851
            conn.rollback()
1852
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1853
        finally:
1854
            # Close the db connection
1855
            conn.close()
1856

    
1857
    '''
1858
        @brief      delete line data list
1859
        @author     kyouho
1860
        @date       2018.08.13
1861
    '''
1862
    def deleteLineDataList_LineNo(self, removeUID):
1863
        try:
1864
            # Creates or opens a file called mydb with a SQLite3 DB
1865
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1866
            conn = sqlite3.connect(dbPath)
1867
            # Get a cursor object
1868
            cursor = conn.cursor()
1869
            
1870
            for uid in removeUID:
1871
                sql = "delete from LINE_DATA_LIST where LINE_NO = ?"
1872
                param = (uid,)
1873
                cursor.execute(sql, param)
1874

    
1875
            conn.commit()
1876

    
1877
        # Catch the exception
1878
        except Exception as ex:
1879
            # Roll back any change if something goes wrong
1880
            conn.rollback()
1881
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1882
        finally:
1883
            # Close the db connection
1884
            conn.close()
1885

    
1886
    '''
1887
        @brief      delete equip data list
1888
        @author     kyouho
1889
        @date       2018.08.14
1890
    '''
1891
    def deleteEquipDataList(self, removeUID):
1892
        try:
1893
            # Creates or opens a file called mydb with a SQLite3 DB
1894
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1895
            conn = sqlite3.connect(dbPath)
1896
            # Get a cursor object
1897
            cursor = conn.cursor()
1898
            
1899
            for uid in removeUID:
1900
                sql = "delete from EQUIPMENT_DATA_LIST where uid = '{}'".format(uid)
1901
                cursor.execute(sql)
1902

    
1903
            conn.commit()
1904

    
1905
        # Catch the exception
1906
        except Exception as ex:
1907
            # Roll back any change if something goes wrong
1908
            conn.rollback()
1909
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1910
        finally:
1911
            # Close the db connection
1912
            conn.close()
1913

    
1914
    '''
1915
        @brief      delete inst data list
1916
        @author     kyouho
1917
        @date       2018.08.14
1918
    '''
1919
    def deleteInstDataList(self, removeUID):
1920
        try:
1921
            # Creates or opens a file called mydb with a SQLite3 DB
1922
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1923
            conn = sqlite3.connect(dbPath)
1924
            # Get a cursor object
1925
            cursor = conn.cursor()
1926
            
1927
            for uid in removeUID:
1928
                sql = "delete from INSTRUMENT_DATA_LIST where uid = '{}'".format(uid)
1929
                cursor.execute(sql)
1930

    
1931
            conn.commit()
1932

    
1933
        # Catch the exception
1934
        except Exception as ex:
1935
            # Roll back any change if something goes wrong
1936
            conn.rollback()
1937
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1938
        finally:
1939
            # Close the db connection
1940
            conn.close()
1941

    
1942
    '''
1943
        @brief      get equipment data list
1944
        @author     humkyung
1945
        @date       2018.05.03
1946
    '''
1947
    def getEquipmentDataList(self, docName = None):
1948
        result = []
1949
        try:
1950
            # Creates or opens a file called mydb with a SQLite3 DB
1951
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1952
            conn = sqlite3.connect(dbPath)
1953
            # Get a cursor object
1954
            cursor = conn.cursor()
1955

    
1956
            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'
1957
            if docName is not None:
1958
                sql += " where PNID_NO = '{}'".format(docName)
1959

    
1960
            cursor.execute(sql)
1961
            rows = cursor.fetchall()
1962
            for row in rows:
1963
                data = []
1964
                for index in range(len(cursor.description)): 
1965
                    data.append(row[index])
1966
                result.append(data)
1967
        # Catch the exception
1968
        except Exception as ex:
1969
            from App import App 
1970

    
1971
            # Roll back any change if something goes wrong
1972
            conn.rollback()
1973
            
1974
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1975
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1976
        finally:
1977
            # Close the db connection
1978
            conn.close()
1979

    
1980
        return result
1981

    
1982
    '''
1983
        @brief      get instrument data list
1984
        @author     kyouho
1985
        @date       2018.08.14
1986
    '''
1987
    def getInstrumentDataList(self, docName = None):
1988
        result = []
1989
        try:
1990
            # Creates or opens a file called mydb with a SQLite3 DB
1991
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
1992
            conn = sqlite3.connect(dbPath)
1993
            # Get a cursor object
1994
            cursor = conn.cursor()
1995

    
1996
            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'
1997
            if docName is not None:
1998
                sql += " where PNID_NO = '{}'".format(docName)
1999

    
2000
            cursor.execute(sql)
2001
            rows = cursor.fetchall()
2002
            for row in rows:
2003
                data = []
2004
                for index in range(len(cursor.description)): 
2005
                    data.append(row[index])
2006
                result.append(data)
2007
        # Catch the exception
2008
        except Exception as ex:
2009
            # Roll back any change if something goes wrong
2010
            conn.rollback()
2011
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2012
        finally:
2013
            # Close the db connection
2014
            conn.close()
2015

    
2016
        return result
2017

    
2018
    '''
2019
        @brief      set equipment data list
2020
        @author     humkyung
2021
        @date       2018.05.03
2022
    '''
2023
    def setEquipmentDataList(self, dataList):
2024
        try:
2025
            # Creates or opens a file called mydb with a SQLite3 DB
2026
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2027
            conn = sqlite3.connect(dbPath)
2028
            # Get a cursor object
2029
            cursor = conn.cursor()
2030

    
2031
            for data in dataList:
2032
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2033
                param = tuple(data)
2034
                cursor.execute(sql, param)
2035
            conn.commit()
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      set instrumnet data list
2047
        @author     kyoyho
2048
        @date       2018.08.14
2049
    '''
2050
    def setInstrumentDataList(self, dataList):
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 data in dataList:
2059
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2060
                param = tuple(data)
2061
                cursor.execute(sql, param)
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 IsOriginDetect ComboBox Items
2075
    '''
2076
    def getIsOriginDetectComboBoxItems(self):
2077
        return [("원본 도면", 0), ("텍스트 제거 도면", 1)]
2078

    
2079
    '''
2080
        @brief  get IsOriginDetect ComboBox Items
2081
    '''
2082
    def getOcrOptionComboBoxItems(self):
2083
        return [("OCR 미적용", 0), ("일반 심볼", 1), ("Instrument 계통", 2)]
2084
    
2085
    '''
2086
        @brief      Return Symbol Type Items
2087
        @author     Jeongwoo
2088
        @date       18.04.20
2089
        @history    18.05.08    Jeongwoo type index changed
2090
    '''
2091
    def getSymbolTypeList(self):
2092
        symbolTypeList = []
2093

    
2094
        try:
2095
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
2096

    
2097
            conn = sqlite3.connect(dbPath)
2098
            cursor = conn.cursor()
2099
            sql = 'SELECT * FROM SymbolType ORDER BY type ASC'
2100
            try:
2101
                cursor.execute(sql)
2102
                rows = cursor.fetchall()
2103
                for row in rows:
2104
                    symbolTypeList.append((row[0], row[1], row[2])) # UID, category, type
2105
            except Exception as ex:
2106
                from App import App
2107

    
2108
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2109
                App.mainWin().addMessage(MessageType.Error, message)
2110
        finally:
2111
            conn.close()
2112

    
2113
        return symbolTypeList
2114

    
2115
    '''
2116
        @brief      Get Symbol Category by Symbol Type
2117
        @author     Jeongwoo
2118
        @date       2018.05.09
2119
    '''
2120
    def getSymbolCategoryByType(self, type):
2121
        category = None
2122
        try:
2123
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), "ITI_PID.db")
2124
            conn = sqlite3.connect(dbPath)
2125
            cursor = conn.cursor()
2126
            sql = 'SELECT category FROM SymbolType WHERE type = "' + type + '"'
2127
            cursor.execute(sql)
2128
            rows = cursor.fetchall()
2129
            if rows is not None and len(rows) > 0:
2130
                category = rows[0][0]
2131
        except Exception as ex:
2132
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2133
        finally:
2134
            conn.close()
2135

    
2136
        return category
2137

    
2138
    '''
2139
        @brief      Check Symbol Type is included in 'Equipment' Category
2140
        @author     Jeongwoo
2141
        @date       2018.05.09
2142
    '''
2143
    def isEquipmentType(self, type):
2144
        category = self.getSymbolCategoryByType(type)
2145
        return (category is not None and category == 'Equipment')
2146

    
2147
    '''
2148
        @brief      Return Symbol Type Items with "None"
2149
        @author     Jeongwoo
2150
        @date       18.04.06
2151
        @history    Seperate SymbolTypeList and "None"
2152
    '''
2153
    def getSymbolTypeComboBoxItems(self):
2154
        symbolTypeList = self.getSymbolTypeList()
2155
        symbolTypeList.insert(0, ('None', 'None', 'None'))
2156

    
2157
        return symbolTypeList
2158

    
2159
    '''
2160
        @brief  get Base Symbol ComboBox Items
2161
    '''
2162
    def getBaseSymbolComboBoxItems(self, type = None):
2163
        bsymbolNameList = self.getSymbolNameListByType(type)
2164
        bsymbolNameList.sort()
2165
        bsymbolNameList.insert(0, "None")
2166
        return bsymbolNameList
2167

    
2168
    '''
2169
        @brief  get Additional Symbol ComboBox Items
2170
    '''
2171
    def getAdditionalSymbolComboBoxItems(self):
2172
        asymbolNameList = self.getSymbolNameList()
2173
        asymbolNameList.sort()
2174
        asymbolNameList.insert(0, "None")
2175
        return asymbolNameList
2176

    
2177
    '''
2178
        @brief  get Additional Symbol's default direction ComboBox Items
2179
    '''
2180
    def getDefaultSymbolDirectionComboBoxItems(self):
2181
        return [("UP", 0), ("DOWN", 2), ("LEFT", 3), ("RIGHT", 1)]
2182
    
2183
    '''
2184
        @brief  getter of activeDrawing
2185
        @author humkyung
2186
        @date   2018.07.07
2187
    '''
2188
    @property
2189
    def activeDrawing(self):
2190
        return self._activeDrawing
2191

    
2192
    '''
2193
        @brief  setter of activeDrawing
2194
        @author humkyung
2195
        @date   2018.07.07
2196
    '''
2197
    @activeDrawing.setter
2198
    def activeDrawing(self, value):
2199
        self._activeDrawing = value
클립보드 이미지 추가 (최대 크기: 500 MB)