프로젝트

일반

사용자정보

통계
| 개정판:

hytos / HYTOS / HYTOS / AppDocData.py @ 2ab99cff

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

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

    
4
import sys
5
import os
6
import sqlite3
7
import datetime
8
from enum import Enum
9

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

    
19
from App import App
20
from SingletonInstance import SingletonInstane
21
import symbol
22
from NominalPipeSize import NominalPipeSize
23

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

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

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

    
54
    '''
55
        @brief  return size value string
56
        @author humkyung
57
        @date   2018.04.24
58
    '''
59
    def sizeValue(self):
60
        return self.inchStr if 'Inch' == self.sizeUnit else self.metricStr
61

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

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

    
81
class AppDocData(SingletonInstane):
82
    DATABASE = App.NAME + '.db'
83

    
84
    def __init__(self):
85
        from DisplayColors import DisplayColors
86

    
87
        self._imgFilePath = None
88
        self.imgName = None
89
        self.imgWidth = 0
90
        self.imgHeight = 0
91
        self._OCRData = None
92

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

    
110
        self.configTable = None
111

    
112
    def clearItemList(self, trim):
113
        '''
114
            @brief      clear item list
115
            @author     euisung
116
            @date       2018.11.28
117
        '''
118
        self.equipments.clear()
119
        self.symbols.clear()
120
        self.lineNos.clear()
121
        self.texts.clear()
122
        self.lines.clear()
123
        self.unknowns.clear()
124
        self.lineIndicators.clear()
125
        if trim:
126
            self.tracerLineNos.clear()
127

    
128
    '''
129
        @brief      clear
130
        @author     humkyung
131
        @date       2018.09.06
132
    '''
133
    def clear(self):
134
        self._imgFilePath = None
135
        self.imgName = None
136
        self.imgWidth = 0
137
        self.imgHeight = 0
138

    
139
        self._areas.clear()
140
        self.equipments.clear()
141
        self.lineNos.clear()
142
        self.lines.clear()
143
        self.texts.clear()
144
        self.symbols.clear()
145
        self.unknowns.clear()
146
        self.tracerLineNos.clear()
147
        self.lineIndicators.clear()
148
        self._colors = None
149
        self._lineNoProperties = None
150
        self._lineTypeConfigs = None
151
        self._activeDrawing = None
152
        self._titleBlockProperties = None
153

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

    
171
        return drawingFileList
172

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

    
189
        return drawingFileList
190

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

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

    
209
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
210
        app_database = os.path.join(path, 'App.db')
211
        return app_database 
212

    
213
    '''
214
        @brief  getter of colors 
215
        @author humkyung
216
        @date   2018.06.18
217
    '''
218
    @property
219
    def colors(self):
220
        import random
221

    
222
        if self._colors is None or self._colors == []:
223
            self._colors = []
224
            try:
225
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath() , AppDocData.DATABASE)
226

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

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

    
245
        return self._colors.pop(random.randrange(0, len(self._colors)))
246

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

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

    
265
    '''
266
        @brief  getter of line type configs
267
        @author humkyung
268
        @date   2018.06.28
269
    '''
270
    @property
271
    def lineTypeConfigs(self):
272
        from PyQt5.QtCore import Qt
273

    
274
        if self._lineTypeConfigs is None:
275
            self._lineTypeConfigs = []
276

    
277
            styleMap = [('SolidLine', Qt.SolidLine), ('DashLine', Qt.DashLine), ('DotLine', Qt.DotLine), ('DashDotLine', Qt.DashDotLine), 
278
                ('DashDotDotLine', Qt.DashDotDotLine), ('CustomDashLine', Qt.CustomDashLine)]
279

    
280
            configs = self.getConfigs('LineTypes')
281
            for config in configs:
282
                color, width, _style, transparent = config.value.split(',')
283
                matches = [param for param in styleMap if param[0] == _style]
284
                style = matches[0][1] if matches else Qt.SolidLine
285
                self._lineTypeConfigs.append((config.key, color, int(width), style, float(transparent)))
286
        
287
        return self._lineTypeConfigs
288

    
289
    '''
290
        @brief  setter of line type configs
291
        @author humkyung
292
        @date   2018.06.28
293
    '''
294
    @lineTypeConfigs.setter
295
    def lineTypeConfigs(self, value):
296
        self._lineTypeConfigs = value
297

    
298
    @property
299
    def drain_size(self):
300
        """ getter of drain_size """
301
        if not hasattr(self, '_drain_size') or not self._drain_size:
302
            configs = self.getConfigs('Drain Size Rule', 'Size')
303
            self._drain_size = configs[0].value if configs else '1"'
304

    
305
        return self._drain_size
306

    
307
    @drain_size.setter
308
    def drain_size(self, value):
309
        """ setter of drain_size """
310
        self._drain_size = value
311

    
312
    '''
313
        @brief  get line type config of given line type
314
        @author humkyung
315
        @date   2018.06.28
316
    '''
317
    def getLineTypeConfig(self, lineType):
318
        from PyQt5.QtCore import Qt
319

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

    
323
    def setCurrentPidSource(self, image):
324
        self.imgWidth, self.imgHeight = image.size
325

    
326
        self.currentPidSource = Source(image)
327

    
328
    def getCurrentPidSource(self):
329
        return self.currentPidSource
330

    
331
    '''
332
        @brief      Check if data exists or not
333
        @author     Jeongwoo
334
        @date       2018.05.03
335
    '''
336
    def isExistData(self, fieldName, data):
337
        rows = None
338
        try:
339
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
340

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

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

    
388
    '''
389
        @brief      Insert new symbol into Symbol Table, Moved from SG_DbHelper
390
        @author     Jeongwoo
391
        @date       2018.05.03
392
    '''
393
    def insertSymbol(self, symbol):
394
        isAdded = False
395
        try:
396
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
397
            conn = sqlite3.connect(dbPath)
398
            
399
            INSERT_SYMBOL_SQL = """
400
                INSERT INTO Symbol(name, SymbolType_UID, threshold, minMatchPoint, isDetectOrigin, rotationCount, ocrOption, isContainChild, originalPoint, connectionPoint, baseSymbol, additionalSymbol, isExceptDetect, hasInstrumentLabel, width, height, flip) 
401
                VALUES(?, (select UID from SymbolType where Type=?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
402
            """
403

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

    
423
    '''
424
        @brief      Update symbol in Symbol Table, Moved from SG_DbHelper
425
        @author     Jeongwoo
426
        @date       2018.05.03
427
    '''
428
    def updateSymbol(self, symbol):
429
        isUpdated = False
430
        try:
431
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
432
            conn = sqlite3.connect(dbPath)
433
            
434
            UPDATE_SYMBOL_SQL = """
435
                UPDATE Symbols
436
                   SET name = ?
437
                     , originalPoint = ?
438
                     , connectionPoint = ?
439
                 WHERE uid = ?
440
            """
441
            
442
            cursor = conn.cursor()
443
            query = (symbol.getName(), symbol.getOriginalPoint(), symbol.getConnectionPoint(), symbol.getUid())
444
            cursor.execute(UPDATE_SYMBOL_SQL, query)
445
            conn.commit()
446
            isUpdated = True
447
        # Catch the exception
448
        except Exception as ex:
449
            # Roll back any change if something goes wrong
450
            conn.rollback()
451
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
452
        finally:
453
            conn.close()
454
            return (isUpdated, symbol.getType(), symbol.getName(), symbol.getPath())
455

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

    
465
        try:
466
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
467

    
468
            conn = sqlite3.connect(dbPath)
469
            cursor = conn.cursor()
470
            #sql = """SELECT a.UID,a.Name,b.Type,a.Threshold,a.MinMatchPoint,a.IsDetectOrigin,a.RotationCount,a.OCROption,a.IsContainChild,a.OriginalPoint,a.ConnectionPoint,
471
            #        a.BaseSymbol,a.AdditionalSymbol,a.IsExceptDetect,a.HasInstrumentLabel,a.flip FROM Symbol a inner join SymbolType b on a.SymbolType_UID=b.UID WHERE a.IsExceptDetect = 0 order by width * height desc"""
472

    
473
            sql = """select s.UID
474
                          , s.Name
475
                          , t.Category
476
                          , t.Type
477
                          , s.OriginalPoint
478
                          , s.ConnectionPoint
479
                       from Symbols s 
480
                      inner join SymbolType t
481
                         on s.SymbolType_UID = t.UID"""
482

    
483
            try:
484
                cursor.execute(sql)
485
                rows = cursor.fetchall()
486
                for row in rows:
487
                    sym = symbol.SymbolBase(row[0], row[1], row[2], row[3], row[4], row[5])
488
                    targetSymbolList.append(sym)
489
            except Exception as ex:
490
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
491
        finally:
492
            conn.close()
493

    
494
        return targetSymbolList
495

    
496
    '''
497
        @brief  build application database
498
        @author humkyung
499
        @date   2018.04.20
500
    '''
501
    def buildAppDatabase(self):
502
        try:
503
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
504
            appDatabaseFilePath = os.path.join(path, 'App.db')
505

    
506
            # Creates or opens a file called mydb with a SQLite3 DB
507
            conn = sqlite3.connect(appDatabaseFilePath)
508
            # Get a cursor object
509
            cursor = conn.cursor()
510

    
511
            sqlFiles = ['App.Configuration.sql', 'App.Styles.sql']
512
            for sqlFile in sqlFiles:
513
                filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', sqlFile)
514
                try:
515
                    file = QFile(filePath)
516
                    file.open(QFile.ReadOnly)
517
                    sql = file.readAll()
518
                    sql = str(sql, encoding='utf8')
519
                    cursor.executescript(sql)
520
                finally:
521
                    file.close()
522
            conn.commit()
523
        # Catch the exception
524
        except Exception as ex:
525
            # Roll back any change if something goes wrong
526
            conn.rollback()
527
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
528
        finally:
529
            # Close the db connection
530
            conn.close()
531

    
532
        configs = [Config('app', 'mode', 'advanced'), Config('app', 'error origin point', '51,72')]
533
        self.saveAppConfigs(configs)
534

    
535
    '''
536
        @brief  load app style
537
        @author humkyung
538
        @date   2018.04.20
539
    '''
540
    def loadAppStyle(self):
541
        style = 'Fusion'
542

    
543
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
544
        if not os.path.exists(path): os.makedirs(path)
545

    
546
        self.buildAppDatabase()
547
        try:
548
            appDatabaseFilePath = os.path.join(path, 'App.db')
549
            # Creates or opens a file called mydb with a SQLite3 DB
550
            conn = sqlite3.connect(appDatabaseFilePath)
551
            # Get a cursor object
552
            cursor = conn.cursor()
553

    
554
            sql = "select Value from Configuration where Section='App' and Key='Style'" 
555
            cursor.execute(sql)
556
            rows = cursor.fetchall()
557
            style = rows[0][0] if 1 == len(rows) else 'Fusion'
558
        # Catch the exception
559
        except Exception as ex:
560
            # Roll back any change if something goes wrong
561
            conn.rollback()
562
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
563
        finally:
564
            # Close the db connection
565
            conn.close()
566

    
567
        return style
568

    
569
    '''
570
        @brief  load app styles and then return a list
571
        @author humkyung
572
        @date   2018.04.20
573
    '''
574
    def loadAppStyles(self):
575
        styles = []
576

    
577
        try:
578
            self.buildAppDatabase()
579

    
580
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
581
            appDatabaseFilePath = os.path.join(path, 'App.db')
582

    
583
            # Creates or opens a file called mydb with a SQLite3 DB
584
            conn = sqlite3.connect(appDatabaseFilePath)
585
            # Get a cursor object
586
            cursor = conn.cursor()
587

    
588
            sql = 'select UID,Value from Styles'
589
            cursor.execute(sql)
590
            rows = cursor.fetchall()
591
            for row in rows: styles.append(row[1])
592
            if 0 == len(rows): rows.append('fusion')
593
        # Catch the exception
594
        except Exception as ex:
595
            # Roll back any change if something goes wrong
596
            conn.rollback()
597
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
598
        finally:
599
            # Close the db connection
600
            conn.close()
601

    
602
        return styles
603

    
604
    '''
605
        @brief  Set current Project
606
        @history    2018.06.27  Jeongwoo    If DB file is not, copy DB file from ProgramData
607
    '''
608
    def setCurrentProject(self, project):
609
        self.project = project
610
        self.makeChildDir()
611
        self.copySvg()
612
        try:
613
            # Creates or opens a file called mydb with a SQLite3 DB
