프로젝트

일반

사용자정보

통계
| 개정판:

hytos / HYTOS / HYTOS / AppDocData.py @ 50bad001

이력 | 보기 | 이력해설 | 다운로드 (128 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 DB file path in ProgramData
156
        @author     Jeongwoo
157
        @date       2018.06.27
158
        @history    2018.06.29  Jeongwoo    Change method to get template db path
159
    '''
160
    def getTemplateDbPath(self):
161
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
162
        templateDbPath = os.path.join(path, 'Template.db')
163
        return templateDbPath
164

    
165
    def getAppDbPath(self):
166
        """
167
        @brief      Get application DB file path in ProgramData
168
        @author     humkyung
169
        @date       2018.10.01
170
        """
171

    
172
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
173
        app_database = os.path.join(path, 'App.db')
174
        return app_database 
175

    
176
    '''
177
        @brief  getter of colors 
178
        @author humkyung
179
        @date   2018.06.18
180
    '''
181
    @property
182
    def colors(self):
183
        import random
184

    
185
        if self._colors is None or self._colors == []:
186
            self._colors = []
187
            try:
188
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath() , AppDocData.DATABASE)
189

    
190
                conn = sqlite3.connect(dbPath)
191
                cursor = conn.cursor()
192
                sql = 'SELECT UID,RED,GREEN,BLUE FROM Colors'
193
                cursor.execute(sql)
194
                rows = cursor.fetchall()
195
                for row in rows:
196
                    self._colors.append(Color(int(row[0]), int(row[1]), int(row[2]), int(row[3])))
197
            # Catch the exception
198
            except Exception as ex:
199
                # Roll back any change if something goes wrong
200
                conn.rollback()
201

    
202
                from App import App 
203
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
204
                App.mainWnd().addMessage.emit(MessageType.Error, message)
205
            finally:
206
                conn.close()
207

    
208
        return self._colors.pop(random.randrange(0, len(self._colors)))
209

    
210
    '''
211
        @brief  setter of colors
212
        @author humkyung
213
        @date   2018.06.18
214
    '''
215
    @colors.setter
216
    def colors(self, value):
217
        self._colors = value
218

    
219
    '''
220
        @brief      set image file path
221
        @author     humkyung
222
        @date       2018.07.30
223
    '''
224
    def setImgFilePath(self, path):
225
        self._imgFilePath = path
226
        self.imgName = os.path.splitext(os.path.basename(self._imgFilePath))[0]
227

    
228
    '''
229
        @brief  getter of line type configs
230
        @author humkyung
231
        @date   2018.06.28
232
    '''
233
    @property
234
    def lineTypeConfigs(self):
235
        from PyQt5.QtCore import Qt
236

    
237
        if self._lineTypeConfigs is None:
238
            self._lineTypeConfigs = []
239

    
240
            styleMap = [('SolidLine', Qt.SolidLine), ('DashLine', Qt.DashLine), ('DotLine', Qt.DotLine), ('DashDotLine', Qt.DashDotLine), 
241
                ('DashDotDotLine', Qt.DashDotDotLine), ('CustomDashLine', Qt.CustomDashLine)]
242

    
243
            configs = self.getConfigs('LineTypes')
244
            for config in configs:
245
                color, width, _style, transparent = config.value.split(',')
246
                matches = [param for param in styleMap if param[0] == _style]
247
                style = matches[0][1] if matches else Qt.SolidLine
248
                self._lineTypeConfigs.append((config.key, color, int(width), style, float(transparent)))
249
        
250
        return self._lineTypeConfigs
251

    
252
    '''
253
        @brief  setter of line type configs
254
        @author humkyung
255
        @date   2018.06.28
256
    '''
257
    @lineTypeConfigs.setter
258
    def lineTypeConfigs(self, value):
259
        self._lineTypeConfigs = value
260

    
261
    '''
262
        @brief  get line type config of given line type
263
        @author humkyung
264
        @date   2018.06.28
265
    '''
266
    def getLineTypeConfig(self, lineType):
267
        from PyQt5.QtCore import Qt
268

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

    
272
    def setCurrentPidSource(self, image):
273
        self.imgWidth, self.imgHeight = image.size
274

    
275
        self.currentPidSource = Source(image)
276

    
277
    def getCurrentPidSource(self):
278
        return self.currentPidSource
279

    
280
    '''
281
        @brief      Check if data exists or not
282
        @author     Jeongwoo
283
        @date       2018.05.03
284
    '''
285
    def isExistData(self, fieldName, data):
286
        rows = None
287
        try:
288
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
289

    
290
            conn = sqlite3.connect(dbPath)
291
            cursor = conn.cursor()
292
            sql = ""
293
            if isinstance(data, str):
294
                sql = "SELECT * FROM Symbol WHERE " + fieldName + " = '"+ data +"'"
295
            else:
296
                sql = "SELECT * FROM Symbol WHERE " + fieldName + " = "+ str(data) +""
297
            cursor.execute(sql)
298
            rows = cursor.fetchall()
299
        # Catch the exception
300
        except Exception as ex:
301
            # Roll back any change if something goes wrong
302
            conn.rollback()
303
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
304
        finally:
305
            conn.close()
306
            if rows is not None and len(rows) > 0:
307
                return True
308
            else:
309
                return False
310

    
311
    '''
312
        @brief      Check if exist file name or not
313
        @author     Jeongwoo
314
        @date       2018.05.03
315
    '''
316
    def isExistFileName(self, name):
317
        rows = None
318
        try:
319
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
320
            conn = sqlite3.connect(dbPath)
321
            cursor = conn.cursor()
322
            sql = "SELECT * FROM Symbol WHERE name = '"+ name +"'"
323
            cursor.execute(sql)
324
            rows = cursor.fetchall()
325
        # Catch the exception
326
        except Exception as ex:
327
            # Roll back any change if something goes wrong
328
            conn.rollback()
329
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
330
        finally:
331
            conn.close()
332
            if rows is not None and len(rows) > 0:
333
                return True
334
            else:
335
                return False
336

    
337
    '''
338
        @brief      Insert new symbol into Symbol Table, Moved from SG_DbHelper
339
        @author     Jeongwoo
340
        @date       2018.05.03
341
    '''
342
    def insertSymbol(self, symbol):
343
        isAdded = False
344
        try:
345
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
346
            conn = sqlite3.connect(dbPath)
347
            
348
            INSERT_SYMBOL_SQL = """
349
                INSERT INTO Symbol(name, SymbolType_UID, threshold, minMatchPoint, isDetectOrigin, rotationCount, ocrOption, isContainChild, originalPoint, connectionPoint, baseSymbol, additionalSymbol, isExceptDetect, hasInstrumentLabel, width, height, flip) 
350
                VALUES(?, (select UID from SymbolType where Type=?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
351
            """
352

    
353
            cursor = conn.cursor()
354
            query = ( symbol.getName(), symbol.getType(), symbol.getThreshold()
355
                           , symbol.getMinMatchCount(), symbol.getIsDetectOnOrigin(), symbol.getRotationCount()
356
                           , symbol.getOcrOption(), symbol.getIsContainChild()
357
                           , symbol.getOriginalPoint(), symbol.getConnectionPoint()
358
                           , symbol.getBaseSymbol(), symbol.getAdditionalSymbol(), symbol.getIsExceptDetect(), symbol.getHasInstrumentLabel()
359
                           , symbol.width, symbol.height, symbol.detectFlip)
360
            cursor.execute(INSERT_SYMBOL_SQL, query)
361
            conn.commit()
362
            isAdded = True
363
        # Catch the exception
364
        except Exception as ex:
365
            # Roll back any change if something goes wrong
366
            conn.rollback()
367
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
368
        finally:
369
            conn.close()
370
            return (isAdded, symbol.getType(), symbol.getName(), symbol.getPath())
371

    
372
    '''
373
        @brief      Update symbol in Symbol Table, Moved from SG_DbHelper
374
        @author     Jeongwoo
375
        @date       2018.05.03
376
    '''
377
    def updateSymbol(self, symbol):
378
        isUpdated = False
379
        try:
380
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
381
            conn = sqlite3.connect(dbPath)
382
            
383
            UPDATE_SYMBOL_SQL = """
384
                UPDATE Symbols
385
                   SET name = ?
386
                     , originalPoint = ?
387
                     , connectionPoint = ?
388
                 WHERE uid = ?
389
            """
390
            
391
            cursor = conn.cursor()
392
            query = (symbol.getName(), symbol.getOriginalPoint(), symbol.getConnectionPoint(), symbol.getUid())
393
            cursor.execute(UPDATE_SYMBOL_SQL, query)
394
            conn.commit()
395
            isUpdated = True
396
        # Catch the exception
397
        except Exception as ex:
398
            # Roll back any change if something goes wrong
399
            conn.rollback()
400
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
401
        finally:
402
            conn.close()
403
            return (isUpdated, symbol.getType(), symbol.getName(), symbol.getPath())
404

    
405
    '''
406
        @brief      Get Detecting Target Symbol List (Field 'isExceptDetect' == False(0))
407
        @author     Jeongwoo
408
        @date       18.04.24
409
        @history    humkyung 2018.06.28 select symbol order by threshold descending
410
    '''
411
    def getTargetSymbolList(self):
412
        targetSymbolList = []
413

    
414
        try:
415
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
416

    
417
            conn = sqlite3.connect(dbPath)
418
            cursor = conn.cursor()
419
            #sql = """SELECT a.UID,a.Name,b.Type,a.Threshold,a.MinMatchPoint,a.IsDetectOrigin,a.RotationCount,a.OCROption,a.IsContainChild,a.OriginalPoint,a.ConnectionPoint,
420
            #        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"""
421

    
422
            sql = """select s.UID
423
                          , s.Name
424
                          , t.Category
425
                          , t.Type
426
                          , s.OriginalPoint
427
                          , s.ConnectionPoint
428
                       from Symbols s 
429
                      inner join SymbolType t
430
                         on s.SymbolType_UID = t.UID"""
431

    
432
            try:
433
                cursor.execute(sql)
434
                rows = cursor.fetchall()
435
                for row in rows:
436
                    sym = symbol.SymbolBase(row[0], row[1], row[2], row[3], row[4], row[5])
437
                    targetSymbolList.append(sym)
438
            except Exception as ex:
439
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
440
        finally:
441
            conn.close()
442

    
443
        return targetSymbolList
444

    
445
    '''
446
        @brief  build application database
447
        @author humkyung
448
        @date   2018.04.20
449
    '''
450
    def buildAppDatabase(self):
451
        try:
452
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
453
            appDatabaseFilePath = os.path.join(path, 'App.db')
454

    
455
            # Creates or opens a file called mydb with a SQLite3 DB
456
            conn = sqlite3.connect(appDatabaseFilePath)
457
            with conn:
458
                # Get a cursor object
459
                cursor = conn.cursor()
460

    
461
                sqlFiles = ['App.sql']
462
                for sqlFile in sqlFiles:
463
                    filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', sqlFile)
464
                    try:
465
                        file = QFile(filePath)
466
                        file.open(QFile.ReadOnly)
467
                        sql = file.readAll()
468
                        sql = str(sql, encoding='utf8')
469
                        cursor.executescript(sql)
470
                    finally:
471
                        file.close()
472
                conn.commit()
473
        # Catch the exception
474
        except Exception as ex:
475
            # Roll back any change if something goes wrong
476
            conn.rollback()
477
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
478

    
479
    '''
480
        @brief  load app style
481
        @author humkyung
482
        @date   2018.04.20
483
    '''
484
    def loadAppStyle(self):
485
        style = 'Fusion'
486

    
487
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
488
        if not os.path.exists(path): os.makedirs(path)
489

    
490
        self.buildAppDatabase()
491
        try:
492
            appDatabaseFilePath = os.path.join(path, 'App.db')
493
            # Creates or opens a file called mydb with a SQLite3 DB
494
            conn = sqlite3.connect(appDatabaseFilePath)
495
            # Get a cursor object
496
            cursor = conn.cursor()
497

    
498
            sql = "select Value from Configuration where Section='App' and Key='Style'" 
499
            cursor.execute(sql)
500
            rows = cursor.fetchall()
501
            style = rows[0][0] if 1 == len(rows) else 'Fusion'
502
        # Catch the exception
503
        except Exception as ex:
504
            # Roll back any change if something goes wrong
505
            conn.rollback()
506
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
507
        finally:
508
            # Close the db connection
509
            conn.close()
510

    
511
        return style
512

    
513
    '''
514
        @brief  load app styles and then return a list
515
        @author humkyung
516
        @date   2018.04.20
517
    '''
518
    def loadAppStyles(self):
519
        styles = []
520

    
521
        try:
522
            self.buildAppDatabase()
523

    
524
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
525
            appDatabaseFilePath = os.path.join(path, 'App.db')
526

    
527
            # Creates or opens a file called mydb with a SQLite3 DB
528
            conn = sqlite3.connect(appDatabaseFilePath)
529
            # Get a cursor object
530
            cursor = conn.cursor()
531

    
532
            sql = 'select UID,Value from Styles'
533
            cursor.execute(sql)
534
            rows = cursor.fetchall()
535
            for row in rows: styles.append(row[1])
536
            if 0 == len(rows): rows.append('fusion')
537
        # Catch the exception
538
        except Exception as ex:
539
            # Roll back any change if something goes wrong
540
            conn.rollback()
541
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
542
        finally:
543
            # Close the db connection
544
            conn.close()
545

    
546
        return styles
547

    
548
    @property
549
    def border_file_path(self):
550
        """ return border file path """
551

    
552
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
553
        return os.path.join(path, 'Border.png')
554

    
555
    @property
556
    def symbol_file_path(self):
557
        """ return svg symbol file path """
558

    
559
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
560
        return os.path.join(path, 'svg')
561

    
562
    '''
563
        @brief  Get current Project
564
    '''
565
    def getCurrentProject(self):
566
        return self.project
567

    
568
    '''
569
        @brief      return project database path
570
        @history    humkyung 2018.04.19 return Project.db in Program Data folder instead of PROJECT_DB_PATH variable
571
    '''
572
    def getPrjDatabasePath(self):
573
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
574
        if not os.path.exists(path): os.makedirs(path)
575

    
576
        prjDatabaseFilePath = os.path.join(path, 'Project.db')
577
        try:
578
            # Creates or opens a file called mydb with a SQLite3 DB
579
            conn = sqlite3.connect(prjDatabaseFilePath)
580
            # Get a cursor object
581
            cursor = conn.cursor()
582

    
583
            filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', 'Project.Projects.sql')
584
            try:
585
                file = QFile(filePath)
586
                file.open(QFile.ReadOnly)
587
                sql = file.readAll()
588
                sql = str(sql, encoding='utf8')
589
                cursor.executescript(sql)
590
            finally:
591
                file.close()
592
            conn.commit()
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 prjDatabaseFilePath
603

    
604
    def getErrorItemSvgPath(self):
605
        '''
606
            @brief  return error item svg path
607
            @author euisung
608
            @date   2019.04.02
609
        '''
610
        return os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME, 'Explode.svg')
611

    
612
    def updateTitleBlockProperties(self, titleBlockProps):
613
        '''
614
            @brief  update title block properties
615
            @author euisung
616
            @date   2018.11.09
617
        '''
618
        try:
619
            for titleBlockProp in titleBlockProps:
620
                titleBlockProp[1] = self.imgName + '!@!' + titleBlockProp[1]
621
            originTitleBlockProps = self.getTitleBlockProperties()
622
            deletedTitleBlockProps = []
623
            for originTitleBlockProp in originTitleBlockProps:
624
                for titleBlockProp in titleBlockProps:
625
                    # uid compare for determine delete props
626
                    if originTitleBlockProp[0] == titleBlockProp[0]:
627
                        break
628
                deletedTitleBlockProps.append(originTitleBlockProp[0])
629
            
630
            # Creates or opens a file called mydb with a SQLite3 DB
631
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
632
            conn = sqlite3.connect(dbPath)
633
            # Get a cursor object
634
            cursor = conn.cursor()
635

    
636
            for deletedTitleBlockProp in deletedTitleBlockProps:
637
                sql = "delete from TitleBlockProperties where UID='{}'".format(deletedTitleBlockProp)
638
                cursor.execute(sql)
639

    
640
            for titleBlockProp in titleBlockProps:
641
                sql = "insert or replace into TitleBlockProperties values(?,?,?)"
642
                param = (titleBlockProp[0], titleBlockProp[1], titleBlockProp[2]) # uid, name, area
643
                cursor.execute(sql, param)
644
            conn.commit()
645
        # Catch the exception
646
        except Exception as ex:
647
            # Roll back any change if something goes wrong
648
            conn.rollback()
649
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
650
        finally:
651
            # Close the db connection
652
            conn.close()
653

    
654
        self._titleBlockProperties = None
655
    
656
    def getTitleBlockProperties(self):
657
        '''
658
            @brief  return title block properties
659
            @author euisung
660
            @date   2018.11.09
661
        '''
662
        res = None
663
        if True:#self._titleBlockProperties is None:
664
            try:
665
                self._titleBlockProperties = []
666

    
667
                # Creates or opens a file called mydb with a SQLite3 DB
668
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
669
                db = sqlite3.connect(dbPath)
670
                # Get a cursor object
671
                cursor = db.cursor()
672

    
673
                sql = "select UID, Name, AREA from TitleBlockProperties" 
674
                cursor.execute(sql)
675
                rows = cursor.fetchall()
676
                for row in rows:
677
                    if row[1].split('!@!')[0] != self.imgName:
678
                        continue
679
                    else:
680
                        attr = []
681
                        attr.append(row[0]) # uid
682
                        attr.append(row[1].split('!@!')[1]) # name
683
                        attr.append(row[2]) # area
684
                        self._titleBlockProperties.append(attr)
685
                
686
                res = self._titleBlockProperties
687
            # Catch the exception
688
            except Exception as ex:
689
                # Roll back any change if something goes wrong
690
                db.rollback()
691
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
692
            finally:
693
                # Close the db connection
694
                db.close()
695
        else:
696
            res = self._titleBlockProperties
697

    
698
        return res
699

    
700
    def clearLineNoProperties(self):
701
        self._lineNoProperties = None
702

    
703
    '''
704
        @brief  return line properties
705
        @author humkyung
706
        @date   2018.04.09
707
    '''
708
    def getLineProperties(self):
709
        from SymbolAttr import SymbolAttr
710

    
711
        res = None
712
        if self._lineNoProperties is None:
713
            try:
714
                self._lineNoProperties = []
715

    
716
                # Creates or opens a file called mydb with a SQLite3 DB
717
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
718
                db = sqlite3.connect(dbPath)
719
                # Get a cursor object
720
                cursor = db.cursor()
721

    
722
                sql = "select UID, Name, DisplayName, Type, LimitNumber, [index] from LineProperties order by [index]" 
723
                cursor.execute(sql)
724
                rows = cursor.fetchall()
725
                for row in rows:
726
                    attr = SymbolAttr()
727
                    attr.UID = row[0]
728
                    attr.Attribute = row[1]
729
                    attr.DisplayAttribute = row[2]
730
                    attr.AttributeType = row[3]
731
                    attr.Length = row[4]
732
                    self._lineNoProperties.append(attr)
733
                
734
                res = self._lineNoProperties
735
            # Catch the exception
736
            except Exception as ex:
737
                # Roll back any change if something goes wrong
738
                db.rollback()
739
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
740
            finally:
741
                # Close the db connection
742
                db.close()
743
        else:
744
            res = self._lineNoProperties
745

    
746
        return res
747

    
748
    '''
749
        @brief  return line properties
750
        @author humkyung
751
        @date   2018.04.09
752
    '''
753
    def getLinePropertiesByUID(self, UID):
754
        from SymbolAttr import SymbolAttr
755

    
756
        res = []
757
        try:
758
            # Creates or opens a file called mydb with a SQLite3 DB
759
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
760
            db = sqlite3.connect(dbPath)
761
            # Get a cursor object
762
            cursor = db.cursor()
763

    
764
            sql = "select UID, Name, DisplayName, Type, LimitNumber, [index] from LineProperties where uid = '{}'".format(UID)
765
            cursor.execute(sql)
766
            rows = cursor.fetchall()
767
            for row in rows:
768
                attr = SymbolAttr()
769
                attr.UID = row[0]
770
                attr.Attribute = row[1]
771
                attr.DisplayAttribute = row[2]
772
                attr.AttributeType = row[3]
773
                attr.Length = row[4]
774
                res.append(attr)
775
        # Catch the exception
776
        except Exception as ex:
777
            # Roll back any change if something goes wrong
778
            db.rollback()
779
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
780
        finally:
781
            # Close the db connection
782
            db.close()
783

    
784
        return res
785

    
786
    def getRoughness(self):
787
        res = []
788

    
789
        conn = sqlite3.connect(self.activeDrawing.path)
790
        with conn:
791
            try:
792
                conn.row_factory = sqlite3.Row
793
                # Get a cursor object
794
                cursor = conn.cursor()
795

    
796
                sql = "select UID, Material, Meter, Inch, Feet, Milimeter from Roughness" 
797
                cursor.execute(sql)
798
                rows = cursor.fetchall()
799
                for row in rows:                
800
                    res.append((row[0], row[1], row[2], row[3], row[4], row[5]))
801
            # Catch the exception
802
            except Exception as ex:
803
                # Roll back any change if something goes wrong
804
                conn.rollback()
805
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
806

    
807
        return res
808

    
809
    def getInsideDiameter(self, nominaldiameter_uid, schedule_uid):
810
        res = []
811
        try:
812
            # Creates or opens a file called mydb with a SQLite3 DB
813
            #dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
814
            #db = sqlite3.connect(dbPath)
815
            db = sqlite3.connect(self.activeDrawing.path)
816
            # Get a cursor object
817
            cursor = db.cursor()
818

    
819
            sql = """select UID
820
                          , Milimeter
821
                          , Inch 
822
                       from InsideDiameter
823
                      where NominalDiameter_UID = ?
824
                        and Schedule_UID = ?"""
825

    
826
            param = (nominaldiameter_uid, schedule_uid)
827
            cursor.execute(sql, param)
828
            rows = cursor.fetchall()
829
            for row in rows:                
830
                res.append((row[0], row[1], row[2]))
831
        # Catch the exception
832
        except Exception as ex:
833
            # Roll back any change if something goes wrong
834
            db.rollback()
835
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
836
        finally:
837
            # Close the db connection
838
            db.close()
839

    
840
        return res
841

    
842
    def getSchedule(self):
843
        res = []
844

    
845
        conn = sqlite3.connect(self.activeDrawing.path)
846
        with conn:
847
            try:
848
                # Get a cursor object
849
                cursor = conn.cursor()
850

    
851
                sql = "select UID, No from Schedule" 
852
                cursor.execute(sql)
853
                rows = cursor.fetchall()
854
                for row in rows:                
855
                    res.append((row[0], row[1]))
856
            # Catch the exception
857
            except Exception as ex:
858
                # Roll back any change if something goes wrong
859
                conn.rollback()
860
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
861

    
862
        return res
863

    
864
    def getNominalDiameter(self):
865
        
866
        res = []
867

    
868
        # Creates or opens a file called mydb with a SQLite3 DB
869
        conn = sqlite3.connect(self.activeDrawing.path)
870
        with conn:
871
            try:
872
                # Get a cursor object
873
                cursor = conn.cursor()
874

    
875
                sql = "select UID, Milimeter, Inch from NominalDiameter" 
876
                cursor.execute(sql)
877
                rows = cursor.fetchall()
878
                for row in rows:                
879
                    res.append((row[0], row[1], row[2]))
880
            # Catch the exception
881
            except Exception as ex:
882
                # Roll back any change if something goes wrong
883
                conn.rollback()
884
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
885

    
886
        return res
887

    
888
    '''
889
        @brief  return line types 
890
        @author humkyung
891
        @date   2018.06.27
892
    '''
893
    def getLineTypes(self):
894
        from LineTypeConditions import LineTypeConditions
895

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

    
904
            sql = "select UID,Name,Type1,Conditions1,Type2,Conditions2 from LineTypes order by Name" 
905
            cursor.execute(sql)
906
            rows = cursor.fetchall()
907
            for row in rows:
908
                line_type = LineTypeConditions(row[0], row[1])
909
                line_type._conditions[0][0] = row[2]
910
                line_type._conditions[0][1] = row[3]
911
                line_type._conditions[1][0] = row[4]
912
                line_type._conditions[1][1] = row[5]
913
                res.append(line_type)
914
        # Catch the exception
915
        except Exception as ex:
916
            # Roll back any change if something goes wrong
917
            db.rollback()
918
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
919
        finally:
920
            # Close the db connection
921
            db.close()
922

    
923
        return res
924

    
925
    '''
926
        @brief      Insert New Project Info
927
        @author     Jeongwoo
928
        @date       2018.04.06
929
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
930
    '''
931
    def insertProjectInfo(self, desc, dir):
932
        try:
933
            prjDatabaseFilePath = self.getPrjDatabasePath()
934
            conn = sqlite3.connect(prjDatabaseFilePath)
935
            folderName = dir.split('/')[-1]
936
            if folderName:
937
                nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
938
                sql = "insert or replace into Projects(Name, [Desc], Path, CreatedDate, UpdatedDate) values(?, ?, ?, ?, ?)"
939
                param = (folderName, desc, dir, nowDate, nowDate)
940
    
941
                cursor = conn.cursor()
942
                cursor.execute(sql, param)
943
                conn.commit()
944
            else:
945
                print("Empty folder name")
946
        except Exception as ex:
947
            # Roll back any change if something goes wrong
948
            conn.rollback()
949
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
950
        finally:
951
            conn.close()
952

    
953
    def removeProjectInfo(self, targetProject):
954
        '''
955
        @brief      Remove Project Info
956
        @author     Euisung
957
        @date       2019.01.28
958
        '''
959
        try:
960
            prjDatabaseFilePath = self.getPrjDatabasePath()
961
            conn = sqlite3.connect(prjDatabaseFilePath)
962
            sql = "delete from Projects where Id = '{}'".format(targetProject.id)
963
            cur = conn.cursor()
964
            cur.execute(sql)
965
            conn.commit()
966
        except Exception as ex:
967
            # Roll back any change if something goes wrong
968
            conn.rollback()
969
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
970
        finally:
971
            conn.close()
972

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

    
999
    '''
1000
        @brief  get project list from database
1001
        @history    humkyung 2018.04.18 add only project which's project exists
1002
    '''
1003
    def getProjectList(self):
1004
        from Project import Project
1005

    
1006
        projectList = []
1007

    
1008
        try:
1009
            conn = sqlite3.connect(self.getPrjDatabasePath())
1010
            cursor = conn.cursor()
1011
            sql = 'SELECT id,name,[desc],path,createddate,updateddate  FROM Projects ORDER BY UpdatedDate DESC'
1012
            try:
1013
                cursor.execute(sql)
1014
                rows = cursor.fetchall()
1015
                for row in rows:
1016
                    if os.path.isdir(row[3]):   # check if folder exists
1017
                        projectList.append(Project(row[0], row[1], desc=row[2], path=row[3], createDate=row[4], updateDate=row[5]))
1018
            except Exception as ex:
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
        return projectList
1024

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

    
1044
    '''
1045
        @brief  get line no configuration
1046
        @author humkyung
1047
        @date   2018.04.16
1048
    '''
1049
    def getLineNoConfiguration(self):
1050
        res = None
1051
        try:
1052
            # Creates or opens a file called mydb with a SQLite3 DB
1053
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1054
            conn = sqlite3.connect(dbPath)
1055
            # Get a cursor object
1056
            cursor = conn.cursor()
1057

    
1058
            delimiter = None
1059
            sql = "select * from configuration where section='Line No' and key='Delimiter"
1060
            cursor.execute(sql)
1061
            rows = cursor.fetchall()
1062
            if len(rows) == 1:
1063
                delimiter = rows[0][2]
1064

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

    
1082
    '''
1083
        @brief  get area list
1084
        @author humkyung
1085
        @history    euisung     2018.11.20 (0,0),(0,0) process add
1086
    '''
1087
    def getAreaList(self):
1088
        from Area import Area
1089

    
1090
        if len(self._areas) == 0:
1091
            try:
1092
                # Creates or opens a file called mydb with a SQLite3 DB
1093
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1094
                conn = sqlite3.connect(dbPath)
1095
                # Get a cursor object
1096
                cursor = conn.cursor()
1097

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

    
1117
    '''
1118
        @brief  get area of given name
1119
        @author humkyung
1120
        @date   2018.04.07
1121
    '''
1122
    def getArea(self, name):
1123
        areas = self.getAreaList()
1124
        matches = [area for area in areas if area.name==name]
1125
        if 1 == len(matches) and matches[0].height is not 0 and matches[0].width is not 0:
1126
            return matches[0]
1127

    
1128
        return None
1129

    
1130
    '''
1131
        @brief  get configurations
1132
        @author humkyung
1133
        @date   2018.04.16
1134
        @history kyouho 2018.07.09 change query method
1135
    '''
1136
    '''
1137
    def getConfigs(self, section, key=None):
1138
        res = []
1139

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

1147
            if key is not None:
1148
                sql = "select * from configuration where section=? and key=?"
1149
                param = (section, key)
1150
            else:
1151
                sql = "select * from configuration where section=?"
1152
                param = (section,)
1153

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

1167
        return res
1168
        '''
1169
    def getConfigs(self, section, key=None):        
1170
        res = []
1171

    
1172
        if self.configTable is None:
1173
            self.configTable = []
1174
            try:
1175
                # Creates or opens a file called mydb with a SQLite3 DB
1176
                dbPath = self.getAppDbPath()
1177
                conn = sqlite3.connect(dbPath)
1178
                # Get a cursor object
1179
                cursor = conn.cursor()
1180

    
1181
                sql = "select Section, Key, Value from configuration"
1182
            
1183
                cursor.execute(sql)
1184
                rows = cursor.fetchall()
1185
                for row in rows:
1186
                    self.configTable.append(Config(row[0], row[1], row[2]))
1187
                # Catch the exception
1188
            except Exception as ex:
1189
                # Roll back any change if something goes wrong
1190
                conn.rollback()
1191
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1192
            finally:
1193
                # Close the db connection
1194
                conn.close()
1195

    
1196
        if key is not None:
1197
            for con in self.configTable:
1198
                if con.section == section and con.key == key:
1199
                    res.append(con)
1200
        else:
1201
            for con in self.configTable:
1202
                if con.section == section:
1203
                    res.append(con)
1204

    
1205
        return res
1206

    
1207
    def getAppConfigs(self, section, key=None):
1208
        """
1209
            @brief  get application configurations
1210
            @author humkyung
1211
            @date   2018.11.01
1212
        """
1213

    
1214
        res = []
1215

    
1216
        try:
1217
            # Creates or opens a file called mydb with a SQLite3 DB
1218
            dbPath = self.getAppDbPath()
1219
            conn = sqlite3.connect(dbPath)
1220
            # Get a cursor object
1221
            cursor = conn.cursor()
1222

    
1223
            if key is not None:
1224
                sql = "select * from configuration where section=? and key=?"
1225
                param = (section, key)
1226
            else:
1227
                sql = "select * from configuration where section=?"
1228
                param = (section,)
1229

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

    
1243
        return res
1244

    
1245
    '''
1246
        @brief      save configurations
1247
        @author     humkyung
1248
        @date       2018.04.16
1249
        @history    humkyung 2018.07.03 replace ' with " if value has '
1250
                    kyouho 2018.07.09 change query method
1251
    '''
1252
    def saveConfigs(self, configs):
1253
        import uuid
1254
        
1255
        try:
1256
            # Creates or opens a file called mydb with a SQLite3 DB
1257
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1258
            conn = sqlite3.connect(dbPath, isolation_level=None)
1259
            # Get a cursor object
1260
            cursor = conn.cursor()
1261

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

    
1268
                    sql = "insert or replace into configuration values(?,?,?,?)"
1269
                    param = (str(uuid.uuid4()), config.section, config.key, value)                    
1270

    
1271
                    cursor.execute(sql, param)
1272
                elif hasattr(config, 'toSql'):
1273
                    sql = config.toSql()
1274
                    if type(sql) is list:
1275
                        for item in sql:
1276
                            if item is not None and 2 == len(item):
1277
                                cursor.execute(item[0], item[1])
1278
                    else:
1279
                        if sql is not None and 2 == len(sql):
1280
                            cursor.execute(sql[0], sql[1])
1281

    
1282
            conn.commit()
1283
        # Catch the exception
1284
        except Exception as ex:
1285
            # Roll back any change if something goes wrong
1286
            conn.rollback()
1287
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1288
        finally:
1289
            # Close the db connection
1290
            conn.close()
1291

    
1292
    def saveAppConfigs(self, configs):
1293
        """
1294
        @brief      save application configurations
1295
        @author     humkyung
1296
        @date       2018.10.01
1297
        """
1298

    
1299
        try:
1300
            # Creates or opens a file called mydb with a SQLite3 DB
1301
            dbPath = self.getAppDbPath()
1302
            conn = sqlite3.connect(dbPath)
1303
            # Get a cursor object
1304
            cursor = conn.cursor()
1305

    
1306
            for config in configs:
1307
                value = config.value
1308
                if type(value) is str and "'" in value:
1309
                    value = value.replace("'", "''")
1310

    
1311
                sql = "insert or replace into configuration values(?,?,?)"
1312
                param = (config.section, config.key, value)
1313

    
1314
                cursor.execute(sql, param)
1315
            conn.commit()
1316
        # Catch the exception
1317
        except Exception as ex:
1318
            # Roll back any change if something goes wrong
1319
            conn.rollback()
1320
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1321
        finally:
1322
            # Close the db connection
1323
            conn.close()
1324

    
1325

    
1326
    def initializeDataByDrawingUID(self, uid):
1327
        try:
1328
            # Creates or opens a file called mydb with a SQLite3 DB
1329
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1330
            conn = sqlite3.connect(dbPath)
1331
            # Get a cursor object
1332
            cursor = conn.cursor()
1333

    
1334
            # 0. Delete Points
1335
            sql = "delete from Points where Components_UID in (select UID from Components where Drawings_UID = '{}')".format(uid)
1336
            cursor.execute(sql)
1337

    
1338
            # 1. Delete HMB
1339
            sql = "delete from HMB where Components_UID in (select UID from Components where Drawings_UID = '{}')".format(uid)
1340
            cursor.execute(sql)
1341

    
1342
            # 2. Delete Components
1343
            sql = "delete from Components where Drawings_UID='{}'".format(uid)
1344
            cursor.execute(sql)            
1345
            
1346
            conn.commit()
1347
        # Catch the exception
1348
        except Exception as ex:
1349
            # Roll back any change if something goes wrong
1350
            conn.rollback()
1351
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1352
        finally:
1353
            # Close the db connection
1354
            conn.close()
1355

    
1356
    def deleteDrawingByName(self, drawingName):
1357
        """ delete given drawing """
1358
        conn = sqlite3.connect(self.getAppDbPath())
1359
        with conn:
1360
            try:
1361
                # Get a cursor object
1362
                cursor = conn.cursor()
1363

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

    
1375
    '''
1376
        @brief  delete configurations
1377
        @author humkyung
1378
        @date   2018.06.29
1379
    '''
1380
    def deleteConfigs(self, section, key=None):
1381
        try:
1382
            # Creates or opens a file called mydb with a SQLite3 DB
1383
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1384
            conn = sqlite3.connect(dbPath)
1385
            # Get a cursor object
1386
            cursor = conn.cursor()
1387

    
1388
            if key is not None:
1389
                sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
1390
            else:
1391
                sql = "delete from configuration where section='{}'".format(section)
1392
            cursor.execute(sql)
1393

    
1394
            conn.commit()
1395
        # Catch the exception
1396
        except Exception as ex:
1397
            # Roll back any change if something goes wrong
1398
            conn.rollback()
1399
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1400
        finally:
1401
            # Close the db connection
1402
            conn.close()
1403

    
1404
    def deleteAppConfigs(self, section, key=None):
1405
        """
1406
        @brief  delete application configurations
1407
        @author humkyung
1408
        @date   2018.11.01
1409
        """
1410

    
1411
        try:
1412
            # Creates or opens a file called mydb with a SQLite3 DB
1413
            dbPath = self.getAppDbPath()
1414
            conn = sqlite3.connect(dbPath)
1415
            # Get a cursor object
1416
            cursor = conn.cursor()
1417

    
1418
            if key is not None:
1419
                sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
1420
            else:
1421
                sql = "delete from configuration where section='{}'".format(section)
1422
            cursor.execute(sql)
1423

    
1424
            conn.commit()
1425
        # Catch the exception
1426
        except Exception as ex:
1427
            # Roll back any change if something goes wrong
1428
            conn.rollback()
1429
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1430
        finally:
1431
            # Close the db connection
1432
            conn.close()
1433

    
1434
    '''
1435
        @brief      set area list
1436
        @history    humkyung 2018.05.18 round area coordinate and dimension before saving
1437
        @history    euisung  2018.11.20 add self._area reset process
1438
    '''
1439
    def setAreaList(self, areas):
1440
        for area in areas:
1441
            matches = [x for x in self._areas if x.name==area.name]
1442
            if 1 == len(matches):
1443
                matches[0].x = area.x
1444
                matches[0].y = area.y
1445
                matches[0].width = area.width
1446
                matches[0].height = area.height
1447
            elif 0 == len(matches):
1448
                self._areas.append(area)
1449

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

    
1457
            for area in self._areas:
1458
                sql = "insert or replace into configuration values('Area','{}','({},{}),({},{})')".format(area.name, round(area.x), round(area.y), round(area.width), round(area.height))
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
            self._areas = []
1470
            conn.close()
1471
            
1472
    '''
1473
        @brief  get symbol name list
1474
    '''
1475
    def getSymbolNameList(self):
1476
        symbolNametList = []
1477

    
1478
        try:            
1479
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1480

    
1481
            conn = sqlite3.connect(dbPath)
1482
            cursor = conn.cursor()
1483
            sql = 'SELECT * FROM SymbolName'
1484
            try:
1485
                cursor.execute(sql)
1486
                rows = cursor.fetchall()
1487
                for row in rows:
1488
                    symbolNametList.append(row[4]) # Name String
1489
            except Exception as ex:
1490
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1491
        finally:
1492
            conn.close()
1493

    
1494
        return symbolNametList
1495

    
1496
    '''
1497
        @brief      get symbol name list by symbol Type
1498
        @author     Jeongwoo
1499
        @date       18.04.06
1500
        @history    .
1501
    '''
1502
    def getSymbolNameListByType(self, type):
1503
        symbolNametList = []
1504

    
1505
        try:
1506
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1507

    
1508
            conn = sqlite3.connect(dbPath)
1509
            cursor = conn.cursor()
1510
            sql = ''
1511
            if type is not None:
1512
                sql = 'SELECT * FROM SymbolName WHERE type = "' + type + '"'
1513
                try:
1514
                    cursor.execute(sql)
1515
                    rows = cursor.fetchall()
1516
                    for row in rows:
1517
                        symbolNametList.append(row[4]) # Name String
1518
                except Exception as ex:
1519
                    print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1520
        finally:
1521
            conn.close()
1522

    
1523
        return symbolNametList
1524

    
1525
    '''
1526
        @brief  delete added symbol data
1527
    '''
1528
    def deleteSymbol(self, fileName):
1529
        ret = False
1530
        try:
1531
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1532

    
1533
            conn = sqlite3.connect(dbPath)
1534
            cursor = conn.cursor()
1535
            sql = "DELETE FROM Symbol WHERE name = ?"
1536
            try:
1537
                cursor.execute(sql, (fileName,))
1538
                conn.commit()
1539
                ret = True
1540
            except Exception as ex:
1541
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1542
                ret = False
1543
        finally:
1544
            conn.close()
1545
            return (ret, fileName)
1546
        
1547
    '''
1548
        @brief  get symbol name
1549
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1550
    '''
1551
    def getSymbolByQuery(self, fieldName, param):
1552
        ret = None
1553

    
1554
        conn = sqlite3.connect(self.activeDrawing.path)
1555
        with conn:
1556
            cursor = conn.cursor()
1557

    
1558
            sql = """select s.UID
1559
                            , s.Name
1560
                            , t.Category
1561
                            , t.Type
1562
                            , s.OriginalPoint
1563
                            , s.ConnectionPoint
1564
                        from Symbols s
1565
                        inner join SymbolType t
1566
                            on s.SymbolType_UID = t.UID 
1567
                        where """ + "s." + fieldName + '=?'
1568

    
1569
            try:
1570
                cursor.execute(sql, (param,))
1571
                rows = cursor.fetchall()
1572
                if rows is not None and len(rows) > 0:
1573
                    symbolTuple = rows[0]
1574
                    ret = symbol.SymbolBase(symbolTuple[0], symbolTuple[1], symbolTuple[2], symbolTuple[3], symbolTuple[4], symbolTuple[5]) 
1575
            except Exception as ex:
1576
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1577

    
1578
        return ret
1579

    
1580
    def getSymbolListByUID(self, uid):
1581
        """ get symbol list by given uid """
1582
        ret = []
1583

    
1584
        conn = sqlite3.connect(self.getTemplateDbPath())
1585
        with conn:
1586
            cursor = conn.cursor()
1587
            
1588
            sql = """select s.UID
1589
                            , s.Name
1590
                            , t.Category
1591
                            , t.Type
1592
                            , s.OriginalPoint
1593
                            , s.ConnectionPoint
1594
                        from Symbols s
1595
                        inner join SymbolType t
1596
                            on s.SymbolType_UID = t.uid 
1597
                        where s.SymbolType_UID = ?"""
1598
            
1599
            try:
1600
                cursor.execute(sql, (uid,))
1601
                rows = cursor.fetchall()
1602
                if rows is not None and len(rows) > 0:
1603
                    for row in rows:
1604
                        sym = symbol.SymbolBase(row[0], row[1], row[2], row[3], row[4], row[5])
1605
                                                
1606
                        ret.append(sym)
1607
            except Exception as ex:
1608
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1609

    
1610
        return ret
1611

    
1612

    
1613
    '''
1614
        @brief  get symbol name list
1615
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1616
    '''
1617
    def getSymbolListByType(self, fieldName=None, param=None):
1618
        ret = []
1619

    
1620
        try:
1621
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1622
            conn = sqlite3.connect(dbPath)
1623
            cursor = conn.cursor()
1624
            if fieldName is not None and param is not None:
1625

    
1626
                sql = """select s.UID
1627
                              , s.Name
1628
                              , t.Category
1629
                              , t.Type
1630
                              , s.OriginalPoint
1631
                              , s.ConnectionPoint
1632
                           from Symbols s 
1633
                          inner join SymbolType t 
1634
                             on s.SymbolType_UID = t.UID
1635
                          where s.SymbolType_UID = (select UID from SymbolType where Type=?)"""
1636
            else:
1637

    
1638
                sql = """select s.UID
1639
                              , s.Name
1640
                              , t.Category
1641
                              , t.Type
1642
                              , s.OriginalPoint
1643
                              , s.ConnectionPoint
1644
                           from Symbols s
1645
                          inner join SymbolType t
1646
                             on s.SymbolType_UID = t.UID"""
1647
            try:
1648
                cursor.execute(sql, (param,)) if param is not None else cursor.execute(sql)
1649
                rows = cursor.fetchall()
1650
                if rows is not None and len(rows) > 0:
1651
                    for row in rows:
1652
                        sym = symbol.SymbolBase(row[0], row[1], row[2], row[3], row[4], row[5])
1653
                                                
1654
                        ret.append(sym)
1655
            except Exception as ex:
1656
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1657
        finally:
1658
            conn.close()
1659

    
1660
        return ret
1661

    
1662
    '''
1663
        @brief      insert NominalDiameter table
1664
        @author     kyouho
1665
        @date       2018.07.16
1666
    '''
1667
    def insertNomialPipeSize(self, pipeSizes):
1668
        try:
1669
            # Creates or opens a file called mydb with a SQLite3 DB
1670
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1671
            conn = sqlite3.connect(dbPath)
1672
            # Get a cursor object
1673
            cursor = conn.cursor()
1674
            for pipeSize in pipeSizes:
1675
                sql = pipeSize.toSql()
1676
                if type(sql) is list and len(sql) == 1:
1677
                    cursor.execute(sql[0][0], sql[0][1])
1678

    
1679
            conn.commit()
1680
            # Catch the exception
1681
        except Exception as ex:
1682
            # Roll back any change if something goes wrong
1683
            conn.rollback()
1684
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1685
        finally:
1686
            # Close the db connection
1687
            conn.close()
1688

    
1689
    '''
1690
        @brief      delete NominalDiameter table
1691
        @author     kyouho
1692
        @date       2018.07.16
1693
    '''
1694
    def deleteNomialPipeSize(self):
1695
        try:
1696
            dbPath = os.path.join(self.getCurrentProject().getPath(), 'db', AppDocData.DATABASE)
1697
            conn = sqlite3.connect(dbPath)
1698
            cursor = conn.cursor()
1699
            sql = "DELETE FROM NominalDiameter"
1700
            try:
1701
                cursor.execute(sql)
1702
                conn.commit()
1703
            except Exception as ex:
1704
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1705
        finally:
1706
            conn.close()
1707

    
1708
    '''
1709
        @brief      convert inch to metric
1710
        @author     kyouho
1711
        @date       2018.07.09
1712
    '''
1713
    def convertInchToMetric(self, inch):
1714
        result = ''
1715
        try:
1716
            # Creates or opens a file called mydb with a SQLite3 DB
1717
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1718
            conn = sqlite3.connect(dbPath)
1719
            # Get a cursor object
1720
            cursor = conn.cursor()
1721
            
1722
            sql = "select MetricStr from NominalDiameter WHERE InchStr = ?"
1723
            param = (inch,)
1724
            cursor.execute(sql, param)
1725
            rows = cursor.fetchall()
1726

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

    
1738
        return result
1739

    
1740
    '''
1741
        @brief      get Color MaxUID
1742
        @author     kyouho
1743
        @date       2018.07.03
1744
    '''
1745
    def getMaxColorUID(self):
1746
        result = 0
1747

    
1748
        try:
1749
            # Creates or opens a file called mydb with a SQLite3 DB
1750
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1751
            conn = sqlite3.connect(dbPath)
1752
            # Get a cursor object
1753
            cursor = conn.cursor()
1754

    
1755
            sql = "select MAX(UID) from Colors"
1756
            cursor.execute(sql)
1757
            rows = cursor.fetchall()
1758

    
1759
            result = rows[0][0]
1760
            # Catch the exception
1761
        except Exception as ex:
1762
            # Roll back any change if something goes wrong
1763
            conn.rollback()
1764
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1765
        finally:
1766
            # Close the db connection
1767
            conn.close()
1768

    
1769
        return result
1770

    
1771
    '''
1772
        @brief      insert Color property
1773
        @author     kyouho
1774
        @date       2018.07.09
1775
    '''
1776
    def setPropertyColor(self, _color):
1777
        try:
1778
            # Creates or opens a file called mydb with a SQLite3 DB
1779
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1780
            conn = sqlite3.connect(dbPath)
1781
            # Get a cursor object
1782
            cursor = conn.cursor()
1783
            sql = "INSERT INTO Colors(UID, RED, GREEN, BLUE, PROPERTY, VALUE) VALUES(?,?,?,?,?,?)"
1784
            param = (_color.index, _color.red, _color.green, _color.blue, _color._property, _color.value)
1785
            cursor.execute(sql, param)
1786
            conn.commit()
1787
            # Catch the exception
1788
        except Exception as ex:
1789
            # Roll back any change if something goes wrong
1790
            conn.rollback()
1791
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1792
        finally:
1793
            # Close the db connection
1794
            conn.close()
1795

    
1796
    '''
1797
        @brief      delete Color property
1798
        @author     kyouho
1799
        @date       2018.07.09
1800
    '''
1801
    def deletePropertyColor(self, property):
1802
        try:
1803
            # Creates or opens a file called mydb with a SQLite3 DB
1804
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1805
            conn = sqlite3.connect(dbPath)
1806
            # Get a cursor object
1807
            cursor = conn.cursor()
1808

    
1809
            sql = "DELETE FROM Colors WHERE PROPERTY = '{}'".format(property)
1810
            cursor.execute(sql)
1811
            conn.commit()
1812
            # Catch the exception
1813
        except Exception as ex:
1814
            # Roll back any change if something goes wrong
1815
            conn.rollback()
1816
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1817
        finally:
1818
            # Close the db connection
1819
            conn.close()
1820

    
1821
    '''
1822
        @brief      get Fluid Code
1823
        @author     kyouho
1824
        @date       2018.07.03
1825
        @history    kyouho 2018.07.04 kyouho 2018.07.04 forCheckLineNumber get only code
1826
    '''
1827
    def getFluidCodeData(self, forCheckLineNumber = False):
1828
        from FluidCodeData import FluidCodeData
1829
        result = []
1830

    
1831
        try:
1832
            # Creates or opens a file called mydb with a SQLite3 DB
1833
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1834
            conn = sqlite3.connect(dbPath)
1835
            # Get a cursor object
1836
            cursor = conn.cursor()
1837

    
1838
            sql = 'select uid, code, description from FluidCode order by length(code) DESC'
1839
            cursor.execute(sql)
1840
            rows = cursor.fetchall()
1841
            for row in rows:
1842
                data = FluidCodeData(row[0], row[1], row[2])
1843
                if forCheckLineNumber:
1844
                    result.append(data.code)
1845
                else:
1846
                    result.append(data)
1847
            # Catch the exception
1848
        except Exception as ex:
1849
            # Roll back any change if something goes wrong
1850
            conn.rollback()
1851
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1852
        finally:
1853
            # Close the db connection
1854
            conn.close()
1855

    
1856
        return result
1857

    
1858
    '''
1859
        @brief      get Symbol Attribute
1860
        @author     kyouho
1861
        @date       2018.07.18
1862
    '''
1863
    def checkAttribute(self, attr):
1864
        try:
1865
            # Creates or opens a file called mydb with a SQLite3 DB
1866
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1867
            conn = sqlite3.connect(dbPath)
1868
            # Get a cursor object
1869
            cursor = conn.cursor()
1870

    
1871
            sql = 'select UID from SymbolAttribute where UID = ?'
1872
            param = (attr,)
1873
            cursor.execute(sql, param)
1874
            rows = cursor.fetchall()
1875
            if len(rows):
1876
                return True
1877
            else:
1878
                return False
1879
            # Catch the exception
1880
        except Exception as ex:
1881
            # Roll back any change if something goes wrong
1882
            conn.rollback()
1883
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1884
        finally:
1885
            # Close the db connection
1886
            conn.close()
1887

    
1888
        return False
1889

    
1890
    '''
1891
        @brief      get Symbol Attribute
1892
        @author     kyouho
1893
        @date       2018.07.18
1894
        @history    humkyung 2018.10.13 load expression
1895
    '''
1896
    def getSymbolAttribute(self, _type):
1897
        import uuid
1898
        from SymbolAttr import SymbolAttr
1899

    
1900
        result = []
1901

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

    
1909
            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]'
1910
            param = (_type,)
1911
            cursor.execute(sql, param)
1912
            rows = cursor.fetchall()
1913
            for row in rows:
1914
                attr = SymbolAttr()
1915
                attr.UID = uuid.UUID(row[0], version=4)
1916
                attr.Attribute = row[1]
1917
                attr.DisplayAttribute = row[2]
1918
                attr.AttributeType = row[3]
1919
                attr.AttrAt = row[4]
1920
                attr.Expression = row[5]
1921
                attr.Target = row[7]
1922
                attr.IsProp = bool(row[8])
1923
                result.append(attr)
1924
            # Catch the exception
1925
        except Exception as ex:
1926
            from App import App 
1927

    
1928
            # Roll back any change if something goes wrong
1929
            conn.rollback()
1930

    
1931
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1932
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1933
        finally:
1934
            # Close the db connection
1935
            conn.close()
1936

    
1937
        return result
1938

    
1939
    '''
1940
        @brief      get Symbol Attribute by UID
1941
        @author     kyouho
1942
        @date       2018.08.17
1943
        @history    humkyung 2018.10.13 load expression
1944
    '''
1945
    def getSymbolAttributeByUID(self, UID):
1946
        from SymbolAttr import SymbolAttr
1947

    
1948
        res = None
1949

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

    
1957
            sql = 'select Attribute, DisplayAttribute, AttributeType, AttrAt, Expression, Target, Property from SymbolAttribute where uid = "{}"'.format(UID)
1958
            cursor.execute(sql)
1959
            rows = cursor.fetchall()
1960
            if len(rows):
1961
                res = SymbolAttr()
1962
                res.UID = UID
1963
                res.Attribute = rows[0][0]
1964
                res.DisplayAttribute = rows[0][1]
1965
                res.AttributeType = rows[0][2]
1966
                res.AttrAt = rows[0][3]
1967
                res.Expression = rows[0][4]
1968
                res.Target = rows[0][5]
1969
                res.IsProp = bool(row[0][6])
1970
            # Catch the exception
1971
        except Exception as ex:
1972
            from App import App
1973

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

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

    
1983
        return res
1984

    
1985
    '''
1986
        @brief      save symbol attributes
1987
        @author     humkyung
1988
        @date       2018.08.14
1989
        @history    humkyung 2018.10.13 save expression
1990
    '''
1991
    def saveSymbolAttributes(self, type, attrs):
1992
        try:
1993
            # Creates or opens a file called mydb with a SQLite3 DB
1994
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1995
            conn = sqlite3.connect(dbPath)
1996
            # Get a cursor object
1997
            cursor = conn.cursor()
1998

    
1999
            sql = 'delete from SymbolAttribute where SymbolType_UID = ?'
2000
            param = (type,)
2001
            cursor.execute(sql, param)
2002

    
2003
            for attr in attrs:
2004
                sql = 'insert into SymbolAttribute(UID, SymbolType_UID, Attribute, DisplayAttribute, AttributeType, AttrAt, Expression, Target, [index]) values(?, ?, ?, ?, ?, ?, ?, ?, ?)'
2005
                attr.insert(1, type)
2006
                param = tuple(attr)
2007
                cursor.execute(sql, param)
2008

    
2009
            conn.commit()
2010
            # Catch the exception
2011
        except Exception as ex:
2012
            # Roll back any change if something goes wrong
2013
            conn.rollback()
2014
            
2015
            from App import App 
2016
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2017
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2018
        finally:
2019
            # Close the db connection
2020
            conn.close()
2021

    
2022
    '''
2023
        @brief      save symbol attributes
2024
        @author     humkyung
2025
        @date       2018.08.14
2026
    '''
2027
    def saveLineAttributes(self, attrs):
2028
        try:
2029
            # Creates or opens a file called mydb with a SQLite3 DB
2030
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2031
            conn = sqlite3.connect(dbPath)
2032
            # Get a cursor object
2033
            cursor = conn.cursor()
2034

    
2035
            sql = 'delete from LineProperties'
2036
            cursor.execute(sql)
2037

    
2038
            for attr in attrs:
2039
                sql = 'insert into LineProperties(UID, Name, DisplayName, Type, LimitNumber, [index]) values(?, ?, ?, ?, ?, ?)'
2040
                param = tuple(attr)
2041
                cursor.execute(sql, param)
2042

    
2043
            conn.commit()
2044

    
2045
            self._lineNoProperties = None
2046
            # Catch the exception
2047
        except Exception as ex:
2048
            # Roll back any change if something goes wrong
2049
            conn.rollback()
2050
            
2051
            from App import App 
2052
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2053
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2054
        finally:
2055
            # Close the db connection
2056
            conn.close()
2057

    
2058
    '''
2059
        @brief      get symbol type id
2060
        @author     kyouho
2061
        @date       2018.08.17
2062
    '''
2063
    def getSymbolTypeId(self, symbolType):
2064
        result = []
2065

    
2066
        try:
2067
            # Creates or opens a file called mydb with a SQLite3 DB
2068
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2069
            conn = sqlite3.connect(dbPath)
2070
            # Get a cursor object
2071
            cursor = conn.cursor()
2072

    
2073
            sql = 'select UID from SymbolType where Type = ?'
2074
            param = (symbolType,)
2075
            cursor.execute(sql, param)
2076
            rows = cursor.fetchall()
2077
            
2078
            if len(rows):
2079
                result = rows[0][0]
2080
            else:
2081
                result = -1
2082
            # Catch the exception
2083
        except Exception as ex:
2084
            # Roll back any change if something goes wrong
2085
            conn.rollback()
2086
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2087
        finally:
2088
            # Close the db connection
2089
            conn.close()
2090

    
2091
        return result
2092

    
2093
    '''
2094
        @brief      get Code Table Data
2095
        @author     kyouho
2096
        @date       2018.07.10
2097
    '''
2098
    def getCodeTable(self, property, forCheckLineNumber = False):
2099
        result = []
2100
        try:
2101
            # Creates or opens a file called mydb with a SQLite3 DB
2102
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2103
            conn = sqlite3.connect(dbPath)
2104
            # Get a cursor object
2105
            cursor = conn.cursor()
2106

    
2107
            if property.upper().replace(' ','') == "NOMINALDIAMETER" and forCheckLineNumber:
2108
                sql = 'select InchStr, MetricStr from [{}] order by Metric ASC'.format(property)
2109
                cursor.execute(sql)
2110
                rows = cursor.fetchall()
2111
                for index in range(2):
2112
                    for row in rows:
2113
                        if row[index] != '' and result.count(row[index].replace("'", '"')) == 0:
2114
                            result.append(row[index].replace("'", '"'))
2115
            else:
2116
                sql = 'select uid, code, description, Allowables from [{}] order by length(code) DESC'.format(property)
2117
                cursor.execute(sql)
2118
                rows = cursor.fetchall()
2119
                for row in rows:
2120
                    if forCheckLineNumber:
2121
                        data = row[1]
2122
                    else:
2123
                        data = (row[0], row[1], row[2], row[3])
2124
                    result.append(data)
2125
            # Catch the exception
2126
        except Exception as ex:
2127
            # Roll back any change if something goes wrong
2128
            conn.rollback()
2129
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2130
        finally:
2131
            # Close the db connection
2132
            conn.close()
2133

    
2134
        return result
2135

    
2136

    
2137
    def getResistanceCoefficientByMethod(self, method):
2138
        res = []
2139
        try:
2140
            # Creates or opens a file called mydb with a SQLite3 DB
2141
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2142
            db = sqlite3.connect(dbPath)
2143
            db.row_factory = sqlite3.Row
2144
            # Get a cursor object
2145
            cursor = db.cursor()
2146

    
2147
            sql = """select UID
2148
                          , Method
2149
                          , Category
2150
                          , Type
2151
                          , Name
2152
                          , K 
2153
                       from ResistanceCoefficient 
2154
                      where Method = ?
2155
                      order by rowid""" 
2156

    
2157
            param = (method,)
2158
            cursor.execute(sql, param)
2159
            rows = cursor.fetchall()
2160
            for row in rows:                
2161
                res.append((row[0], row[1], row[2], row[3], row[4], row[5]))
2162
        # Catch the exception
2163
        except Exception as ex:
2164
            # Roll back any change if something goes wrong
2165
            db.rollback()
2166
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2167
        finally:
2168
            # Close the db connection
2169
            db.close()
2170

    
2171
        return res
2172

    
2173

    
2174
    '''
2175
        @brief      Set Common Code Data
2176
        @author     kyouho
2177
        @date       2018.07.12
2178
    '''
2179
    def saveCommonCodeData(self, tableName, datas):
2180
        import uuid
2181

    
2182
        try:
2183
            # Creates or opens a file called mydb with a SQLite3 DB
2184
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2185
            conn = sqlite3.connect(dbPath)
2186
            # Get a cursor object
2187
            cursor = conn.cursor()
2188

    
2189
            for data in datas:
2190
                uid,code,description,allowables = data[0],data[1],data[2],data[3]
2191
                if not uid:
2192
                    sql = "insert or replace into {}(UID, CODE, DESCRIPTION, ALLOWABLES) values(?, ?, ?, ?)".format(tableName)
2193
                    param = (str(uuid.uuid4()), data[1], data[2], data[3])
2194
                elif uid == '-1':
2195
                    sql = 'delete from {} where uid=?'.format(tableName) 
2196
                    param = (data[-1],)
2197
                else:
2198
                    sql = "update {} SET CODE=?, DESCRIPTION=?, ALLOWABLES=? WHERE UID = ?".format(tableName)
2199
                    param = (data[1], data[2], data[3], data[0])
2200
                cursor.execute(sql, param)
2201

    
2202
            conn.commit()
2203
        
2204
        # Catch the exception
2205
        except Exception as ex:
2206
            # Roll back any change if something goes wrong
2207
            conn.rollback()
2208
            print('error occured({}:{}) in {}:{}'.format(tableName, ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2209
        finally:
2210
            # Close the db connection
2211
            conn.close()
2212

    
2213
    '''
2214
        @brief      Set Common Code Data
2215
        @author     kyouho
2216
        @date       2018.07.12
2217
    '''
2218
    def deleteCommonCodeData(self, datas):
2219
        try:
2220
            # Creates or opens a file called mydb with a SQLite3 DB
2221
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2222
            conn = sqlite3.connect(dbPath)
2223
            # Get a cursor object
2224
            cursor = conn.cursor()
2225

    
2226
            for data in datas:
2227
                uid = data[0]
2228
                tableName = data[1]
2229

    
2230
                if uid:
2231
                    sql = "delete from {} where UID = ?".format(tableName)
2232
                    param = (uid,)
2233
                    cursor.execute(sql, param)
2234

    
2235
                cursor.execute(sql, param)
2236

    
2237
            conn.commit()
2238
        
2239
        # Catch the exception
2240
        except Exception as ex:
2241
            # Roll back any change if something goes wrong
2242
            conn.rollback()
2243
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2244
        finally:
2245
            # Close the db connection
2246
            conn.close()
2247

    
2248
    '''
2249
        @brief      delete data list
2250
        @author     kyouho
2251
        @date       2018.08.16
2252
    '''
2253
    def deleteDataList(self, tableName, UID):
2254
        try:
2255
            # Creates or opens a file called mydb with a SQLite3 DB
2256
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2257
            conn = sqlite3.connect(dbPath)
2258
            # Get a cursor object
2259
            cursor = conn.cursor()
2260

    
2261
            sql = 'delete from {} where UID = {}'.format(tableName, UID)
2262
            
2263
            cursor.execute(sql)
2264

    
2265
            conn.commit()
2266

    
2267
        # Catch the exception
2268
        except Exception as ex:
2269
            # Roll back any change if something goes wrong
2270
            conn.rollback()
2271
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2272
        finally:
2273
            # Close the db connection
2274
            conn.close()
2275

    
2276
    def getDocumentNameList(self):
2277
        '''
2278
            @brief      get documentName list
2279
            @author     euisung
2280
            @date       2018.12.11
2281
        '''
2282
        result = []
2283

    
2284
        try:
2285
            # Creates or opens a file called mydb with a SQLite3 DB
2286
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2287
            conn = sqlite3.connect(dbPath)
2288
            # Get a cursor object
2289
            cursor = conn.cursor()
2290

    
2291
            sql = 'select DISTINCT(PNID_NO) from LINE_DATA_LIST'
2292
            cursor.execute(sql)
2293
            sql = 'select DISTINCT(PNID_NO) from EQUIPMENT_DATA_LIST'
2294
            cursor.execute(sql)
2295
            sql = 'select DISTINCT(PNID_NO) from INSTRUMENT_DATA_LIST'
2296
            cursor.execute(sql)
2297
            sql = 'select DISTINCT(PNID_NO) from NOTE_DATA_LIST'
2298
            cursor.execute(sql)
2299
            sql = 'select DISTINCT(PNID_NO) from VALVE_DATA_LIST'
2300
            cursor.execute(sql)
2301

    
2302
            rows = cursor.fetchall()
2303
            for row in rows:
2304
                result.append(row[0])
2305

    
2306
            result = list(set(result))
2307
            result.sort()
2308
        # Catch the exception
2309
        except Exception as ex:
2310
            # Roll back any change if something goes wrong
2311
            conn.rollback()
2312
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2313
        finally:
2314
            # Close the db connection
2315
            conn.close()
2316

    
2317
        return result
2318

    
2319

    
2320
    '''
2321
        @brief      get line documentName list
2322
        @author     kyouho
2323
        @date       2018.08.13
2324
    '''
2325
    def getLineDocumentNameList(self):
2326
        result = []
2327

    
2328
        try:
2329
            # Creates or opens a file called mydb with a SQLite3 DB
2330
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2331
            conn = sqlite3.connect(dbPath)
2332
            # Get a cursor object
2333
            cursor = conn.cursor()
2334

    
2335
            sql = 'select DISTINCT(PNID_NO) from LINE_DATA_LIST'
2336

    
2337
            cursor.execute(sql)
2338
            rows = cursor.fetchall()
2339
            for row in rows:
2340
                result.append(row[0])
2341
        # Catch the exception
2342
        except Exception as ex:
2343
            # Roll back any change if something goes wrong
2344
            conn.rollback()
2345
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2346
        finally:
2347
            # Close the db connection
2348
            conn.close()
2349

    
2350
        return result
2351

    
2352
    '''
2353
        @brief      get line documentName list
2354
        @author     kyouho
2355
        @date       2018.08.14
2356
    '''
2357
    def getEquipDocumentNameList(self):
2358
        result = []
2359

    
2360
        try:
2361
            # Creates or opens a file called mydb with a SQLite3 DB
2362
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2363
            conn = sqlite3.connect(dbPath)
2364
            # Get a cursor object
2365
            cursor = conn.cursor()
2366

    
2367
            sql = 'select DISTINCT(PNID_NO) from EQUIPMENT_DATA_LIST'
2368

    
2369
            cursor.execute(sql)
2370
            rows = cursor.fetchall()
2371
            for row in rows:
2372
                result.append(row[0])
2373
        # Catch the exception
2374
        except Exception as ex:
2375
            # Roll back any change if something goes wrong
2376
            conn.rollback()
2377
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2378
        finally:
2379
            # Close the db connection
2380
            conn.close()
2381

    
2382
        return result
2383

    
2384

    
2385
    '''
2386
        @brief      get line data list
2387
        @author     kyouho
2388
        @date       2018.08.13
2389
    '''
2390
    def getLineDataList(self, docName = None):
2391
        result = []
2392

    
2393
        try:
2394
            # Creates or opens a file called mydb with a SQLite3 DB
2395
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2396
            conn = sqlite3.connect(dbPath)
2397
            # Get a cursor object
2398
            cursor = conn.cursor()
2399

    
2400
            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'
2401
            if docName is not None:
2402
                sql += " where PNID_NO = '{}'".format(docName)
2403

    
2404
            cursor.execute(sql)
2405
            #columnName = list(map(lambda x: x[0].upper(), cursor.description))
2406
            rows = cursor.fetchall()
2407
            for row in rows:
2408
                data = []
2409
                for index in range(len(cursor.description)):
2410
                    data.append(row[index])
2411
                result.append(data)
2412
        # Catch the exception
2413
        except Exception as ex:
2414
            # Roll back any change if something goes wrong
2415
            conn.rollback()
2416
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2417
        finally:
2418
            # Close the db connection
2419
            conn.close()
2420

    
2421
        return result
2422

    
2423
    '''
2424
        @brief      set line data list
2425
        @author     kyouho
2426
        @date       2018.08.13
2427
    '''
2428
    def setLineDataList(self, dataLists):
2429
        try:
2430
            # Creates or opens a file called mydb with a SQLite3 DB
2431
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2432
            conn = sqlite3.connect(dbPath)
2433
            # Get a cursor object
2434
            cursor = conn.cursor()
2435
            
2436
            for data in dataLists:
2437
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2438
                param = tuple(data)
2439
                cursor.execute(sql, param)
2440

    
2441
            conn.commit()
2442

    
2443
        # Catch the exception
2444
        except Exception as ex:
2445
            # Roll back any change if something goes wrong
2446
            conn.rollback()
2447
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2448
        finally:
2449
            # Close the db connection
2450
            conn.close()
2451

    
2452
    '''
2453
        @brief      delete line data list
2454
        @author     kyouho
2455
        @date       2018.08.13
2456
    '''
2457
    def deleteLineDataList(self, removeUID):
2458
        try:
2459
            # Creates or opens a file called mydb with a SQLite3 DB
2460
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2461
            conn = sqlite3.connect(dbPath)
2462
            # Get a cursor object
2463
            cursor = conn.cursor()
2464
            
2465
            for uid in removeUID:
2466
                sql = "delete from LINE_DATA_LIST where uid = '{}'".format(uid)
2467
                cursor.execute(sql)
2468

    
2469
            conn.commit()
2470

    
2471
        # Catch the exception
2472
        except Exception as ex:
2473
            # Roll back any change if something goes wrong
2474
            conn.rollback()
2475
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2476
        finally:
2477
            # Close the db connection
2478
            conn.close()
2479

    
2480
    '''
2481
        @brief      delete line data list
2482
        @author     kyouho
2483
        @date       2018.08.13
2484
    '''
2485
    def deleteLineDataList_LineNo(self, removeUID):
2486
        try:
2487
            # Creates or opens a file called mydb with a SQLite3 DB
2488
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2489
            conn = sqlite3.connect(dbPath)
2490
            # Get a cursor object
2491
            cursor = conn.cursor()
2492
            
2493
            for uid in removeUID:
2494
                sql = "delete from LINE_DATA_LIST where LINE_NO = ?"
2495
                param = (uid,)
2496
                cursor.execute(sql, param)
2497

    
2498
            conn.commit()
2499

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

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

    
2526
            conn.commit()
2527

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

    
2537
    '''
2538
        @brief      delete inst data list
2539
        @author     kyouho
2540
        @date       2018.08.14
2541
    '''
2542
    def deleteInstDataList(self, removeUID):
2543
        try:
2544
            # Creates or opens a file called mydb with a SQLite3 DB
2545
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2546
            conn = sqlite3.connect(dbPath)
2547
            # Get a cursor object
2548
            cursor = conn.cursor()
2549
            
2550
            for uid in removeUID:
2551
                sql = "delete from INSTRUMENT_DATA_LIST where uid = '{}'".format(uid)
2552
                cursor.execute(sql)
2553

    
2554
            conn.commit()
2555

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

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

    
2582
            conn.commit()
2583

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

    
2593
    '''
2594
        @brief      get equipment data list
2595
        @author     humkyung
2596
        @date       2018.05.03
2597
    '''
2598
    def getEquipmentDataList(self, docName = None):
2599
        result = []
2600
        try:
2601
            # Creates or opens a file called mydb with a SQLite3 DB
2602
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2603
            conn = sqlite3.connect(dbPath)
2604
            # Get a cursor object
2605
            cursor = conn.cursor()
2606

    
2607
            sql = 'select a.*,C.Attribute,B.Value  from EQUIPMENT_DATA_LIST a left join Attributes B on a.UID=B.Components_UID ' \
2608
                                                                             'left join SymbolAttribute C on B.SymbolAttribute_UID=C.UID'
2609
            if docName is not None:
2610
                sql += " where PNID_NO = '{}'".format(docName)
2611

    
2612
            cursor.execute(sql)
2613
            col_names = [desc[0] for desc in cursor.description]    # get coloumn name
2614
            rows = cursor.fetchall()
2615
            for row in rows:
2616
                matches = [res for res in result if res['UID']==row[0]]
2617
                if matches:
2618
                    matches[0][row[len(row)-2]] = row[len(row)-1]
2619
                else:
2620
                    data = dict(zip(col_names[:-2], row[:-2]))
2621
                    if row[len(row)-2] is not None:
2622
                        data[row[len(row)-2]] = row[len(row)-1]
2623
                    result.append(data)
2624
        # Catch the exception
2625
        except Exception as ex:
2626
            from App import App 
2627

    
2628
            # Roll back any change if something goes wrong
2629
            conn.rollback()
2630
            
2631
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2632
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2633
        finally:
2634
            # Close the db connection
2635
            conn.close()
2636

    
2637
        return result
2638

    
2639
    def get_valve_data_list(self, docName = None):
2640
        """
2641
        @brief      get valve data list
2642
        @author     humkyung
2643
        @date       2018.10.11
2644
        """
2645

    
2646
        result = []
2647
        try:
2648
            # Creates or opens a file called mydb with a SQLite3 DB
2649
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2650
            conn = sqlite3.connect(dbPath)
2651
            # Get a cursor object
2652
            cursor = conn.cursor()
2653

    
2654
            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 ' \
2655
                  'left join SymbolAttribute c on b.SymbolAttribute_UID=c.UID'
2656
            if docName is not None:
2657
                sql += " where PNID_NO = '{}'".format(docName)
2658

    
2659
            cursor.execute(sql)
2660
            rows = cursor.fetchall()
2661
            for row in rows:
2662
                matches = [res for res in result if res['UID'] == row[0]]
2663
                if matches:
2664
                    matches[0][row[5]] = row[6]
2665
                else:
2666
                    data = {'UID':row[0], 'ITEM_NO':row[1], 'PNID_NO':row[2], 'MainSize':row[3], 'SubSize':row[4]}
2667
                    data[row[5]] = row[6]
2668
                    result.append(data)
2669

    
2670
        # Catch the exception
2671
        except Exception as ex:
2672
            from App import App 
2673

    
2674
            # Roll back any change if something goes wrong
2675
            conn.rollback()
2676
            
2677
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2678
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2679
        finally:
2680
            # Close the db connection
2681
            conn.close()
2682

    
2683
        return result
2684

    
2685
    '''
2686
        @brief      get instrument data list
2687
        @author     kyouho
2688
        @date       2018.08.14
2689
    '''
2690
    def getInstrumentDataList(self, docName = None):
2691
        result = []
2692
        try:
2693
            # Creates or opens a file called mydb with a SQLite3 DB
2694
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2695
            conn = sqlite3.connect(dbPath)
2696
            # Get a cursor object
2697
            cursor = conn.cursor()
2698

    
2699
            #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'
2700
            sql = 'select * from INSTRUMENT_DATA_LIST'
2701
            if docName is not None:
2702
                sql += " where PNID_NO = '{}'".format(docName)
2703

    
2704
            cursor.execute(sql)
2705
            rows = cursor.fetchall()
2706
            for row in rows:
2707
                data = []
2708
                for index in range(len(cursor.description)): 
2709
                    data.append(row[index])
2710
                result.append(data)
2711
        # Catch the exception
2712
        except Exception as ex:
2713
            # Roll back any change if something goes wrong
2714
            conn.rollback()
2715
            from App import App
2716

    
2717
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2718
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2719
        finally:
2720
            # Close the db connection
2721
            conn.close()
2722

    
2723
        return result
2724

    
2725
    '''
2726
        @brief      get Note data list
2727
        @author     kyouho
2728
        @date       2018.10.10
2729
    '''
2730
    def getNoteDataList(self, docName = None):
2731
        result = []
2732
        try:
2733
            # Creates or opens a file called mydb with a SQLite3 DB
2734
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2735
            conn = sqlite3.connect(dbPath)
2736
            # Get a cursor object
2737
            cursor = conn.cursor()
2738

    
2739
            sql = 'select UID, NOTE_NO, DESCRIPTION, PNID_NO from NOTE_DATA_LIST'
2740
            if docName is not None:
2741
                sql += " where PNID_NO = '{}'".format(docName)
2742

    
2743
            sql += ' ORDER BY NOTE_NO ASC'
2744
            cursor.execute(sql)
2745
            rows = cursor.fetchall()
2746
            for row in rows:
2747
                data = []
2748
                for index in range(len(cursor.description)): 
2749
                    data.append(row[index])
2750
                result.append(data)
2751
        # Catch the exception
2752
        except Exception as ex:
2753
            # Roll back any change if something goes wrong
2754
            conn.rollback()
2755
            from App import App
2756

    
2757
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2758
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2759
        finally:
2760
            # Close the db connection
2761
            conn.close()
2762

    
2763
        return result
2764

    
2765

    
2766
    '''
2767
        @brief      save to database
2768
        @author     yjkim
2769
        @date       2019.08.28
2770
    '''
2771
    def saveToDatabase(self, item, index):
2772
        """ save given items to database """
2773
        conn = sqlite3.connect(self.activeDrawing.path, isolation_level=None)
2774
        with conn:
2775
            try:
2776
                # Get a cursor object
2777
                cursor = conn.cursor()
2778

    
2779
                if index == 0:
2780
                    # delete Points
2781
                    sql = 'delete from Points'
2782
                    cursor.execute(sql)
2783

    
2784
                    # delete HMB
2785
                    sql = 'delete from HMB'
2786
                    cursor.execute(sql)
2787

    
2788
                    # delete Components 
2789
                    sql = 'delete from Components'
2790
                    cursor.execute(sql)
2791
                
2792
                sql = item.toSql()
2793
                if type(sql) is list:
2794
                    for item in sql:
2795
                        if item is not None and 2 == len(item):
2796
                            cursor.execute(item[0], item[1])
2797
                else:
2798
                    if sql is not None and 2 == len(sql):
2799
                        cursor.execute(sql[0], sql[1])
2800

    
2801
                conn.commit()
2802
            # Catch the exception
2803
            except Exception as ex:
2804
                from App import App
2805
                # Roll back any change if something goes wrong
2806
                conn.rollback()
2807

    
2808
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2809
                print(message)
2810
                print(sql)
2811
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2812

    
2813
    '''
2814
        @brief      set equipment data list
2815
        @author     humkyung
2816
        @date       2018.05.03
2817
    '''
2818
    def setEquipmentDataList(self, dataList):
2819
        try:
2820
            # Creates or opens a file called mydb with a SQLite3 DB
2821
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2822
            conn = sqlite3.connect(dbPath)
2823
            # Get a cursor object
2824
            cursor = conn.cursor()
2825

    
2826
            for data in dataList:
2827
                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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2828
                param = tuple(data)
2829
                cursor.execute(sql, param)
2830
            conn.commit()
2831
        # Catch the exception
2832
        except Exception as ex:
2833
            # Roll back any change if something goes wrong
2834
            conn.rollback()
2835
            from App import App
2836

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

    
2843
    """
2844
        @brief      exists drawing
2845
        @author     yeonjin
2846
        @date       2019.07.03
2847
    """
2848
    def exists_drawing(self, drawingName):
2849
        rows = None
2850
        try:           
2851
            # Creates or opens a file called mydb with a SQLite3 DB
2852
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2853
            conn = sqlite3.connect(dbPath)
2854
            # Get a cursor object
2855
            cursor = conn.cursor()
2856
            sql = "select name from Drawings where upper(name) = '" + drawingName.upper() + "'"
2857
            cursor.execute(sql)
2858
            rows = cursor.fetchall()
2859
        # Catch the exception
2860
        except Exception as ex:
2861
            # Roll back any change if something goes wrong
2862
            conn.rollback()
2863
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2864
        finally:
2865
            # Close the db connection
2866
            conn.close()
2867
            if rows is not None and len(rows) > 0:
2868
                return True
2869
            else:
2870
                return False
2871

    
2872
    def getDrawings(self):
2873
        """
2874
        @brief      get drawings
2875
        @author     humkyung
2876
        @date       2018.11.03
2877
        """
2878
        from Drawing import Drawing
2879

    
2880
        res = []
2881
        # Creates or opens a file called mydb with a SQLite3 DB
2882
        dbPath = self.getAppDbPath()
2883
        conn = sqlite3.connect(dbPath)
2884
        with conn:
2885
            try:
2886
                conn.row_factory = sqlite3.Row
2887
                # Get a cursor object
2888
                cursor = conn.cursor()
2889

    
2890
                sql = 'select UID,[NAME],[DATETIME] from Drawings'
2891
                cursor.execute(sql)
2892
                rows = cursor.fetchall()
2893
                for row in rows:
2894
                    res.append(Drawing(row[0], row[1], row[2]))
2895
            # Catch the exception
2896
            except Exception as ex:
2897
                # Roll back any change if something goes wrong
2898
                conn.rollback()
2899
                from App import App
2900

    
2901
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2902
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2903

    
2904
        return res
2905

    
2906
    '''
2907
        @brief      update drawings
2908
        @author     yeonjin
2909
        @date       2019.08.07
2910
    '''
2911
    def updateDrawing(self, drawing):
2912
        import uuid
2913
        
2914
        # Creates or opens a file called mydb with a SQLite3 DB
2915
        dbPath = self.getAppDbPath()
2916
        conn = sqlite3.connect(dbPath)
2917
        with conn:
2918
            try:
2919
                # Get a cursor object
2920
                cursor = conn.cursor()
2921
                    
2922
                sql = """update Drawings
2923
                            set Name = ?
2924
                                , DateTime = ?
2925
                            where uid = ?"""
2926
                param = (drawing[0][1], drawing[0][2], drawing[0][0])
2927
                cursor.execute(sql, param)
2928

    
2929
                conn.commit()
2930

    
2931
            # Catch the exception
2932
            except Exception as ex:
2933
                # Roll back any change if something goes wrong
2934
                conn.rollback()
2935
                from App import App
2936

    
2937
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2938
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2939

    
2940
    '''
2941
        @brief      save drawings
2942
        @author     humkyung
2943
        @date       2018.11.03
2944
    '''
2945
    def saveDrawing(self, drawing):
2946
        import uuid
2947
        from shutil import copyfile       
2948

    
2949
        conn = sqlite3.connect(self.getAppDbPath())
2950
        with conn:
2951
            try:
2952
                # Get a cursor object
2953
                cursor = conn.cursor()
2954
                    
2955
                sql = 'insert or replace into Drawings(UID, [NAME], [DATETIME]) values(?, ?, ?)'
2956
                param = (drawing.UID, drawing.path, drawing.date_time)
2957
                cursor.execute(sql, param)
2958

    
2959
                conn.commit()
2960

    
2961
                if not os.path.exists(drawing.path): copyfile(self.getTemplateDbPath(), drawing.path)
2962
            # Catch the exception
2963
            except Exception as ex:
2964
                # Roll back any change if something goes wrong
2965
                conn.rollback()
2966
                from App import App
2967

    
2968
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2969
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2970

    
2971
    '''
2972
        @brief      Return Symbol Category Items
2973
        @author     yeonjin
2974
        @date       19.07.11
2975
    '''
2976
    def getSymbolCategoryList(self):
2977
        SymbolCategoryList = []
2978

    
2979
        conn = sqlite3.connect(self.getTemplateDbPath())
2980
        with conn:
2981
            cursor = conn.cursor()
2982
            sql = 'SELECT DISTINCT CATEGORY FROM SymbolType ORDER BY type ASC'
2983
            try:
2984
                cursor.execute(sql)
2985
                rows = cursor.fetchall()
2986
                for row in rows:
2987
                    SymbolCategoryList.append((row[0])) # category
2988
            except Exception as ex:
2989
                from App import App
2990

    
2991
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2992
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2993

    
2994
        return SymbolCategoryList
2995

    
2996

    
2997
    def getComponentByComponentUID(self, uid):
2998
        ComponentList = []
2999

    
3000
        conn = sqlite3.connect(self.activeDrawing.path)
3001
        with conn:
3002
            try:
3003
                conn.row_factory = sqlite3.Row
3004
                cursor = conn.cursor()
3005
                
3006
                sql = """select c.uid
3007
                                , c.Name
3008
                                , c.Symbols_UID
3009
                                , t.Category
3010
                                , t.type
3011
                                , s.Name
3012
                                , s.OriginalPoint
3013
                                , c.X
3014
                                , c.Y
3015
                                , c.Rotation
3016
                                , c.Scale
3017
                                , p.uid
3018
                                , p.[Index]
3019
                                , p.x
3020
                                , p.y
3021
                                , p.ConnectedItem_UID
3022
                            from points p
3023
                            left join components c
3024
                                on p.components_uid = c.uid
3025
                            left join symbols s
3026
                                on c.Symbols_UID = s.UID    
3027
                            left join SymbolType t
3028
                                on s.symboltype_uid = t.uid
3029
                            where c.uid = ?
3030
                            order by p.[Index]"""
3031
                param = (uid,)                      
3032
                cursor.execute(sql, param)
3033
                rows = cursor.fetchall()
3034
                for row in rows:
3035
                    data = []
3036
                    for index in range(len(cursor.description)):
3037
                        data.append(row[index])
3038
                    ComponentList.append(data) # Components_UID
3039
            except Exception as ex:
3040
                from App import App
3041

    
3042
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3043
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3044

    
3045
        return ComponentList
3046

    
3047
    def get_nozzle_data(self, uid):
3048
        """ get nozzle data of given uid """
3049
        from EngineeringConnectorItem import NozzleData
3050

    
3051
        res = None
3052
        conn = sqlite3.connect(self.activeDrawing.path)
3053
        with conn:
3054
            conn.row_factory = sqlite3.Row
3055
            cursor = conn.cursor()
3056
            sql = 'select Pressure, Pressure_Drop, Elevation, Over_Design_CV from Nozzles where Points_UID=?' 
3057
            param = (uid, )
3058
            cursor.execute(sql, param)
3059
            rows = cursor.fetchall()
3060
            if rows:
3061
                res = NozzleData()
3062
                if rows[0]['Pressure']:
3063
                    res.pressure = float(rows[0]['Pressure'])
3064
                if rows[0]['Pressure_Drop']:
3065
                    res.pressure_drop = float(rows[0]['Pressure_Drop'])
3066
                if rows[0]['Elevation']:
3067
                    res.elevation = float(rows[0]['Elevation'])
3068
                if rows[0]['Over_Design_CV']:
3069
                    res.over_design_cv = float(rows[0]['Over_Design_CV'])
3070
        return res
3071

    
3072
    def getDrawingsUnitsByDrawingUID(self, drawing):
3073
        """ get units of drawing """
3074
        unitsList = []
3075

    
3076
        conn = sqlite3.connect(drawing.path)
3077
        with conn:
3078
            cursor = conn.cursor()
3079

    
3080
            sql = 'select du.Units, u.Value from DrawingsUnits du \
3081
                                                 left join units u on du.Units_UID = u.uid'
3082
            try:
3083
                cursor.execute(sql)
3084
                rows = cursor.fetchall()
3085
                for row in rows:
3086
                    unitsList.append((row[0], row[1])) 
3087
            except Exception as ex:
3088
                from App import App
3089

    
3090
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3091
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3092

    
3093
        return unitsList
3094

    
3095

    
3096
    '''
3097
        @brief      Return Components By DrawingUID
3098
        @author     yeonjin
3099
        @date       19.07.29
3100
    '''
3101
    def getComponentListByDrawingUID(self, drawing):
3102
        ComponentList = []
3103

    
3104
        conn = sqlite3.connect(drawing.path)
3105
        with conn:
3106
            try:
3107
                conn.row_factory = sqlite3.Row
3108
                cursor = conn.cursor()
3109
                sql = 'select UID from Components order by x desc'
3110
                cursor.execute(sql)
3111
                rows = cursor.fetchall()
3112
                for row in rows:
3113
                    ComponentList.append((row[0])) # Components_UID
3114
            except Exception as ex:
3115
                from App import App
3116

    
3117
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3118
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3119

    
3120
        return ComponentList
3121

    
3122
    '''
3123
        @brief      Return Symbol Type Items By Category
3124
        @author     yeonjin
3125
        @date       19.07.11
3126
    '''
3127
    def getSymbolTypeListByCategory(self, category):
3128
        symbolTypeList = []
3129

    
3130
        conn = sqlite3.connect(self.getTemplateDbPath())
3131
        with conn:
3132
            cursor = conn.cursor()
3133
            sql = 'SELECT UID, Category, Type FROM SymbolType WHERE Category = "' + category + '"'
3134
            try:
3135
                cursor.execute(sql)
3136
                rows = cursor.fetchall()
3137
                for row in rows:
3138
                    symbolTypeList.append((row[0], row[1], row[2])) # UID, Category, Type
3139
            except Exception as ex:
3140
                from App import App
3141

    
3142
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3143
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3144

    
3145
        return symbolTypeList
3146

    
3147
    def getUnits(self):
3148
        unitsList = []
3149

    
3150
        try:            
3151
            conn = sqlite3.connect(self.activeDrawing.path)
3152
            cursor = conn.cursor()
3153
            sql = 'Select UID, Key, Value From Units'
3154
            try:
3155
                cursor.execute(sql)
3156
                rows = cursor.fetchall()
3157
                for row in rows:
3158
                    unitsList.append((row[0], row[1], row[2])) # UID, Key, Value
3159
            except Exception as ex:
3160
                from App import App
3161

    
3162
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3163
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3164
        finally:
3165
            conn.close()
3166

    
3167
        return unitsList
3168

    
3169

    
3170
    def getUnitsByDrawingName(self, drawingName):
3171
        unitsList = []
3172

    
3173
        try:
3174
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3175

    
3176
            conn = sqlite3.connect(dbPath)
3177
            cursor = conn.cursor()
3178
            sql = """select ifnull(d.display_name, u.column_name)
3179
                          , u.UNIT
3180
                       from units u
3181
                       left join displayNames d
3182
                         on u.TABLE_NAME = d.TABLE_NAME and u.COLUMN_NAME = d.COLUMN_NAME    
3183
                      where u.uid in (
3184
                                        select distinct du.units_uid
3185
                                          from drawings d
3186
                                         inner join drawingsunits du
3187
                                            on d.uid = du.drawings_uid
3188
                                         where d.name = ?
3189
                                     )
3190
                        and u.table_name = 'HMB'"""
3191
            param = (drawingName, )
3192
            try:
3193
                cursor.execute(sql, param)
3194
                rows = cursor.fetchall()
3195
                for row in rows:
3196
                    unitsList.append((row[0], row[1])) 
3197
            except Exception as ex:
3198
                from App import App
3199

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

    
3205
        return unitsList
3206

    
3207
    def getHMBDisplayNameAndUnitsExpression(self):
3208
        res = []
3209

    
3210
        if self.activeDrawing:
3211
            conn = sqlite3.connect(self.activeDrawing.path)
3212
            with conn:
3213
                cursor = conn.cursor()
3214
                sql = """SELECT dn.DISPLAY_NAME
3215
                                , hu.Units_Expression
3216
                            FROM DisplayNames dn
3217
                            left join HMBUnits hu
3218
                                on dn.COLUMN_NAME = Hu.Column_Name
3219
                            where dn.Table_Name = 'HMB'
3220
                            order by dn.[Order]"""    
3221
                try:
3222
                    cursor.execute(sql)  
3223
                    rows = cursor.fetchall()
3224
                    for row in rows:
3225
                        res.append((row[0], row[1])) 
3226
                except Exception as ex:
3227
                    from App import App
3228

    
3229
                    message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3230
                    App.mainWnd().addMessage.emit(MessageType.Error, message)
3231

    
3232
        return res
3233

    
3234

    
3235

    
3236
    def getColumnDisplayNames(self, uid, table):
3237
        columnDisplayNameList = []
3238

    
3239
        try:
3240
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3241

    
3242
            conn = sqlite3.connect(dbPath)
3243
            cursor = conn.cursor()
3244
            sql = """SELECT dn.DISPLAY_NAME
3245
                          , u.Value
3246
                       FROM DisplayNames dn
3247
                       left join drawingsUnits du
3248
                         on dn.TABLE_NAME = du.Table_Name and dn.COLUMN_NAME = du.Column_Name
3249
                       left join Units u
3250
                         on du.Units_UID = u.UID
3251
                      where du.Drawings_UID = ?
3252
                        and dn.Table_Name = ?
3253
                      order by dn.[Order]"""    
3254
            try:
3255
                param = (uid, table,)
3256
                cursor.execute(sql, param)
3257
  
3258
                rows = cursor.fetchall()
3259
                for row in rows:
3260
                    columnDisplayNameList.append((row[0], row[1])) # Display_Name
3261
            except Exception as ex:
3262
                from App import App
3263

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

    
3269
        return columnDisplayNameList
3270

    
3271

    
3272

    
3273
    '''
3274
        @brief      Return Symbol Type Items
3275
        @author     Jeongwoo
3276
        @date       18.04.20
3277
        @history    18.05.08    Jeongwoo type index changed
3278
    '''
3279
    def getSymbolTypeList(self):
3280
        symbolTypeList = []
3281

    
3282
        try:
3283
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3284

    
3285
            conn = sqlite3.connect(dbPath)
3286
            cursor = conn.cursor()
3287
            sql = 'SELECT * FROM SymbolType ORDER BY type ASC'
3288
            try:
3289
                cursor.execute(sql)
3290
                rows = cursor.fetchall()
3291
                for row in rows:
3292
                    symbolTypeList.append((row[0], row[1], row[2])) # UID, category, type
3293
            except Exception as ex:
3294
                from App import App
3295

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

    
3301
        return symbolTypeList
3302

    
3303
    '''
3304
        @brief      Get Symbol Category by Symbol Type
3305
        @author     Jeongwoo
3306
        @date       2018.05.09
3307
    '''
3308
    def getSymbolCategoryByType(self, type):
3309
        category = None
3310

    
3311
        conn = sqlite3.connect(self.activeDrawing.path)
3312
        with conn:
3313
            try:
3314
                cursor = conn.cursor()
3315
                sql = 'SELECT Category FROM SymbolType WHERE type = "' + type + '"'
3316
                cursor.execute(sql)
3317
                rows = cursor.fetchall()
3318
                if rows is not None and len(rows) > 0:
3319
                    category = rows[0][0]
3320
            except Exception as ex:
3321
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
3322

    
3323
        return category
3324

    
3325
    '''
3326
        @brief      Check Symbol Type is included in 'Equipment' Category
3327
        @author     Jeongwoo
3328
        @date       2018.05.09
3329
    '''
3330
    def isEquipmentType(self, type):
3331
        category = self.getSymbolCategoryByType(type)
3332
        return (category is not None and category == 'Equipment')
3333

    
3334
    '''
3335
        @brief      Return Symbol Type Items with "None"
3336
        @author     Jeongwoo
3337
        @date       18.04.06
3338
        @history    Seperate SymbolTypeList and "None"
3339
    '''
3340
    def getSymbolTypeComboBoxItems(self):
3341
        symbolTypeList = self.getSymbolTypeList()
3342
        symbolTypeList.insert(0, ('None', 'None', 'None'))
3343

    
3344
        return symbolTypeList
3345

    
3346
    '''
3347
        @brief  get Base Symbol ComboBox Items
3348
    '''
3349
    def getBaseSymbolComboBoxItems(self, type = None):
3350
        bsymbolNameList = self.getSymbolNameListByType(type)
3351
        bsymbolNameList.sort()
3352
        bsymbolNameList.insert(0, "None")
3353
        return bsymbolNameList
3354

    
3355
    '''
3356
        @brief  get Additional Symbol ComboBox Items
3357
    '''
3358
    def getAdditionalSymbolComboBoxItems(self):
3359
        asymbolNameList = self.getSymbolNameList()
3360
        asymbolNameList.sort()
3361
        asymbolNameList.insert(0, "None")
3362
        return asymbolNameList
3363

    
3364
    '''
3365
        @brief  get Additional Symbol's default direction ComboBox Items
3366
    '''
3367
    def getDefaultSymbolDirectionComboBoxItems(self):
3368
        return [("UP", 0), ("DOWN", 2), ("LEFT", 3), ("RIGHT", 1)]
3369
    
3370
    '''
3371
        @brief  getter of activeDrawing
3372
        @author humkyung
3373
        @date   2018.07.07
3374
    '''
3375
    @property
3376
    def activeDrawing(self):
3377
        return self._activeDrawing
3378

    
3379
    '''
3380
        @brief  setter of activeDrawing
3381
        @author humkyung
3382
        @date   2018.07.07
3383
    '''
3384
    @activeDrawing.setter
3385
    def activeDrawing(self, value):
3386
        self._activeDrawing = value
3387

    
3388
    def getColNames(self, table):
3389
        """
3390
        return column names of given table and attribute names if tabe is VALVE_DATA_LIST or EQUIPMET_DATA_LIST
3391
        """
3392
        res = None
3393
        try:
3394
            # Creates or opens a file called mydb with a SQLite3 DB
3395
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3396
            conn = sqlite3.connect(dbPath)
3397
            cursor = conn.execute('select * from {}'.format(table))
3398
            res = [col_name[0] for col_name in cursor.description]
3399

    
3400
            if table == 'EQUIPMET_DATA_LIST' or table == 'VALVE_DATA_LIST':
3401
                sql = 'select distinct c.Attribute from {} a left join Attributes b on a.uid=b.Components_UID ' \
3402
                                                            'left join SymbolAttribute c on b.SymbolAttribute_UID=c.UID where c.Attribute is not NULL'.format(table)
3403
                cursor = conn.execute(sql)
3404
                rows = cursor.fetchall()
3405
                for row in rows:
3406
                    res.append(row[0])
3407
        # Catch the exception
3408
        except Exception as ex:
3409
            # Roll back any change if something goes wrong
3410
            conn.rollback()
3411
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
3412
        finally:
3413
            # Close the db connection
3414
            conn.close()
3415

    
3416
        return res
3417
    
3418
    def add_column_into_table(self, table, columnName):
3419
        '''
3420
            @brief  add column into table
3421
            @author euisung
3422
            @date   2019.03.13
3423
        '''
3424
        err = False
3425
        try:
3426
            # Creates or opens a file called mydb with a SQLite3 DB
3427
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3428
            conn = sqlite3.connect(dbPath)
3429
            # Get a cursor object
3430
            cursor = conn.cursor()
3431
            sql = "alter table {} add {}".format(table, columnName)
3432
            cursor.execute(sql)
3433

    
3434
            conn.commit()
3435

    
3436
        # Catch the exception
3437
        except Exception as ex:
3438
            # Roll back any change if something goes wrong
3439
            conn.rollback()
3440
            err = True
3441
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
3442
        finally:
3443
            # Close the db connection
3444
            conn.close()
3445
            return (True if not err else False)
3446

    
3447
    def edit_column_Name_in_table(self, table, columnName, newColName):
3448
        '''
3449
            @brief  edit column into table
3450
            @author euisung
3451
            @date   2019.03.13
3452
        '''
3453
        err = False
3454
        colNames = AppDocData.instance().getColNames(table)
3455

    
3456
        for index in range(len(colNames)):
3457
            if colNames[index] == columnName:
3458
                colNames[index] = newColName
3459
                break
3460

    
3461
        try:
3462
            # Creates or opens a file called mydb with a SQLite3 DB
3463
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3464
            conn = sqlite3.connect(dbPath)
3465
            # Get a cursor object
3466
            cursor = conn.cursor()
3467
            sql = "ALTER TABLE {} RENAME TO {}".format(table, table + '_orig')
3468
            cursor.execute(sql)
3469
            value = []
3470
            for colName in colNames:
3471
                value.append(colName + ' TEXT')
3472
            sql = "CREATE TABLE {}({}, CONSTRAINT '{}_PK' PRIMARY KEY('UID'))".format(table, ','.join(value), table)
3473
            cursor.execute(sql)
3474
            sql = "INSERT INTO {} SELECT * FROM {}".format(table, table + '_orig')
3475
            cursor.execute(sql)
3476
            sql = "DROP TABLE {}".format(table + '_orig')
3477
            cursor.execute(sql)
3478

    
3479
            conn.commit()
3480

    
3481
        # Catch the exception
3482
        except Exception as ex:
3483
            # Roll back any change if something goes wrong
3484
            conn.rollback()
3485
            err = True
3486
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
3487
        finally:
3488
            # Close the db connection
3489
            conn.close()
3490
            return (True if not err else False)
3491

    
3492
    '''
3493
        @brief  getter of OCRData
3494
        @author humkyung
3495
        @date   2018.11.19
3496
    '''
3497
    @property
3498
    def OCRData(self):
3499
        if self._OCRData is None:
3500
            configs = self.getConfigs('Text Recognition', 'OCR Data')
3501
            self._OCRData = configs[0].value if 1 == len(configs) else 'eng'
3502

    
3503
        return self._OCRData
3504

    
3505
    '''
3506
        @brief  setter of OCRData
3507
        @author humkyung
3508
        @date   2018.11.19
3509
    '''
3510
    @OCRData.setter
3511
    def OCRData(self, value):
3512
        self._OCRData = value
클립보드 이미지 추가 (최대 크기: 500 MB)