614
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath() , App.NAME + '.db')
615
            
616
            if not os.path.isfile(dbPath):
617
                templatePath = self.getTemplateDbPath()
618
                templateFile = QFile(templatePath)
619
                templateFile.copy(dbPath)
620
            else:
621
                try:
622
                    conn = sqlite3.connect(dbPath)
623
                    # Get a cursor object
624
                    cursor = conn.cursor()
625

    
626
                    fileNames = os.listdir(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts'))
627
                    for fileName in fileNames:
628
                        if fileName.endswith(".sql") and (1 == len(os.path.splitext(fileName)[0].split('.'))):
629
                            try:
630
                                file = QFile(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', fileName))
631
                                file.open(QFile.ReadOnly)
632
                                sql = file.readAll()
633
                                sql = str(sql, encoding='utf8')
634
                                cursor.executescript(sql)
635
                            finally:
636
                                file.close()
637
                    conn.commit()
638
                except Exception as ex:
639
                    print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
640
                finally:
641
                    conn.close()
642
        # Catch the exception
643
        except Exception as ex:
644
            # Roll back any change if something goes wrong
645
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
646
        finally:
647
            pass
648

    
649
    '''
650
        @brief      Copy Svg
651
        @author     yeonjin
652
        @date       19.07.31
653
    '''
654
    def copySvg(self):
655
        from shutil import copyfile
656

    
657
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
658
        sourceDir = os.path.join(path, 'svg')
659
        if not os.path.exists(sourceDir): 
660
            return
661
        
662
        project = AppDocData.instance().getCurrentProject()
663
        targetDir = project.getSvgFilePath()
664

    
665
        for root, dirs, files in os.walk(sourceDir):
666
            for file in files: # loops through directories and files
667
                sourceFile = os.path.join(root, file)
668
                targetFile = sourceFile.replace(sourceDir, targetDir)
669
                if not os.path.exists(targetFile):
670
                    dir = os.path.dirname(targetFile)
671
                    if not os.path.exists(dir):
672
                        os.makedirs(dir)
673

    
674
                    copyfile(sourceFile, targetFile)
675

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

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

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

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

    
756
    def getErrorItemSvgPath(self):
757
        '''
758
            @brief  return error item svg path
759
            @author euisung
760
            @date   2019.04.02
761
        '''
762
        return os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME, 'Explode.svg')
763

    
764
    def updateTitleBlockProperties(self, titleBlockProps):
765
        '''
766
            @brief  update title block properties
767
            @author euisung
768
            @date   2018.11.09
769
        '''
770
        try:
771
            for titleBlockProp in titleBlockProps:
772
                titleBlockProp[1] = self.imgName + '!@!' + titleBlockProp[1]
773
            originTitleBlockProps = self.getTitleBlockProperties()
774
            deletedTitleBlockProps = []
775
            for originTitleBlockProp in originTitleBlockProps:
776
                for titleBlockProp in titleBlockProps:
777
                    # uid compare for determine delete props
778
                    if originTitleBlockProp[0] == titleBlockProp[0]:
779
                        break
780
                deletedTitleBlockProps.append(originTitleBlockProp[0])
781
            
782
            # Creates or opens a file called mydb with a SQLite3 DB
783
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
784
            conn = sqlite3.connect(dbPath)
785
            # Get a cursor object
786
            cursor = conn.cursor()
787

    
788
            for deletedTitleBlockProp in deletedTitleBlockProps:
789
                sql = "delete from TitleBlockProperties where UID='{}'".format(deletedTitleBlockProp)
790
                cursor.execute(sql)
791

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

    
806
        self._titleBlockProperties = None
807
    
808
    def getTitleBlockProperties(self):
809
        '''
810
            @brief  return title block properties
811
            @author euisung
812
            @date   2018.11.09
813
        '''
814
        res = None
815
        if True:#self._titleBlockProperties is None:
816
            try:
817
                self._titleBlockProperties = []
818

    
819
                # Creates or opens a file called mydb with a SQLite3 DB
820
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
821
                db = sqlite3.connect(dbPath)
822
                # Get a cursor object
823
                cursor = db.cursor()
824

    
825
                sql = "select UID, Name, AREA from TitleBlockProperties" 
826
                cursor.execute(sql)
827
                rows = cursor.fetchall()
828
                for row in rows:
829
                    if row[1].split('!@!')[0] != self.imgName:
830
                        continue
831
                    else:
832
                        attr = []
833
                        attr.append(row[0]) # uid
834
                        attr.append(row[1].split('!@!')[1]) # name
835
                        attr.append(row[2]) # area
836
                        self._titleBlockProperties.append(attr)
837
                
838
                res = self._titleBlockProperties
839
            # Catch the exception
840
            except Exception as ex:
841
                # Roll back any change if something goes wrong
842
                db.rollback()
843
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
844
            finally:
845
                # Close the db connection
846
                db.close()
847
        else:
848
            res = self._titleBlockProperties
849

    
850
        return res
851

    
852
    def clearLineNoProperties(self):
853
        self._lineNoProperties = None
854

    
855
    '''
856
        @brief  return line properties
857
        @author humkyung
858
        @date   2018.04.09
859
    '''
860
    def getLineProperties(self):
861
        from SymbolAttr import SymbolAttr
862

    
863
        res = None
864
        if self._lineNoProperties is None:
865
            try:
866
                self._lineNoProperties = []
867

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

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

    
898
        return res
899

    
900
    '''
901
        @brief  return line properties
902
        @author humkyung
903
        @date   2018.04.09
904
    '''
905
    def getLinePropertiesByUID(self, UID):
906
        from SymbolAttr import SymbolAttr
907

    
908
        res = []
909
        try:
910
            # Creates or opens a file called mydb with a SQLite3 DB
911
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
912
            db = sqlite3.connect(dbPath)
913
            # Get a cursor object
914
            cursor = db.cursor()
915

    
916
            sql = "select UID, Name, DisplayName, Type, LimitNumber, [index] from LineProperties where uid = '{}'".format(UID)
917
            cursor.execute(sql)
918
            rows = cursor.fetchall()
919
            for row in rows:
920
                attr = SymbolAttr()
921
                attr.UID = row[0]
922
                attr.Attribute = row[1]
923
                attr.DisplayAttribute = row[2]
924
                attr.AttributeType = row[3]
925
                attr.Length = row[4]
926
                res.append(attr)
927
        # Catch the exception
928
        except Exception as ex:
929
            # Roll back any change if something goes wrong
930
            db.rollback()
931
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
932
        finally:
933
            # Close the db connection
934
            db.close()
935

    
936
        return res
937

    
938
    '''
939
        @brief  return line types 
940
        @author humkyung
941
        @date   2018.06.27
942
    '''
943
    def getLineTypes(self):
944
        from LineTypeConditions import LineTypeConditions
945

    
946
        res = []
947
        try:
948
            # Creates or opens a file called mydb with a SQLite3 DB
949
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
950
            db = sqlite3.connect(dbPath)
951
            # Get a cursor object
952
            cursor = db.cursor()
953

    
954
            sql = "select UID,Name,Type1,Conditions1,Type2,Conditions2 from LineTypes order by Name" 
955
            cursor.execute(sql)
956
            rows = cursor.fetchall()
957
            for row in rows:
958
                line_type = LineTypeConditions(row[0], row[1])
959
                line_type._conditions[0][0] = row[2]
960
                line_type._conditions[0][1] = row[3]
961
                line_type._conditions[1][0] = row[4]
962
                line_type._conditions[1][1] = row[5]
963
                res.append(line_type)
964
        # Catch the exception
965
        except Exception as ex:
966
            # Roll back any change if something goes wrong
967
            db.rollback()
968
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
969
        finally:
970
            # Close the db connection
971
            db.close()
972

    
973
        return res
974

    
975
    '''
976
        @brief      Insert New Project Info
977
        @author     Jeongwoo
978
        @date       2018.04.06
979
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
980
    '''
981
    def insertProjectInfo(self, desc, dir):
982
        try:
983
            prjDatabaseFilePath = self.getPrjDatabasePath()
984
            conn = sqlite3.connect(prjDatabaseFilePath)
985
            folderName = dir.split('/')[-1]
986
            if folderName:
987
                nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
988
                sql = "insert or replace into Projects(Name, [Desc], Path, CreatedDate, UpdatedDate) values(?, ?, ?, ?, ?)"
989
                param = (folderName, desc, dir, nowDate, nowDate)
990
    
991
                cursor = conn.cursor()
992
                cursor.execute(sql, param)
993
                conn.commit()
994
            else:
995
                print("Empty folder name")
996
        except Exception as ex:
997
            # Roll back any change if something goes wrong
998
            conn.rollback()
999
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1000
        finally:
1001
            conn.close()
1002

    
1003
    def removeProjectInfo(self, targetProject):
1004
        '''
1005
        @brief      Remove Project Info
1006
        @author     Euisung
1007
        @date       2019.01.28
1008
        '''
1009
        try:
1010
            prjDatabaseFilePath = self.getPrjDatabasePath()
1011
            conn = sqlite3.connect(prjDatabaseFilePath)
1012
            sql = "delete from Projects where Id = '{}'".format(targetProject.id)
1013
            cur = conn.cursor()
1014
            cur.execute(sql)
1015
            conn.commit()
1016
        except Exception as ex:
1017
            # Roll back any change if something goes wrong
1018
            conn.rollback()
1019
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1020
        finally:
1021
            conn.close()
1022

    
1023
    '''
1024
        @brief      Update Project UpdatedDate Field
1025
        @author     Jeongwoo
1026
        @date       2018.04.06
1027
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
1028
    '''
1029
    def updateProjectUpdatedDate(self, id, desc):
1030
        try:
1031
            prjDatabaseFilePath = self.getPrjDatabasePath()
1032
            conn = sqlite3.connect(prjDatabaseFilePath)
1033
            nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
1034
            sql = '''
1035
                UPDATE Projects
1036
                SET UpdatedDate = ?,[Desc]=? 
1037
                WHERE Id = ?
1038
            '''
1039
            cur = conn.cursor()
1040
            cur.execute(sql, (nowDate, desc, id))
1041
            conn.commit()
1042
        except Exception as ex:
1043
            # Roll back any change if something goes wrong
1044
            conn.rollback()
1045
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1046
        finally:
1047
            conn.close()
1048

    
1049
    '''
1050
        @brief  get project list from database
1051
        @history    humkyung 2018.04.18 add only project which's project exists
1052
    '''
1053
    def getProjectList(self):
1054
        from Project import Project
1055

    
1056
        projectList = []
1057

    
1058
        try:
1059
            conn = sqlite3.connect(self.getPrjDatabasePath())
1060
            cursor = conn.cursor()
1061
            sql = 'SELECT id,name,[desc],path,createddate,updateddate  FROM Projects ORDER BY UpdatedDate DESC'
1062
            try:
1063
                cursor.execute(sql)
1064
                rows = cursor.fetchall()
1065
                for row in rows:
1066
                    if os.path.isdir(row[3]):   # check if folder exists
1067
                        projectList.append(Project(row[0], row[1], desc=row[2], path=row[3], createDate=row[4], updateDate=row[5]))
1068
            except Exception as ex:
1069
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1070
        finally:
1071
            conn.close()
1072

    
1073
        return projectList
1074

    
1075
    '''
1076
        @brief  get sliding window size
1077
        @author humkyung
1078
    '''
1079
    def getSlidingWindowSize(self):
1080
        res = [10,15]
1081
        try:
1082
            configs = self.getConfigs('Sliding Window')
1083
            for config in configs:
1084
                if config.key == 'Width':
1085
                    res[0] = int(config.value)
1086
                elif config.key == 'Height':
1087
                    res[1] = int(config.value)
1088
        # Catch the exception
1089
        except Exception as ex:
1090
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1091
        
1092
        return res
1093

    
1094
    '''
1095
        @brief  get line no configuration
1096
        @author humkyung
1097
        @date   2018.04.16
1098
    '''
1099
    def getLineNoConfiguration(self):
1100
        res = None
1101
        try:
1102
            # Creates or opens a file called mydb with a SQLite3 DB
1103
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1104
            conn = sqlite3.connect(dbPath)
1105
            # Get a cursor object
1106
            cursor = conn.cursor()
1107

    
1108
            delimiter = None
1109
            sql = "select * from configuration where section='Line No' and key='Delimiter"
1110
            cursor.execute(sql)
1111
            rows = cursor.fetchall()
1112
            if len(rows) == 1:
1113
                delimiter = rows[0][2]
1114

    
1115
            if delimiter is not None:
1116
                sql = "select * from configuration where section='Line No' and key='Configuration'"
1117
                cursor.execute(sql)
1118
                rows = cursor.fetchall()
1119
                if len(rows) == 1:
1120
                    res = rows[0][2].split(delimiter)
1121
        # Catch the exception
1122
        except Exception as ex:
1123
            # Roll back any change if something goes wrong
1124
            conn.rollback()
1125
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1126
        finally:
1127
            # Close the db connection
1128
            conn.close()
1129
        
1130
        return res
1131

    
1132
    '''
1133
        @brief  get area list
1134
        @author humkyung
1135
        @history    euisung     2018.11.20 (0,0),(0,0) process add
1136
    '''
1137
    def getAreaList(self):
1138
        from Area import Area
1139

    
1140
        if len(self._areas) == 0:
1141
            try:
1142
                # Creates or opens a file called mydb with a SQLite3 DB
1143
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1144
                conn = sqlite3.connect(dbPath)
1145
                # Get a cursor object
1146
                cursor = conn.cursor()
1147

    
1148
                sql = "select * from configuration where section='Area'"
1149
                cursor.execute(sql)
1150
                rows = cursor.fetchall()
1151
                for row in rows:
1152
                    name = row[1]
1153
                    area = Area(name)
1154
                    area.parse(row[2])
1155
                    self._areas.append(area)
1156
            # Catch the exception
1157
            except Exception as ex:
1158
                # Roll back any change if something goes wrong
1159
                conn.rollback()
1160
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1161
            finally:
1162
                # Close the db connection
1163
                conn.close()
1164
        
1165
        return self._areas 
1166

    
1167
    '''
1168
        @brief  get area of given name
1169
        @author humkyung
1170
        @date   2018.04.07
1171
    '''
1172
    def getArea(self, name):
1173
        areas = self.getAreaList()
1174
        matches = [area for area in areas if area.name==name]
1175
        if 1 == len(matches) and matches[0].height is not 0 and matches[0].width is not 0:
1176
            return matches[0]
1177

    
1178
        return None
1179

    
1180
    '''
1181
        @brief  get configurations
1182
        @author humkyung
1183
        @date   2018.04.16
1184
        @history kyouho 2018.07.09 change query method
1185
    '''
1186
    '''
1187
    def getConfigs(self, section, key=None):
1188
        res = []
1189

1190
        try:
1191
            # Creates or opens a file called mydb with a SQLite3 DB
1192
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1193
            conn = sqlite3.connect(dbPath)
1194
            # Get a cursor object
1195
            cursor = conn.cursor()
1196

1197
            if key is not None:
1198
                sql = "select * from configuration where section=? and key=?"
1199
                param = (section, key)
1200
            else:
1201
                sql = "select * from configuration where section=?"
1202
                param = (section,)
1203

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

1217
        return res
1218
        '''
1219
    def getConfigs(self, section, key=None):        
1220
        res = []
1221

    
1222
        if self.configTable is None:
1223
            self.configTable = []
1224
            try:
1225
                # Creates or opens a file called mydb with a SQLite3 DB
1226
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1227
                conn = sqlite3.connect(dbPath)
1228
                # Get a cursor object
1229
                cursor = conn.cursor()
1230

    
1231
                sql = "select Section, Key, Value from configuration"
1232
            
1233
                cursor.execute(sql)
1234
                rows = cursor.fetchall()
1235
                for row in rows:
1236
                    self.configTable.append(Config(row[0], row[1], row[2]))
1237
                # Catch the exception
1238
            except Exception as ex:
1239
                # Roll back any change if something goes wrong
1240
                conn.rollback()
1241
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1242
            finally:
1243
                # Close the db connection
1244
                conn.close()
1245

    
1246
        if key is not None:
1247
            for con in self.configTable:
1248
                if con.section == section and con.key == key:
1249
                    res.append(con)
1250
        else:
1251
            for con in self.configTable:
1252
                if con.section == section:
1253
                    res.append(con)
1254

    
1255
        return res
1256

    
1257
    def getAppConfigs(self, section, key=None):
1258
        """
1259
            @brief  get application configurations
1260
            @author humkyung
1261
            @date   2018.11.01
1262
        """
1263

    
1264
        res = []
1265

    
1266
        try:
1267
            # Creates or opens a file called mydb with a SQLite3 DB
1268
            dbPath = self.getAppDbPath()
1269
            conn = sqlite3.connect(dbPath)
1270
            # Get a cursor object
1271
            cursor = conn.cursor()
1272

    
1273
            if key is not None:
1274
                sql = "select * from configuration where section=? and key=?"
1275
                param = (section, key)
1276
            else:
1277
                sql = "select * from configuration where section=?"
1278
                param = (section,)
1279

    
1280
            cursor.execute(sql, param)
1281
            rows = cursor.fetchall()
1282
            for row in rows:
1283
                res.append(Config(row[0], row[1], row[2]))
1284
        # Catch the exception
1285
        except Exception as ex:
1286
            # Roll back any change if something goes wrong
1287
            conn.rollback()
1288
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1289
        finally:
1290
            # Close the db connection
1291
            conn.close()
1292

    
1293
        return res
1294

    
1295
    '''
1296
        @brief      save configurations
1297
        @author     humkyung
1298
        @date       2018.04.16
1299
        @history    humkyung 2018.07.03 replace ' with " if value has '
1300
                    kyouho 2018.07.09 change query method
1301
    '''
1302
    def saveConfigs(self, configs):
1303
        import uuid
1304
        
1305
        try:
1306
            # Creates or opens a file called mydb with a SQLite3 DB
1307
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1308
            conn = sqlite3.connect(dbPath, isolation_level=None)
1309
            # Get a cursor object
1310
            cursor = conn.cursor()
1311

    
1312
            for config in configs:
1313
                if type(config) is Config:
1314
                    value = config.value
1315
                    if type(value) is str and "'" in value:
1316
                        value = value.replace("'", "''")
1317

    
1318
                    sql = "insert or replace into configuration values(?,?,?,?)"
1319
                    param = (str(uuid.uuid4()), config.section, config.key, value)                    
1320

    
1321
                    cursor.execute(sql, param)
1322
                elif hasattr(config, 'toSql'):
1323
                    sql = config.toSql()
1324
                    if type(sql) is list:
1325
                        for item in sql:
1326
                            if item is not None and 2 == len(item):
1327
                                cursor.execute(item[0], item[1])
1328
                    else:
1329
                        if sql is not None and 2 == len(sql):
1330
                            cursor.execute(sql[0], sql[1])
1331

    
1332
            conn.commit()
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
    def saveAppConfigs(self, configs):
1343
        """
1344
        @brief      save application configurations
1345
        @author     humkyung
1346
        @date       2018.10.01
1347
        """
1348

    
1349
        try:
1350
            # Creates or opens a file called mydb with a SQLite3 DB
1351
            dbPath = self.getAppDbPath()
1352
            conn = sqlite3.connect(dbPath)
1353
            # Get a cursor object
1354
            cursor = conn.cursor()
1355

    
1356
            for config in configs:
1357
                value = config.value
1358
                if type(value) is str and "'" in value:
1359
                    value = value.replace("'", "''")
1360

    
1361
                sql = "insert or replace into configuration values(?,?,?)"
1362
                param = (config.section, config.key, value)
1363

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

    
1375
    def deleteDrawingByUID(self, uid):
1376
        try:
1377
            # Creates or opens a file called mydb with a SQLite3 DB
1378
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1379
            conn = sqlite3.connect(dbPath)
1380
            # Get a cursor object
1381
            cursor = conn.cursor()
1382

    
1383
            # 0. Delete Points
1384
            sql = "delete from Points where Components_UID in (select UID from Components where Drawings_UID = '{}')".format(uid)
1385
            cursor.execute(sql)
1386

    
1387
            # 1. Delete HMB
1388
            sql = "delete from HMB where Components_UID in (select UID from Components where Drawings_UID = '{}')".format(uid)
1389
            cursor.execute(sql)
1390

    
1391
            # 2. Delete Components
1392
            sql = "delete from Components where Drawings_UID='{}'".format(uid)
1393
            cursor.execute(sql)
1394
            # 3. Delete DrawingsUnits
1395
            sql = "delete from DrawingsUnits where Drawings_UID='{}'".format(uid)
1396
            cursor.execute(sql)
1397
            
1398
            # 4. Delete Drawings
1399
            sql = "delete from Drawings where UID='{}'".format(uid)
1400
            cursor.execute(sql)
1401
            
1402
            conn.commit()
1403
        # Catch the exception
1404
        except Exception as ex:
1405
            # Roll back any change if something goes wrong
1406
            conn.rollback()
1407
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1408
        finally:
1409
            # Close the db connection
1410
            conn.close()
1411

    
1412
    '''
1413
        @brief  delete configurations
1414
        @author humkyung
1415
        @date   2018.06.29
1416
    '''
1417
    def deleteConfigs(self, section, key=None):
1418
        try:
1419
            # Creates or opens a file called mydb with a SQLite3 DB
1420
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1421
            conn = sqlite3.connect(dbPath)
1422
            # Get a cursor object
1423
            cursor = conn.cursor()
1424

    
1425
            if key is not None:
1426
                sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
1427
            else:
1428
                sql = "delete from configuration where section='{}'".format(section)
1429
            cursor.execute(sql)
1430

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

    
1441
    def deleteAppConfigs(self, section, key=None):
1442
        """
1443
        @brief  delete application configurations
1444
        @author humkyung
1445
        @date   2018.11.01
1446
        """
1447

    
1448
        try:
1449
            # Creates or opens a file called mydb with a SQLite3 DB
1450
            dbPath = self.getAppDbPath()
1451
            conn = sqlite3.connect(dbPath)
1452
            # Get a cursor object
1453
            cursor = conn.cursor()
1454

    
1455
            if key is not None:
1456
                sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
1457
            else:
1458
                sql = "delete from configuration where section='{}'".format(section)
1459
            cursor.execute(sql)
1460

    
1461
            conn.commit()
1462
        # Catch the exception
1463
        except Exception as ex:
1464
            # Roll back any change if something goes wrong
1465
            conn.rollback()
1466
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1467
        finally:
1468
            # Close the db connection
1469
            conn.close()
1470

    
1471
    '''
1472
        @brief      set area list
1473
        @history    humkyung 2018.05.18 round area coordinate and dimension before saving
1474
        @history    euisung  2018.11.20 add self._area reset process
1475
    '''
1476
    def setAreaList(self, areas):
1477
        for area in areas:
1478
            matches = [x for x in self._areas if x.name==area.name]
1479
            if 1 == len(matches):
1480
                matches[0].x = area.x
1481
                matches[0].y = area.y
1482
                matches[0].width = area.width
1483
                matches[0].height = area.height
1484
            elif 0 == len(matches):
1485
                self._areas.append(area)
1486

    
1487
        try:
1488
            # Creates or opens a file called mydb with a SQLite3 DB
1489
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1490
            conn = sqlite3.connect(dbPath)
1491
            # Get a cursor object
1492
            cursor = conn.cursor()
1493

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

    
1498
            conn.commit()
1499
        # Catch the exception
1500
        except Exception as ex:
1501
            # Roll back any change if something goes wrong
1502
            conn.rollback()
1503
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1504
        finally:
1505
            # Close the db connection
1506
            self._areas = []
1507
            conn.close()
1508
            
1509
    '''
1510
        @brief  get symbol name list
1511
    '''
1512
    def getSymbolNameList(self):
1513
        symbolNametList = []
1514

    
1515
        try:            
1516
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1517

    
1518
            conn = sqlite3.connect(dbPath)
1519
            cursor = conn.cursor()
1520
            sql = 'SELECT * FROM SymbolName'
1521
            try:
1522
                cursor.execute(sql)
1523
                rows = cursor.fetchall()
1524
                for row in rows:
1525
                    symbolNametList.append(row[4]) # Name String
1526
            except Exception as ex:
1527
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1528
        finally:
1529
            conn.close()
1530

    
1531
        return symbolNametList
1532

    
1533
    '''
1534
        @brief      get symbol name list by symbol Type
1535
        @author     Jeongwoo
1536
        @date       18.04.06
1537
        @history    .
1538
    '''
1539
    def getSymbolNameListByType(self, type):
1540
        symbolNametList = []
1541

    
1542
        try:
1543
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1544

    
1545
            conn = sqlite3.connect(dbPath)
1546
            cursor = conn.cursor()
1547
            sql = ''
1548
            if type is not None:
1549
                sql = 'SELECT * FROM SymbolName WHERE type = "' + type + '"'
1550
                try:
1551
                    cursor.execute(sql)
1552
                    rows = cursor.fetchall()
1553
                    for row in rows:
1554
                        symbolNametList.append(row[4]) # Name String
1555
                except Exception as ex:
1556
                    print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1557
        finally:
1558
            conn.close()
1559

    
1560
        return symbolNametList
1561

    
1562
    '''
1563
        @brief  delete added symbol data
1564
    '''
1565
    def deleteSymbol(self, fileName):
1566
        ret = False
1567
        try:
1568
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1569

    
1570
            conn = sqlite3.connect(dbPath)
1571
            cursor = conn.cursor()
1572
            sql = "DELETE FROM Symbol WHERE name = ?"
1573
            try:
1574
                cursor.execute(sql, (fileName,))
1575
                conn.commit()
1576
                ret = True
1577
            except Exception as ex:
1578
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1579
                ret = False
1580
        finally:
1581
            conn.close()
1582
            return (ret, fileName)
1583
        
1584
    '''
1585
        @brief  get symbol name
1586
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1587
    '''
1588
    def getSymbolByQuery(self, fieldName, param):
1589
        ret = None
1590

    
1591
        try:
1592
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1593
            conn = sqlite3.connect(dbPath)
1594
            cursor = conn.cursor()
1595

    
1596
            sql = """select s.UID
1597
                          , s.Name
1598
                          , t.Category
1599
                          , t.Type
1600
                          , s.OriginalPoint
1601
                          , s.ConnectionPoint
1602
                       from Symbols s
1603
                      inner join SymbolType t
1604
                         on s.SymbolType_UID = t.UID 
1605
                      where """ + "s." + fieldName + '=?'
1606

    
1607
            try:
1608
                cursor.execute(sql, (param,))
1609
                rows = cursor.fetchall()
1610
                if rows is not None and len(rows) > 0:
1611
                    symbolTuple = rows[0]
1612
                    ret = symbol.SymbolBase(symbolTuple[0], symbolTuple[1], symbolTuple[2], symbolTuple[3], symbolTuple[4], symbolTuple[5]) 
1613
            except Exception as ex:
1614
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1615
        finally:
1616
            conn.close()
1617

    
1618
        return ret
1619

    
1620

    
1621
    def getSymbolListByUID(self, uid):
1622
        ret = []
1623

    
1624
        try:
1625
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1626
            conn = sqlite3.connect(dbPath)
1627
            cursor = conn.cursor()
1628
            
1629
            sql = """select s.UID
1630
                          , s.Name
1631
                          , t.Category
1632
                          , t.Type
1633
                          , s.OriginalPoint
1634
                          , s.ConnectionPoint
1635
                       from Symbols s
1636
                      inner join SymbolType t
1637
                         on s.SymbolType_UID = t.uid 
1638
                      where s.SymbolType_UID = ?"""
1639
           
1640
            try:
1641
                cursor.execute(sql, (uid,))
1642
                rows = cursor.fetchall()
1643
                if rows is not None and len(rows) > 0:
1644
                    for row in rows:
1645
                        sym = symbol.SymbolBase(row[0], row[1], row[2], row[3], row[4], row[5])
1646
                                                
1647
                        ret.append(sym)
1648
            except Exception as ex:
1649
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1650
        finally:
1651
            conn.close()
1652

    
1653
        return ret
1654

    
1655

    
1656
    '''
1657
        @brief  get symbol name list
1658
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1659
    '''
1660
    def getSymbolListByType(self, fieldName=None, param=None):
1661
        ret = []
1662

    
1663
        try:
1664
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1665
            conn = sqlite3.connect(dbPath)
1666
            cursor = conn.cursor()
1667
            if fieldName is not None and param is not None:
1668

    
1669
                sql = """select s.UID
1670
                              , s.Name
1671
                              , t.Category
1672
                              , t.Type
1673
                              , s.OriginalPoint
1674
                              , s.ConnectionPoint
1675
                           from Symbols s 
1676
                          inner join SymbolType t 
1677
                             on s.SymbolType_UID = t.UID
1678
                          where s.SymbolType_UID = (select UID from SymbolType where Type=?)"""
1679
            else:
1680

    
1681
                sql = """select s.UID
1682
                              , s.Name
1683
                              , t.Category
1684
                              , t.Type
1685
                              , s.OriginalPoint
1686
                              , s.ConnectionPoint
1687
                           from Symbols s
1688
                          inner join SymbolType t
1689
                             on s.SymbolType_UID = t.UID"""
1690
            try:
1691
                cursor.execute(sql, (param,)) if param is not None else cursor.execute(sql)
1692
                rows = cursor.fetchall()
1693
                if rows is not None and len(rows) > 0:
1694
                    for row in rows:
1695
                        sym = symbol.SymbolBase(row[0], row[1], row[2], row[3], row[4], row[5])
1696
                                                
1697
                        ret.append(sym)
1698
            except Exception as ex:
1699
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1700
        finally:
1701
            conn.close()
1702

    
1703
        return ret
1704

    
1705
    '''
1706
        @brief      get NominalDiameter
1707
        @author     humkyung
1708
        @date       2018.04.20
1709
        @history    humkyung 2018.04.24 read MetricStr column and set size unit
1710
                    kyouho 2018.07.04 forCheckLineNumber get only inch or metric
1711
                    kyouho 2018.07.16 edit query order by code
1712
    '''
1713
    def getNomialPipeSizeData(self, forCheckLineNumber = False, orderStr = "CODE"):
1714
        res = []
1715
        try:
1716
            configs = self.getConfigs('Line No', 'Size Unit')
1717
            sizeUnit = configs[0].value if 1 == len(configs) else 'Metric'
1718

    
1719
            # Creates or opens a file called mydb with a SQLite3 DB
1720
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1721
            conn = sqlite3.connect(dbPath)
1722
            # Get a cursor object
1723
            cursor = conn.cursor()
1724

    
1725
            sql = "select UID,Code,Metric,Inch,InchStr,AllowableInchStr,MetricStr,AllowableMetricStr from NominalDiameter ORDER BY {} ASC".format(orderStr)
1726
            cursor.execute(sql)
1727
            rows = cursor.fetchall()
1728
            for row in rows:
1729
                pipeSize = NominalPipeSize(row[0], row[1], float(row[2]) if row[2] else None, float(row[3]) if row[3] else None, row[4], row[5], row[6], row[7])
1730
                pipeSize.sizeUnit = sizeUnit
1731
                if forCheckLineNumber:
1732
                    if sizeUnit == 'Inch' and pipeSize.inchStr:
1733
                        res.append(pipeSize.inchStr)
1734
                    elif sizeUnit == 'Metric' and pipeSize.metricStr:
1735
                        res.append(pipeSize.metricStr)
1736
                else:
1737
                    res.append(pipeSize)
1738
                
1739
        # Catch the exception
1740
        except Exception as ex:
1741
            # Roll back any change if something goes wrong
1742
            conn.rollback()
1743
            
1744
            from App import App 
1745
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1746
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1747
        finally:
1748
            # Close the db connection
1749
            conn.close()
1750

    
1751
        return res
1752

    
1753
    '''
1754
        @brief      insert NominalDiameter table
1755
        @author     kyouho
1756
        @date       2018.07.16
1757
    '''
1758
    def insertNomialPipeSize(self, pipeSizes):
1759
        try:
1760
            # Creates or opens a file called mydb with a SQLite3 DB
1761
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1762
            conn = sqlite3.connect(dbPath)
1763
            # Get a cursor object
1764
            cursor = conn.cursor()
1765
            for pipeSize in pipeSizes:
1766
                sql = pipeSize.toSql()
1767
                if type(sql) is list and len(sql) == 1:
1768
                    cursor.execute(sql[0][0], sql[0][1])
1769

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

    
1780
    '''
1781
        @brief      delete NominalDiameter table
1782
        @author     kyouho
1783
        @date       2018.07.16
1784
    '''
1785
    def deleteNomialPipeSize(self):
1786
        try:
1787
            dbPath = os.path.join(self.getCurrentProject().getPath(), 'db', AppDocData.DATABASE)
1788
            conn = sqlite3.connect(dbPath)
1789
            cursor = conn.cursor()
1790
            sql = "DELETE FROM NominalDiameter"
1791
            try:
1792
                cursor.execute(sql)
1793
                conn.commit()
1794
            except Exception as ex:
1795
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1796
        finally:
1797
            conn.close()
1798

    
1799
    '''
1800
        @brief      convert inch to metric
1801
        @author     kyouho
1802
        @date       2018.07.09
1803
    '''
1804
    def convertInchToMetric(self, inch):
1805
        result = ''
1806
        try:
1807
            # Creates or opens a file called mydb with a SQLite3 DB
1808
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1809
            conn = sqlite3.connect(dbPath)
1810
            # Get a cursor object
1811
            cursor = conn.cursor()
1812
            
1813
            sql = "select MetricStr from NominalDiameter WHERE InchStr = ?"
1814
            param = (inch,)
1815
            cursor.execute(sql, param)
1816
            rows = cursor.fetchall()
1817

    
1818
            if rows:
1819
                result = rows[0][0]
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
        return result
1830

    
1831
    '''
1832
        @brief      get Color MaxUID
1833
        @author     kyouho
1834
        @date       2018.07.03
1835
    '''
1836
    def getMaxColorUID(self):
1837
        result = 0
1838

    
1839
        try:
1840
            # Creates or opens a file called mydb with a SQLite3 DB
1841
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1842
            conn = sqlite3.connect(dbPath)
1843
            # Get a cursor object
1844
            cursor = conn.cursor()
1845

    
1846
            sql = "select MAX(UID) from Colors"
1847
            cursor.execute(sql)
1848
            rows = cursor.fetchall()
1849

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

    
1860
        return result
1861

    
1862
    '''
1863
        @brief      insert Color property
1864
        @author     kyouho
1865
        @date       2018.07.09
1866
    '''
1867
    def setPropertyColor(self, _color):
1868
        try:
1869
            # Creates or opens a file called mydb with a SQLite3 DB
1870
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1871
            conn = sqlite3.connect(dbPath)
1872
            # Get a cursor object
1873
            cursor = conn.cursor()
1874
            sql = "INSERT INTO Colors(UID, RED, GREEN, BLUE, PROPERTY, VALUE) VALUES(?,?,?,?,?,?)"
1875
            param = (_color.index, _color.red, _color.green, _color.blue, _color._property, _color.value)
1876
            cursor.execute(sql, param)
1877
            conn.commit()
1878
            # Catch the exception
1879
        except Exception as ex:
1880
            # Roll back any change if something goes wrong
1881
            conn.rollback()
1882
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1883
        finally:
1884
            # Close the db connection
1885
            conn.close()
1886

    
1887
    '''
1888
        @brief      delete Color property
1889
        @author     kyouho
1890
        @date       2018.07.09
1891
    '''
1892
    def deletePropertyColor(self, property):
1893
        try:
1894
            # Creates or opens a file called mydb with a SQLite3 DB
1895
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1896
            conn = sqlite3.connect(dbPath)
1897
            # Get a cursor object
1898
            cursor = conn.cursor()
1899

    
1900
            sql = "DELETE FROM Colors WHERE PROPERTY = '{}'".format(property)
1901
            cursor.execute(sql)
1902
            conn.commit()
1903
            # Catch the exception
1904
        except Exception as ex:
1905
            # Roll back any change if something goes wrong
1906
            conn.rollback()
1907
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1908
        finally:
1909
            # Close the db connection
1910
            conn.close()
1911

    
1912
    '''
1913
        @brief      get Fluid Code
1914
        @author     kyouho
1915
        @date       2018.07.03
1916
        @history    kyouho 2018.07.04 kyouho 2018.07.04 forCheckLineNumber get only code
1917
    '''
1918
    def getFluidCodeData(self, forCheckLineNumber = False):
1919
        from FluidCodeData import FluidCodeData
1920
        result = []
1921

    
1922
        try:
1923
            # Creates or opens a file called mydb with a SQLite3 DB
1924
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1925
            conn = sqlite3.connect(dbPath)
1926
            # Get a cursor object
1927
            cursor = conn.cursor()
1928

    
1929
            sql = 'select uid, code, description from FluidCode order by length(code) DESC'
1930
            cursor.execute(sql)
1931
            rows = cursor.fetchall()
1932
            for row in rows:
1933
                data = FluidCodeData(row[0], row[1], row[2])
1934
                if forCheckLineNumber:
1935
                    result.append(data.code)
1936
                else:
1937
                    result.append(data)
1938
            # Catch the exception
1939
        except Exception as ex:
1940
            # Roll back any change if something goes wrong
1941
            conn.rollback()
1942
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1943
        finally:
1944
            # Close the db connection
1945
            conn.close()
1946

    
1947
        return result
1948

    
1949
    '''
1950
        @brief      get Symbol Attribute
1951
        @author     kyouho
1952
        @date       2018.07.18
1953
    '''
1954
    def checkAttribute(self, attr):
1955
        try:
1956
            # Creates or opens a file called mydb with a SQLite3 DB
1957
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1958
            conn = sqlite3.connect(dbPath)
1959
            # Get a cursor object
1960
            cursor = conn.cursor()
1961

    
1962
            sql = 'select UID from SymbolAttribute where UID = ?'
1963
            param = (attr,)
1964
            cursor.execute(sql, param)
1965
            rows = cursor.fetchall()
1966
            if len(rows):
1967
                return True
1968
            else:
1969
                return False
1970
            # Catch the exception
1971
        except Exception as ex:
1972
            # Roll back any change if something goes wrong
1973
            conn.rollback()
1974
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1975
        finally:
1976
            # Close the db connection
1977
            conn.close()
1978

    
1979
        return False
1980

    
1981
    '''
1982
        @brief      get Symbol Attribute
1983
        @author     kyouho
1984
        @date       2018.07.18
1985
        @history    humkyung 2018.10.13 load expression
1986
    '''
1987
    def getSymbolAttribute(self, _type):
1988
        import uuid
1989
        from SymbolAttr import SymbolAttr
1990

    
1991
        result = []
1992

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

    
2000
            sql = 'select a.UID, a.Attribute, a.DisplayAttribute, a.AttributeType, a.[AttrAt], a.[Expression], a.[index], a.[Target], a.[Property] from SymbolAttribute a inner join SymbolType t on a.SymbolType_UID = t.UID and t.type = ? order by a.[index]'
2001
            param = (_type,)
2002
            cursor.execute(sql, param)
2003
            rows = cursor.fetchall()
2004
            for row in rows:
2005
                attr = SymbolAttr()
2006
                attr.UID = uuid.UUID(row[0], version=4)
2007
                attr.Attribute = row[1]
2008
                attr.DisplayAttribute = row[2]
2009
                attr.AttributeType = row[3]
2010
                attr.AttrAt = row[4]
2011
                attr.Expression = row[5]
2012
                attr.Target = row[7]
2013
                attr.IsProp = bool(row[8])
2014
                result.append(attr)
2015
            # Catch the exception
2016
        except Exception as ex:
2017
            from App import App 
2018

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

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

    
2028
        return result
2029

    
2030
    '''
2031
        @brief      get Symbol Attribute by UID
2032
        @author     kyouho
2033
        @date       2018.08.17
2034
        @history    humkyung 2018.10.13 load expression
2035
    '''
2036
    def getSymbolAttributeByUID(self, UID):
2037
        from SymbolAttr import SymbolAttr
2038

    
2039
        res = None
2040

    
2041
        try:
2042
            # Creates or opens a file called mydb with a SQLite3 DB
2043
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2044
            conn = sqlite3.connect(dbPath)
2045
            # Get a cursor object
2046
            cursor = conn.cursor()
2047

    
2048
            sql = 'select Attribute, DisplayAttribute, AttributeType, AttrAt, Expression, Target, Property from SymbolAttribute where uid = "{}"'.format(UID)
2049
            cursor.execute(sql)
2050
            rows = cursor.fetchall()
2051
            if len(rows):
2052
                res = SymbolAttr()
2053
                res.UID = UID
2054
                res.Attribute = rows[0][0]
2055
                res.DisplayAttribute = rows[0][1]
2056
                res.AttributeType = rows[0][2]
2057
                res.AttrAt = rows[0][3]
2058
                res.Expression = rows[0][4]
2059
                res.Target = rows[0][5]
2060
                res.IsProp = bool(row[0][6])
2061
            # Catch the exception
2062
        except Exception as ex:
2063
            from App import App
2064

    
2065
            # Roll back any change if something goes wrong
2066
            conn.rollback()
2067

    
2068
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2069
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2070
        finally:
2071
            # Close the db connection
2072
            conn.close()
2073

    
2074
        return res
2075

    
2076
    '''
2077
        @brief      save symbol attributes
2078
        @author     humkyung
2079
        @date       2018.08.14
2080
        @history    humkyung 2018.10.13 save expression
2081
    '''
2082
    def saveSymbolAttributes(self, type, attrs):
2083
        try:
2084
            # Creates or opens a file called mydb with a SQLite3 DB
2085
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2086
            conn = sqlite3.connect(dbPath)
2087
            # Get a cursor object
2088
            cursor = conn.cursor()
2089

    
2090
            sql = 'delete from SymbolAttribute where SymbolType_UID = ?'
2091
            param = (type,)
2092
            cursor.execute(sql, param)
2093

    
2094
            for attr in attrs:
2095
                sql = 'insert into SymbolAttribute(UID, SymbolType_UID, Attribute, DisplayAttribute, AttributeType, AttrAt, Expression, Target, [index]) values(?, ?, ?, ?, ?, ?, ?, ?, ?)'
2096
                attr.insert(1, type)
2097
                param = tuple(attr)
2098
                cursor.execute(sql, param)
2099

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

    
2113
    '''
2114
        @brief      save symbol attributes
2115
        @author     humkyung
2116
        @date       2018.08.14
2117
    '''
2118
    def saveLineAttributes(self, attrs):
2119
        try:
2120
            # Creates or opens a file called mydb with a SQLite3 DB
2121
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2122
            conn = sqlite3.connect(dbPath)
2123
            # Get a cursor object
2124
            cursor = conn.cursor()
2125

    
2126
            sql = 'delete from LineProperties'
2127
            cursor.execute(sql)
2128

    
2129
            for attr in attrs:
2130
                sql = 'insert into LineProperties(UID, Name, DisplayName, Type, LimitNumber, [index]) values(?, ?, ?, ?, ?, ?)'
2131
                param = tuple(attr)
2132
                cursor.execute(sql, param)
2133

    
2134
            conn.commit()
2135

    
2136
            self._lineNoProperties = None
2137
            # Catch the exception
2138
        except Exception as ex:
2139
            # Roll back any change if something goes wrong
2140
            conn.rollback()
2141
            
2142
            from App import App 
2143
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2144
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2145
        finally:
2146
            # Close the db connection
2147
            conn.close()
2148

    
2149
    '''
2150
        @brief      get symbol type id
2151
        @author     kyouho
2152
        @date       2018.08.17
2153
    '''
2154
    def getSymbolTypeId(self, symbolType):
2155
        result = []
2156

    
2157
        try:
2158
            # Creates or opens a file called mydb with a SQLite3 DB
2159
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2160
            conn = sqlite3.connect(dbPath)
2161
            # Get a cursor object
2162
            cursor = conn.cursor()
2163

    
2164
            sql = 'select UID from SymbolType where Type = ?'
2165
            param = (symbolType,)
2166
            cursor.execute(sql, param)
2167
            rows = cursor.fetchall()
2168
            
2169
            if len(rows):
2170
                result = rows[0][0]
2171
            else:
2172
                result = -1
2173
            # Catch the exception
2174
        except Exception as ex:
2175
            # Roll back any change if something goes wrong
2176
            conn.rollback()
2177
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2178
        finally:
2179
            # Close the db connection
2180
            conn.close()
2181

    
2182
        return result
2183

    
2184
    '''
2185
        @brief      get Code Table Data
2186
        @author     kyouho
2187
        @date       2018.07.10
2188
    '''
2189
    def getCodeTable(self, property, forCheckLineNumber = False):
2190
        result = []
2191
        try:
2192
            # Creates or opens a file called mydb with a SQLite3 DB
2193
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2194
            conn = sqlite3.connect(dbPath)
2195
            # Get a cursor object
2196
            cursor = conn.cursor()
2197

    
2198
            if property.upper().replace(' ','') == "NOMINALDIAMETER" and forCheckLineNumber:
2199
                sql = 'select InchStr, MetricStr from [{}] order by Metric ASC'.format(property)
2200
                cursor.execute(sql)
2201
                rows = cursor.fetchall()
2202
                for index in range(2):
2203
                    for row in rows:
2204
                        if row[index] != '' and result.count(row[index].replace("'", '"')) == 0:
2205
                            result.append(row[index].replace("'", '"'))
2206
            else:
2207
                sql = 'select uid, code, description, Allowables from [{}] order by length(code) DESC'.format(property)
2208
                cursor.execute(sql)
2209
                rows = cursor.fetchall()
2210
                for row in rows:
2211
                    if forCheckLineNumber:
2212
                        data = row[1]
2213
                    else:
2214
                        data = (row[0], row[1], row[2], row[3])
2215
                    result.append(data)
2216
            # Catch the exception
2217
        except Exception as ex:
2218
            # Roll back any change if something goes wrong
2219
            conn.rollback()
2220
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2221
        finally:
2222
            # Close the db connection
2223
            conn.close()
2224

    
2225
        return result
2226

    
2227
    '''
2228
        @brief      Set Common Code Data
2229
        @author     kyouho
2230
        @date       2018.07.12
2231
    '''
2232
    def saveCommonCodeData(self, tableName, datas):
2233
        import uuid
2234

    
2235
        try:
2236
            # Creates or opens a file called mydb with a SQLite3 DB
2237
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2238
            conn = sqlite3.connect(dbPath)
2239
            # Get a cursor object
2240
            cursor = conn.cursor()
2241

    
2242
            for data in datas:
2243
                uid,code,description,allowables = data[0],data[1],data[2],data[3]
2244
                if not uid:
2245
                    sql = "insert or replace into {}(UID, CODE, DESCRIPTION, ALLOWABLES) values(?, ?, ?, ?)".format(tableName)
2246
                    param = (str(uuid.uuid4()), data[1], data[2], data[3])
2247
                elif uid == '-1':
2248
                    sql = 'delete from {} where uid=?'.format(tableName) 
2249
                    param = (data[-1],)
2250
                else:
2251
                    sql = "update {} SET CODE=?, DESCRIPTION=?, ALLOWABLES=? WHERE UID = ?".format(tableName)
2252
                    param = (data[1], data[2], data[3], data[0])
2253
                cursor.execute(sql, param)
2254

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

    
2266
    '''
2267
        @brief      Set Common Code Data
2268
        @author     kyouho
2269
        @date       2018.07.12
2270
    '''
2271
    def deleteCommonCodeData(self, datas):
2272
        try:
2273
            # Creates or opens a file called mydb with a SQLite3 DB
2274
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2275
            conn = sqlite3.connect(dbPath)
2276
            # Get a cursor object
2277
            cursor = conn.cursor()
2278

    
2279
            for data in datas:
2280
                uid = data[0]
2281
                tableName = data[1]
2282

    
2283
                if uid:
2284
                    sql = "delete from {} where UID = ?".format(tableName)
2285
                    param = (uid,)
2286
                    cursor.execute(sql, param)
2287

    
2288
                cursor.execute(sql, param)
2289

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

    
2301
    '''
2302
        @brief      delete data list
2303
        @author     kyouho
2304
        @date       2018.08.16
2305
    '''
2306
    def deleteDataList(self, tableName, UID):
2307
        try:
2308
            # Creates or opens a file called mydb with a SQLite3 DB
2309
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2310
            conn = sqlite3.connect(dbPath)
2311
            # Get a cursor object
2312
            cursor = conn.cursor()
2313

    
2314
            sql = 'delete from {} where UID = {}'.format(tableName, UID)
2315
            
2316
            cursor.execute(sql)
2317

    
2318
            conn.commit()
2319

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

    
2329
    def getDocumentNameList(self):
2330
        '''
2331
            @brief      get documentName list
2332
            @author     euisung
2333
            @date       2018.12.11
2334
        '''
2335
        result = []
2336

    
2337
        try:
2338
            # Creates or opens a file called mydb with a SQLite3 DB
2339
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2340
            conn = sqlite3.connect(dbPath)
2341
            # Get a cursor object
2342
            cursor = conn.cursor()
2343

    
2344
            sql = 'select DISTINCT(PNID_NO) from LINE_DATA_LIST'
2345
            cursor.execute(sql)
2346
            sql = 'select DISTINCT(PNID_NO) from EQUIPMENT_DATA_LIST'
2347
            cursor.execute(sql)
2348
            sql = 'select DISTINCT(PNID_NO) from INSTRUMENT_DATA_LIST'
2349
            cursor.execute(sql)
2350
            sql = 'select DISTINCT(PNID_NO) from NOTE_DATA_LIST'
2351
            cursor.execute(sql)
2352
            sql = 'select DISTINCT(PNID_NO) from VALVE_DATA_LIST'
2353
            cursor.execute(sql)
2354

    
2355
            rows = cursor.fetchall()
2356
            for row in rows:
2357
                result.append(row[0])
2358

    
2359
            result = list(set(result))
2360
            result.sort()
2361
        # Catch the exception
2362
        except Exception as ex:
2363
            # Roll back any change if something goes wrong
2364
            conn.rollback()
2365
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2366
        finally:
2367
            # Close the db connection
2368
            conn.close()
2369

    
2370
        return result
2371

    
2372

    
2373
    '''
2374
        @brief      get line documentName list
2375
        @author     kyouho
2376
        @date       2018.08.13
2377
    '''
2378
    def getLineDocumentNameList(self):
2379
        result = []
2380

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

    
2388
            sql = 'select DISTINCT(PNID_NO) from LINE_DATA_LIST'
2389

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

    
2403
        return result
2404

    
2405
    '''
2406
        @brief      get line documentName list
2407
        @author     kyouho
2408
        @date       2018.08.14
2409
    '''
2410
    def getEquipDocumentNameList(self):
2411
        result = []
2412

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

    
2420
            sql = 'select DISTINCT(PNID_NO) from EQUIPMENT_DATA_LIST'
2421

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

    
2435
        return result
2436

    
2437

    
2438
    '''
2439
        @brief      get line data list
2440
        @author     kyouho
2441
        @date       2018.08.13
2442
    '''
2443
    def getLineDataList(self, docName = None):
2444
        result = []
2445

    
2446
        try:
2447
            # Creates or opens a file called mydb with a SQLite3 DB
2448
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2449
            conn = sqlite3.connect(dbPath)
2450
            # Get a cursor object
2451
            cursor = conn.cursor()
2452

    
2453
            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'
2454
            if docName is not None:
2455
                sql += " where PNID_NO = '{}'".format(docName)
2456

    
2457
            cursor.execute(sql)
2458
            #columnName = list(map(lambda x: x[0].upper(), cursor.description))
2459
            rows = cursor.fetchall()
2460
            for row in rows:
2461
                data = []
2462
                for index in range(len(cursor.description)):
2463
                    data.append(row[index])
2464
                result.append(data)
2465
        # Catch the exception
2466
        except Exception as ex:
2467
            # Roll back any change if something goes wrong
2468
            conn.rollback()
2469
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2470
        finally:
2471
            # Close the db connection
2472
            conn.close()
2473

    
2474
        return result
2475

    
2476
    '''
2477
        @brief      set line data list
2478
        @author     kyouho
2479
        @date       2018.08.13
2480
    '''
2481
    def setLineDataList(self, dataLists):
2482
        try:
2483
            # Creates or opens a file called mydb with a SQLite3 DB
2484
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2485
            conn = sqlite3.connect(dbPath)
2486
            # Get a cursor object
2487
            cursor = conn.cursor()
2488
            
2489
            for data in dataLists:
2490
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2491
                param = tuple(data)
2492
                cursor.execute(sql, param)
2493

    
2494
            conn.commit()
2495

    
2496
        # Catch the exception
2497
        except Exception as ex:
2498
            # Roll back any change if something goes wrong
2499
            conn.rollback()
2500
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2501
        finally:
2502
            # Close the db connection
2503
            conn.close()
2504

    
2505
    '''
2506
        @brief      delete line data list
2507
        @author     kyouho
2508
        @date       2018.08.13
2509
    '''
2510
    def deleteLineDataList(self, removeUID):
2511
        try:
2512
            # Creates or opens a file called mydb with a SQLite3 DB
2513
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2514
            conn = sqlite3.connect(dbPath)
2515
            # Get a cursor object
2516
            cursor = conn.cursor()
2517
            
2518
            for uid in removeUID:
2519
                sql = "delete from LINE_DATA_LIST where uid = '{}'".format(uid)
2520
                cursor.execute(sql)
2521

    
2522
            conn.commit()
2523

    
2524
        # Catch the exception
2525
        except Exception as ex:
2526
            # Roll back any change if something goes wrong
2527
            conn.rollback()
2528
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2529
        finally:
2530
            # Close the db connection
2531
            conn.close()
2532

    
2533
    '''
2534
        @brief      delete line data list
2535
        @author     kyouho
2536
        @date       2018.08.13
2537
    '''
2538
    def deleteLineDataList_LineNo(self, removeUID):
2539
        try:
2540
            # Creates or opens a file called mydb with a SQLite3 DB
2541
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2542
            conn = sqlite3.connect(dbPath)
2543
            # Get a cursor object
2544
            cursor = conn.cursor()
2545
            
2546
            for uid in removeUID:
2547
                sql = "delete from LINE_DATA_LIST where LINE_NO = ?"
2548
                param = (uid,)
2549
                cursor.execute(sql, param)
2550

    
2551
            conn.commit()
2552

    
2553
        # Catch the exception
2554
        except Exception as ex:
2555
            # Roll back any change if something goes wrong
2556
            conn.rollback()
2557
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2558
        finally:
2559
            # Close the db connection
2560
            conn.close()
2561

    
2562
    '''
2563
        @brief      delete equip data list
2564
        @author     kyouho
2565
        @date       2018.08.14
2566
    '''
2567
    def deleteEquipDataList(self, removeUID):
2568
        try:
2569
            # Creates or opens a file called mydb with a SQLite3 DB
2570
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2571
            conn = sqlite3.connect(dbPath)
2572
            # Get a cursor object
2573
            cursor = conn.cursor()
2574
            
2575
            for uid in removeUID:
2576
                sql = "delete from EQUIPMENT_DATA_LIST where uid = '{}'".format(uid)
2577
                cursor.execute(sql)
2578

    
2579
            conn.commit()
2580

    
2581
        # Catch the exception
2582
        except Exception as ex:
2583
            # Roll back any change if something goes wrong
2584
            conn.rollback()
2585
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2586
        finally:
2587
            # Close the db connection
2588
            conn.close()
2589

    
2590
    '''
2591
        @brief      delete inst data list
2592
        @author     kyouho
2593
        @date       2018.08.14
2594
    '''
2595
    def deleteInstDataList(self, removeUID):
2596
        try:
2597
            # Creates or opens a file called mydb with a SQLite3 DB
2598
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2599
            conn = sqlite3.connect(dbPath)
2600
            # Get a cursor object
2601
            cursor = conn.cursor()
2602
            
2603
            for uid in removeUID:
2604
                sql = "delete from INSTRUMENT_DATA_LIST where uid = '{}'".format(uid)
2605
                cursor.execute(sql)
2606

    
2607
            conn.commit()
2608

    
2609
        # Catch the exception
2610
        except Exception as ex:
2611
            # Roll back any change if something goes wrong
2612
            conn.rollback()
2613
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2614
        finally:
2615
            # Close the db connection
2616
            conn.close()
2617

    
2618
    '''
2619
        @brief      delete note data list
2620
        @author     kyouho
2621
        @date       2018.10.10
2622
    '''
2623
    def deleteNoteDataList(self, removeUID):
2624
        try:
2625
            # Creates or opens a file called mydb with a SQLite3 DB
2626
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2627
            conn = sqlite3.connect(dbPath)
2628
            # Get a cursor object
2629
            cursor = conn.cursor()
2630
            
2631
            for uid in removeUID:
2632
                sql = "delete from NOTE_DATA_LIST where uid = '{}'".format(uid)
2633
                cursor.execute(sql)
2634

    
2635
            conn.commit()
2636

    
2637
        # Catch the exception
2638
        except Exception as ex:
2639
            # Roll back any change if something goes wrong
2640
            conn.rollback()
2641
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2642
        finally:
2643
            # Close the db connection
2644
            conn.close()
2645

    
2646
    '''
2647
        @brief      get equipment data list
2648
        @author     humkyung
2649
        @date       2018.05.03
2650
    '''
2651
    def getEquipmentDataList(self, docName = None):
2652
        result = []
2653
        try:
2654
            # Creates or opens a file called mydb with a SQLite3 DB
2655
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2656
            conn = sqlite3.connect(dbPath)
2657
            # Get a cursor object
2658
            cursor = conn.cursor()
2659

    
2660
            sql = 'select a.*,C.Attribute,B.Value  from EQUIPMENT_DATA_LIST a left join Attributes B on a.UID=B.Components_UID ' \
2661
                                                                             'left join SymbolAttribute C on B.SymbolAttribute_UID=C.UID'
2662
            if docName is not None:
2663
                sql += " where PNID_NO = '{}'".format(docName)
2664

    
2665
            cursor.execute(sql)
2666
            col_names = [desc[0] for desc in cursor.description]    # get coloumn name
2667
            rows = cursor.fetchall()
2668
            for row in rows:
2669
                matches = [res for res in result if res['UID']==row[0]]
2670
                if matches:
2671
                    matches[0][row[len(row)-2]] = row[len(row)-1]
2672
                else:
2673
                    data = dict(zip(col_names[:-2], row[:-2]))
2674
                    if row[len(row)-2] is not None:
2675
                        data[row[len(row)-2]] = row[len(row)-1]
2676
                    result.append(data)
2677
        # Catch the exception
2678
        except Exception as ex:
2679
            from App import App 
2680

    
2681
            # Roll back any change if something goes wrong
2682
            conn.rollback()
2683
            
2684
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2685
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2686
        finally:
2687
            # Close the db connection
2688
            conn.close()
2689

    
2690
        return result
2691

    
2692
    def get_valve_data_list(self, docName = None):
2693
        """
2694
        @brief      get valve data list
2695
        @author     humkyung
2696
        @date       2018.10.11
2697
        """
2698

    
2699
        result = []
2700
        try:
2701
            # Creates or opens a file called mydb with a SQLite3 DB
2702
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2703
            conn = sqlite3.connect(dbPath)
2704
            # Get a cursor object
2705
            cursor = conn.cursor()
2706

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

    
2712
            cursor.execute(sql)
2713
            rows = cursor.fetchall()
2714
            for row in rows:
2715
                matches = [res for res in result if res['UID'] == row[0]]
2716
                if matches:
2717
                    matches[0][row[5]] = row[6]
2718
                else:
2719
                    data = {'UID':row[0], 'ITEM_NO':row[1], 'PNID_NO':row[2], 'MainSize':row[3], 'SubSize':row[4]}
2720
                    data[row[5]] = row[6]
2721
                    result.append(data)
2722

    
2723
        # Catch the exception
2724
        except Exception as ex:
2725
            from App import App 
2726

    
2727
            # Roll back any change if something goes wrong
2728
            conn.rollback()
2729
            
2730
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2731
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2732
        finally:
2733
            # Close the db connection
2734
            conn.close()
2735

    
2736
        return result
2737

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

    
2752
            #sql = 'select UID, ITEM_NO, SERVICE, FLOW_RATE, PRESSURE, TEMPERATURE, TYPE, RANGE, NOR_LEVEL_MM, NOR_LEVEL_PERCENT, DEL_PRESS, SHUT_OFF, LOCATION, PNID_NO, REV from INSTRUMENT_DATA_LIST'
2753
            sql = 'select * from INSTRUMENT_DATA_LIST'
2754
            if docName is not None:
2755
                sql += " where PNID_NO = '{}'".format(docName)
2756

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

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

    
2776
        return result
2777

    
2778
    '''
2779
        @brief      get Note data list
2780
        @author     kyouho
2781
        @date       2018.10.10
2782
    '''
2783
    def getNoteDataList(self, docName = None):
2784
        result = []
2785
        try:
2786
            # Creates or opens a file called mydb with a SQLite3 DB
2787
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2788
            conn = sqlite3.connect(dbPath)
2789
            # Get a cursor object
2790
            cursor = conn.cursor()
2791

    
2792
            sql = 'select UID, NOTE_NO, DESCRIPTION, PNID_NO from NOTE_DATA_LIST'
2793
            if docName is not None:
2794
                sql += " where PNID_NO = '{}'".format(docName)
2795

    
2796
            sql += ' ORDER BY NOTE_NO ASC'
2797
            cursor.execute(sql)
2798
            rows = cursor.fetchall()
2799
            for row in rows:
2800
                data = []
2801
                for index in range(len(cursor.description)): 
2802
                    data.append(row[index])
2803
                result.append(data)
2804
        # Catch the exception
2805
        except Exception as ex:
2806
            # Roll back any change if something goes wrong
2807
            conn.rollback()
2808
            from App import App
2809

    
2810
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2811
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2812
        finally:
2813
            # Close the db connection
2814
            conn.close()
2815

    
2816
        return result
2817

    
2818
    def saveToDatabase(self, items):
2819
        """ save given items to database """
2820
        try:
2821
            # Creates or opens a file called mydb with a SQLite3 DB
2822
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2823
            conn = sqlite3.connect(dbPath, isolation_level=None)
2824
            # Get a cursor object
2825
            cursor = conn.cursor()
2826

    
2827
            uid = self.activeDrawing.UID
2828

    
2829
            # delete Points
2830
            sql = "delete from Points where Components_UID in (select UID from Components where Drawings_UID = '{}')".format(uid)
2831
            cursor.execute(sql)
2832

    
2833
            # delete HMB
2834
            sql = "delete from HMB where Components_UID in (select UID from Components where Drawings_UID = '{}')".format(uid)
2835
            cursor.execute(sql)
2836

    
2837
            # delete Components 
2838
            sql = "delete from Components where Drawings_UID = '{}'".format(uid)
2839
            cursor.execute(sql)
2840

    
2841
            for item in items:
2842
                sql = item.toSql()
2843
                if type(sql) is list:
2844
                    for item in sql:
2845
                        if item is not None and 2 == len(item):
2846
                            cursor.execute(item[0], item[1])
2847
                else:
2848
                    if sql is not None and 2 == len(sql):
2849
                        cursor.execute(sql[0], sql[1])
2850

    
2851
            conn.commit()
2852
        # Catch the exception
2853
        except Exception as ex:
2854
            from App import App
2855
            # Roll back any change if something goes wrong
2856
            conn.rollback()
2857

    
2858
            print(sql)
2859
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2860
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2861
        finally:
2862
            # Close the db connection
2863
            conn.close()
2864

    
2865
    '''
2866
        @brief      set equipment data list
2867
        @author     humkyung
2868
        @date       2018.05.03
2869
    '''
2870
    def setEquipmentDataList(self, dataList):
2871
        try:
2872
            # Creates or opens a file called mydb with a SQLite3 DB
2873
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2874
            conn = sqlite3.connect(dbPath)
2875
            # Get a cursor object
2876
            cursor = conn.cursor()
2877

    
2878
            for data in dataList:
2879
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2880
                param = tuple(data)
2881
                cursor.execute(sql, param)
2882
            conn.commit()
2883
        # Catch the exception
2884
        except Exception as ex:
2885
            # Roll back any change if something goes wrong
2886
            conn.rollback()
2887
            from App import App
2888

    
2889
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2890
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2891
        finally:
2892
            # Close the db connection
2893
            conn.close()
2894

    
2895
    '''
2896
        @brief      set instrumnet data list
2897
        @author     kyoyho
2898
        @date       2018.08.14
2899
    '''
2900
    def setInstrumentDataList(self, dataList):
2901
        try:
2902
            # Creates or opens a file called mydb with a SQLite3 DB
2903
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2904
            conn = sqlite3.connect(dbPath)
2905
            # Get a cursor object
2906
            cursor = conn.cursor()
2907

    
2908
            for data in dataList:
2909
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2910
                param = tuple(data)
2911
                cursor.execute(sql, param)
2912
            conn.commit()
2913

    
2914
        # Catch the exception
2915
        except Exception as ex:
2916
            # Roll back any change if something goes wrong
2917
            conn.rollback()
2918
            from App import App
2919

    
2920
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2921
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2922
        finally:
2923
            # Close the db connection
2924
            conn.close()
2925

    
2926
    '''
2927
        @brief      set Note data list
2928
        @author     kyoyho
2929
        @date       2018.10.10
2930
    '''
2931
    def setNoteDataList(self, dataList):
2932
        try:
2933
            # Creates or opens a file called mydb with a SQLite3 DB
2934
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2935
            conn = sqlite3.connect(dbPath)
2936
            # Get a cursor object
2937
            cursor = conn.cursor()
2938

    
2939
            for data in dataList:
2940
                sql = "insert or replace into NOTE_DATA_LIST(UID, NOTE_NO, DESCRIPTION, PNID_NO) values(?, ?, ?, ?)"
2941
                param = tuple(data)
2942
                cursor.execute(sql, param)
2943
            conn.commit()
2944

    
2945
        # Catch the exception
2946
        except Exception as ex:
2947
            # Roll back any change if something goes wrong
2948
            conn.rollback()
2949
            from App import App
2950

    
2951
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2952
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2953
        finally:
2954
            # Close the db connection
2955
            conn.close()
2956

    
2957
    """
2958
        @brief      exists drawing
2959
        @author     yeonjin
2960
        @date       2019.07.03
2961
    """
2962
    def exists_drawing(self, drawingName):
2963
        rows = None
2964
        try:           
2965
            # Creates or opens a file called mydb with a SQLite3 DB
2966
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2967
            conn = sqlite3.connect(dbPath)
2968
            # Get a cursor object
2969
            cursor = conn.cursor()
2970
            sql = "select name from Drawings where upper(name) = '" + drawingName.upper() + "'"
2971
            cursor.execute(sql)
2972
            rows = cursor.fetchall()
2973
        # Catch the exception
2974
        except Exception as ex:
2975
            # Roll back any change if something goes wrong
2976
            conn.rollback()
2977
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2978
        finally:
2979
            # Close the db connection
2980
            conn.close()
2981
            if rows is not None and len(rows) > 0:
2982
                return True
2983
            else:
2984
                return False
2985

    
2986
    def getDrawings(self):
2987
        """
2988
        @brief      get drawings
2989
        @author     humkyung
2990
        @date       2018.11.03
2991
        """
2992

    
2993
        res = []
2994
        try:
2995
            # Creates or opens a file called mydb with a SQLite3 DB
2996
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2997
            conn = sqlite3.connect(dbPath)
2998
            # Get a cursor object
2999
            cursor = conn.cursor()
3000

    
3001
            sql = 'select UID,[NAME],[DATETIME] from Drawings'
3002
            cursor.execute(sql)
3003
            rows = cursor.fetchall()
3004
            for row in rows:
3005
                res.append([row[0], row[1], row[2]])
3006

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

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

    
3019
        return res
3020

    
3021
    '''
3022
        @brief      update drawings
3023
        @author     yeonjin
3024
        @date       2019.08.07
3025
    '''
3026
    def updateDrawing(self, drawing):
3027
        import uuid
3028
        
3029
        try:
3030
            # Creates or opens a file called mydb with a SQLite3 DB
3031
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3032
            conn = sqlite3.connect(dbPath)
3033
            # Get a cursor object
3034
            cursor = conn.cursor()
3035
              
3036
            sql = """update Drawings
3037
                        set Name = ?
3038
                          , DateTime = ?
3039
                      where uid = ?"""
3040
            param = (drawing[0][1], drawing[0][2], drawing[0][0])
3041
            cursor.execute(sql, param)
3042

    
3043
            conn.commit()
3044

    
3045
        # Catch the exception
3046
        except Exception as ex:
3047
            # Roll back any change if something goes wrong
3048
            conn.rollback()
3049
            from App import App
3050

    
3051
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3052
            App.mainWnd().addMessage.emit(MessageType.Error, message)
3053
        finally:
3054
            # Close the db connection
3055
            conn.close()
3056
    '''
3057
        @brief      save drawings
3058
        @author     humkyung
3059
        @date       2018.11.03
3060
    '''
3061
    def saveDrawing(self, drawing):
3062
        import uuid
3063
        
3064
        try:
3065
            # Creates or opens a file called mydb with a SQLite3 DB
3066
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3067
            conn = sqlite3.connect(dbPath)
3068
            # Get a cursor object
3069
            cursor = conn.cursor()
3070
              
3071
            sql = 'insert or replace into Drawings(UID, [NAME], [DATETIME]) values(?, ?, ?)'
3072
            param = (drawing[0][0], drawing[0][1], drawing[0][2])
3073
            cursor.execute(sql, param)
3074

    
3075
            sql = "select Table_Name, Column_Name, Units_UID from DrawingsUnits where drawings_UID = '00000000-0000-0000-0000-000000000000'"
3076
            cursor.execute(sql)
3077
            rows = cursor.fetchall()
3078
            for row in rows:
3079
                sql = """insert or replace into DrawingsUnits
3080
                            (
3081
                                UID
3082
                                , Drawings_UID
3083
                                , Table_Name
3084
                                , Column_Name
3085
                                , Units_UID
3086
                             )
3087
                             values 
3088
                             (
3089
                                ?
3090
                                , ?
3091
                                , ?
3092
                                , ?
3093
                                , ?
3094
                             )"""
3095
                param = (str(uuid.uuid4()), drawing[0][0], row[0], row[1], row[2])
3096
                cursor.execute(sql, param)
3097

    
3098
            conn.commit()
3099

    
3100
        # Catch the exception
3101
        except Exception as ex:
3102
            # Roll back any change if something goes wrong
3103
            conn.rollback()
3104
            from App import App
3105

    
3106
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3107
            App.mainWnd().addMessage.emit(MessageType.Error, message)
3108
        finally:
3109
            # Close the db connection
3110
            conn.close()
3111

    
3112
    '''
3113
        @brief  get IsOriginDetect ComboBox Items
3114
    '''
3115
    def getIsOriginDetectComboBoxItems(self):
3116
        return [("원본 도면", 0), ("텍스트 제거 도면", 1)]
3117

    
3118
    '''
3119
        @brief  get IsOriginDetect ComboBox Items
3120
    '''
3121
    def getOcrOptionComboBoxItems(self):
3122
        return [("OCR 미적용", 0), ("일반 심볼", 1), ("Instrument 계통", 2)]
3123
    
3124

    
3125
    '''
3126
        @brief      Return Symbol Category Items
3127
        @author     yeonjin
3128
        @date       19.07.11
3129
    '''
3130
    def getSymbolCategoryList(self):
3131
        SymbolCategoryList = []
3132

    
3133
        try:
3134
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3135

    
3136
            conn = sqlite3.connect(dbPath)
3137
            cursor = conn.cursor()
3138
            sql = 'SELECT DISTINCT CATEGORY FROM SymbolType ORDER BY type ASC'
3139
            try:
3140
                cursor.execute(sql)
3141
                rows = cursor.fetchall()
3142
                for row in rows:
3143
                    SymbolCategoryList.append((row[0])) # category
3144
            except Exception as ex:
3145
                from App import App
3146

    
3147
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3148
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3149
        finally:
3150
            conn.close()
3151

    
3152
        return SymbolCategoryList
3153

    
3154

    
3155
    def getComponentByComponentUID(self, uid):
3156
        ComponentList = []
3157

    
3158
        try:
3159
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3160

    
3161
            conn = sqlite3.connect(dbPath)
3162
            cursor = conn.cursor()
3163
            
3164
            sql = """select c.uid
3165
                          , c.Name
3166
                          , c.Symbols_UID
3167
                          , t.Category
3168
                          , t.type
3169
                          , s.Name
3170
                          , s.OriginalPoint
3171
                          , c.X
3172
                          , c.Y
3173
                          , c.Rotation
3174
                          , c.Scale
3175
                          , p.uid
3176
                          , p.[Index]
3177
                          , p.x
3178
                          , p.y
3179
                          , p.ConnectedItem_UID
3180
                       from points p
3181
                       left join components c
3182
                         on p.components_uid = c.uid
3183
                       left join symbols s
3184
                         on c.Symbols_UID = s.UID    
3185
                       left join SymbolType t
3186
                         on s.symboltype_uid = t.uid
3187
                      where c.uid = ?
3188
                      order by p.[Index]"""
3189
            param = (uid,)                      
3190
            try:
3191
                cursor.execute(sql, param)
3192
                rows = cursor.fetchall()
3193
                for row in rows:
3194
                    data = []
3195
                    for index in range(len(cursor.description)):
3196
                        data.append(row[index])
3197
                    ComponentList.append(data) # Components_UID
3198
            except Exception as ex:
3199
                from App import App
3200

    
3201
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3202
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3203
        finally:
3204
            conn.close()
3205

    
3206
        return ComponentList
3207

    
3208
    '''
3209
        @brief      Return Components By DrawingUID
3210
        @author     yeonjin
3211
        @date       19.07.29
3212
    '''
3213
    def getComponentListByDrawingUID(self, uid):
3214
        ComponentList = []
3215

    
3216
        try:
3217
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3218

    
3219
            conn = sqlite3.connect(dbPath)
3220
            cursor = conn.cursor()
3221
            sql = 'select UID from Components where Drawings_UID = ? order by x desc'
3222
            try:
3223
                param = (uid, )
3224
                cursor.execute(sql, param)
3225
                rows = cursor.fetchall()
3226
                for row in rows:
3227
                    ComponentList.append((row[0])) # Components_UID
3228
            except Exception as ex:
3229
                from App import App
3230

    
3231
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3232
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3233
        finally:
3234
            conn.close()
3235

    
3236
        return ComponentList
3237

    
3238
    '''
3239
        @brief      Return Symbol Type Items By Category
3240
        @author     yeonjin
3241
        @date       19.07.11
3242
    '''
3243
    def getSymbolTypeListByCategory(self, category):
3244
        symbolTypeList = []
3245

    
3246
        try:
3247
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3248

    
3249
            conn = sqlite3.connect(dbPath)
3250
            cursor = conn.cursor()
3251
            sql = 'SELECT UID, Category, Type FROM SymbolType WHERE Category = "' + category + '"'
3252
            try:
3253
                cursor.execute(sql)
3254
                rows = cursor.fetchall()
3255
                for row in rows:
3256
                    symbolTypeList.append((row[0], row[1], row[2])) # UID, Category, Type
3257
            except Exception as ex:
3258
                from App import App
3259

    
3260
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3261
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3262
        finally:
3263
            conn.close()
3264

    
3265
        return symbolTypeList
3266

    
3267
    def getUnitsByDrawingName(self, drawingName):
3268
        unitsList = []
3269

    
3270
        try:
3271
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3272

    
3273
            conn = sqlite3.connect(dbPath)
3274
            cursor = conn.cursor()
3275
            sql = """select ifnull(d.display_name, u.column_name)
3276
                          , u.UNIT
3277
                       from units u
3278
                       left join displayNames d
3279
                         on u.TABLE_NAME = d.TABLE_NAME and u.COLUMN_NAME = d.COLUMN_NAME    
3280
                      where u.uid in (
3281
                                        select distinct du.units_uid
3282
                                          from drawings d
3283
                                         inner join drawingsunits du
3284
                                            on d.uid = du.drawings_uid
3285
                                         where d.name = ?
3286
                                     )
3287
                        and u.table_name = 'HMB'"""
3288
            param = (drawingName, )
3289
            try:
3290
                cursor.execute(sql, param)
3291
                rows = cursor.fetchall()
3292
                for row in rows:
3293
                    unitsList.append((row[0], row[1])) 
3294
            except Exception as ex:
3295
                from App import App
3296

    
3297
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3298
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3299
        finally:
3300
            conn.close()
3301

    
3302
        return unitsList
3303

    
3304
    def getColumnDisplayNames(self, uid, table):
3305
        columnDisplayNameList = []
3306

    
3307
        try:
3308
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3309

    
3310
            conn = sqlite3.connect(dbPath)
3311
            cursor = conn.cursor()
3312
            sql = """SELECT dn.DISPLAY_NAME
3313
                          , u.UNIT
3314
                       FROM DisplayNames dn
3315
                       left join drawingsUnits du
3316
                         on dn.TABLE_NAME = du.Table_Name and dn.COLUMN_NAME = du.Column_Name
3317
                       left join Units u
3318
                         on du.Units_UID = u.UID
3319
                      where du.Drawings_UID = ?
3320
                        and dn.Table_Name = ?
3321
                      order by dn.[Order]"""    
3322
            try:
3323
                param = (uid, table,)
3324
                cursor.execute(sql, param)
3325
  
3326
                rows = cursor.fetchall()
3327
                for row in rows:
3328
                    columnDisplayNameList.append((row[0], row[1])) # Display_Name
3329
            except Exception as ex:
3330
                from App import App
3331

    
3332
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3333
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3334
        finally:
3335
            conn.close()
3336

    
3337
        return columnDisplayNameList
3338

    
3339

    
3340

    
3341
    '''
3342
        @brief      Return Symbol Type Items
3343
        @author     Jeongwoo
3344
        @date       18.04.20
3345
        @history    18.05.08    Jeongwoo type index changed
3346
    '''
3347
    def getSymbolTypeList(self):
3348
        symbolTypeList = []
3349

    
3350
        try:
3351
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3352

    
3353
            conn = sqlite3.connect(dbPath)
3354
            cursor = conn.cursor()
3355
            sql = 'SELECT * FROM SymbolType ORDER BY type ASC'
3356
            try:
3357
                cursor.execute(sql)
3358
                rows = cursor.fetchall()
3359
                for row in rows:
3360
                    symbolTypeList.append((row[0], row[1], row[2])) # UID, category, type
3361
            except Exception as ex:
3362
                from App import App
3363

    
3364
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3365
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3366
        finally:
3367
            conn.close()
3368

    
3369
        return symbolTypeList
3370

    
3371
    '''
3372
        @brief      Get Symbol Category by Symbol Type
3373
        @author     Jeongwoo
3374
        @date       2018.05.09
3375
    '''
3376
    def getSymbolCategoryByType(self, type):
3377
        category = None
3378
        try:
3379
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3380
            
3381
            conn = sqlite3.connect(dbPath)
3382
            cursor = conn.cursor()
3383
            sql = 'SELECT Category FROM SymbolType WHERE type = "' + type + '"'
3384
            cursor.execute(sql)
3385
            rows = cursor.fetchall()
3386
            if rows is not None and len(rows) > 0:
3387
                category = rows[0][0]
3388
        except Exception as ex:
3389
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
3390
        finally:
3391
            conn.close()
3392

    
3393
        return category
3394

    
3395
    '''
3396
        @brief      Check Symbol Type is included in 'Equipment' Category
3397
        @author     Jeongwoo
3398
        @date       2018.05.09
3399
    '''
3400
    def isEquipmentType(self, type):
3401
        category = self.getSymbolCategoryByType(type)
3402
        return (category is not None and category == 'Equipment')
3403

    
3404
    '''
3405
        @brief      Return Symbol Type Items with "None"
3406
        @author     Jeongwoo
3407
        @date       18.04.06
3408
        @history    Seperate SymbolTypeList and "None"
3409
    '''
3410
    def getSymbolTypeComboBoxItems(self):
3411
        symbolTypeList = self.getSymbolTypeList()
3412
        symbolTypeList.insert(0, ('None', 'None', 'None'))
3413

    
3414
        return symbolTypeList
3415

    
3416
    '''
3417
        @brief  get Base Symbol ComboBox Items
3418
    '''
3419
    def getBaseSymbolComboBoxItems(self, type = None):
3420
        bsymbolNameList = self.getSymbolNameListByType(type)
3421
        bsymbolNameList.sort()
3422
        bsymbolNameList.insert(0, "None")
3423
        return bsymbolNameList
3424

    
3425
    '''
3426
        @brief  get Additional Symbol ComboBox Items
3427
    '''
3428
    def getAdditionalSymbolComboBoxItems(self):
3429
        asymbolNameList = self.getSymbolNameList()
3430
        asymbolNameList.sort()
3431
        asymbolNameList.insert(0, "None")
3432
        return asymbolNameList
3433

    
3434
    '''
3435
        @brief  get Additional Symbol's default direction ComboBox Items
3436
    '''
3437
    def getDefaultSymbolDirectionComboBoxItems(self):
3438
        return [("UP", 0), ("DOWN", 2), ("LEFT", 3), ("RIGHT", 1)]
3439
    
3440
    '''
3441
        @brief  getter of activeDrawing
3442
        @author humkyung
3443
        @date   2018.07.07
3444
    '''
3445
    @property
3446
    def activeDrawing(self):
3447
        return self._activeDrawing
3448

    
3449
    '''
3450
        @brief  setter of activeDrawing
3451
        @author humkyung
3452
        @date   2018.07.07
3453
    '''
3454
    @activeDrawing.setter
3455
    def activeDrawing(self, value):
3456
        self._activeDrawing = value
3457

    
3458
    def getColNames(self, table):
3459
        """
3460
        return column names of given table and attribute names if tabe is VALVE_DATA_LIST or EQUIPMET_DATA_LIST
3461
        """
3462
        res = None
3463
        try:
3464
            # Creates or opens a file called mydb with a SQLite3 DB
3465
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3466
            conn = sqlite3.connect(dbPath)
3467
            cursor = conn.execute('select * from {}'.format(table))
3468
            res = [col_name[0] for col_name in cursor.description]
3469

    
3470
            if table == 'EQUIPMET_DATA_LIST' or table == 'VALVE_DATA_LIST':
3471
                sql = 'select distinct c.Attribute from {} a left join Attributes b on a.uid=b.Components_UID ' \
3472
                                                            'left join SymbolAttribute c on b.SymbolAttribute_UID=c.UID where c.Attribute is not NULL'.format(table)
3473
                cursor = conn.execute(sql)
3474
                rows = cursor.fetchall()
3475
                for row in rows:
3476
                    res.append(row[0])
3477
        # Catch the exception
3478
        except Exception as ex:
3479
            # Roll back any change if something goes wrong
3480
            conn.rollback()
3481
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
3482
        finally:
3483
            # Close the db connection
3484
            conn.close()
3485

    
3486
        return res
3487
    
3488
    def add_column_into_table(self, table, columnName):
3489
        '''
3490
            @brief  add column into table
3491
            @author euisung
3492
            @date   2019.03.13
3493
        '''
3494
        err = False
3495
        try:
3496
            # Creates or opens a file called mydb with a SQLite3 DB
3497
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3498
            conn = sqlite3.connect(dbPath)
3499
            # Get a cursor object
3500
            cursor = conn.cursor()
3501
            sql = "alter table {} add {}".format(table, columnName)
3502
            cursor.execute(sql)
3503

    
3504
            conn.commit()
3505

    
3506
        # Catch the exception
3507
        except Exception as ex:
3508
            # Roll back any change if something goes wrong
3509
            conn.rollback()
3510
            err = True
3511
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
3512
        finally:
3513
            # Close the db connection
3514
            conn.close()
3515
            return (True if not err else False)
3516

    
3517
    def edit_column_Name_in_table(self, table, columnName, newColName):
3518
        '''
3519
            @brief  edit column into table
3520
            @author euisung
3521
            @date   2019.03.13
3522
        '''
3523
        err = False
3524
        colNames = AppDocData.instance().getColNames(table)
3525

    
3526
        for index in range(len(colNames)):
3527
            if colNames[index] == columnName:
3528
                colNames[index] = newColName
3529
                break
3530

    
3531
        try:
3532
            # Creates or opens a file called mydb with a SQLite3 DB
3533
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3534
            conn = sqlite3.connect(dbPath)
3535
            # Get a cursor object
3536
            cursor = conn.cursor()
3537
            sql = "ALTER TABLE {} RENAME TO {}".format(table, table + '_orig')
3538
            cursor.execute(sql)
3539
            value = []
3540
            for colName in colNames:
3541
                value.append(colName + ' TEXT')
3542
            sql = "CREATE TABLE {}({}, CONSTRAINT '{}_PK' PRIMARY KEY('UID'))".format(table, ','.join(value), table)
3543
            cursor.execute(sql)
3544
            sql = "INSERT INTO {} SELECT * FROM {}".format(table, table + '_orig')
3545
            cursor.execute(sql)
3546
            sql = "DROP TABLE {}".format(table + '_orig')
3547
            cursor.execute(sql)
3548

    
3549
            conn.commit()
3550

    
3551
        # Catch the exception
3552
        except Exception as ex:
3553
            # Roll back any change if something goes wrong
3554
            conn.rollback()
3555
            err = True
3556
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
3557
        finally:
3558
            # Close the db connection
3559
            conn.close()
3560
            return (True if not err else False)
3561

    
3562
    '''
3563
        @brief  getter of OCRData
3564
        @author humkyung
3565
        @date   2018.11.19
3566
    '''
3567
    @property
3568
    def OCRData(self):
3569
        if self._OCRData is None:
3570
            configs = self.getConfigs('Text Recognition', 'OCR Data')
3571
            self._OCRData = configs[0].value if 1 == len(configs) else 'eng'
3572

    
3573
        return self._OCRData
3574

    
3575
    '''
3576
        @brief  setter of OCRData
3577
        @author humkyung
3578
        @date   2018.11.19
3579
    '''
3580
    @OCRData.setter
3581
    def OCRData(self, value):
3582
        self._OCRData = value
클립보드 이미지 추가 (최대 크기: 500 MB)