프로젝트

일반

사용자정보

통계
| 개정판:

hytos / HYTOS / HYTOS / AppDocData.py @ 56332ce8

이력 | 보기 | 이력해설 | 다운로드 (62.3 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

    
25
class Source:
26
    def __init__(self, source):
27
        if type(source) is np.ndarray:
28
            self.source = Image.fromarray(source)
29
        elif type(source) is PngImagePlugin.PngImageFile or type(source) is JpegImagePlugin.JpegImageFile:
30
            self.source = source
31
        elif type(source) is QImage:
32
            self.source = Image.fromqimage(source)
33
        elif type(source) is QPixmap:
34
            self.source = Image.fromqpixmap(source)
35

    
36
    '''
37
        @history    2018.05.18  Jeongwoo    When Parameter [rect] is None, return whole image
38
    '''
39

    
40
    def getPyImageOnRect(self, rect=None):
41
        if rect is not None:
42
            return self.source.copy().crop((rect.left(), rect.top(), rect.right(), rect.bottom()))
43
        else:
44
            return self.source.copy()
45

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

    
50

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

    
57

    
58
'''
59
    @brief      MessageType
60
    @author     humkyung 
61
    @date       2018.07.31
62
'''
63

    
64

    
65
class MessageType(Enum):
66
    Normal = 1
67
    Error = 2
68
    Information = 3
69

    
70

    
71
class AppDocData(SingletonInstane):
72

    
73
    def __init__(self):
74

    
75
        self._imgFilePath = None
76
        self.imgName = None
77
        self.imgWidth = 0
78
        self.imgHeight = 0
79
        self._OCRData = None
80

    
81
        self._areas = []
82
        self.equipments = []
83
        self.lineNos = []
84
        self.lines = []
85
        self.texts = []
86
        self.symbols = []
87
        self.unknowns = []
88
        self.tracerLineNos = []
89
        self.lineIndicators = []
90
        self._colors = None
91
        self._lineNoProperties = None
92
        self._lineTypes = None
93
        self._lineTypeConfigs = None
94
        self._activeDrawing = None
95
        self._titleBlockProperties = None
96
        self.needReOpening = None
97

    
98
        self.configTable = None
99

    
100
    def clearItemList(self, trim):
101
        '''
102
            @brief      clear item list
103
            @author     euisung
104
            @date       2018.11.28
105
        '''
106
        self.equipments.clear()
107
        self.symbols.clear()
108
        self.lineNos.clear()
109
        self.texts.clear()
110
        self.lines.clear()
111
        self.unknowns.clear()
112
        self.lineIndicators.clear()
113
        if trim:
114
            self.tracerLineNos.clear()
115

    
116
    '''
117
        @brief      clear
118
        @author     humkyung
119
        @date       2018.09.06
120
    '''
121

    
122
    def clear(self):
123
        self._imgFilePath = None
124
        self.imgName = None
125
        self.imgWidth = 0
126
        self.imgHeight = 0
127

    
128
        self._areas.clear()
129
        self.equipments.clear()
130
        self.lineNos.clear()
131
        self.lines.clear()
132
        self.texts.clear()
133
        self.symbols.clear()
134
        self.unknowns.clear()
135
        self.tracerLineNos.clear()
136
        self.lineIndicators.clear()
137
        self._colors = None
138
        self._lineNoProperties = None
139
        self._lineTypeConfigs = None
140
        self._activeDrawing = None
141
        self._titleBlockProperties = None
142

    
143
    '''
144
        @brief      Get DB file path in ProgramData
145
        @author     Jeongwoo
146
        @date       2018.06.27
147
        @history    2018.06.29  Jeongwoo    Change method to get template db path
148
    '''
149

    
150
    def getTemplateDbPath(self):
151
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
152
        templateDbPath = os.path.join(path, 'Template.db')
153
        return templateDbPath
154

    
155
    def getTemplateSymbolCategoryList(self):
156
        symbolCategoryList = []
157

    
158
        conn = sqlite3.connect(self.getTemplateDbPath())
159
        with conn:
160
            cursor = conn.cursor()
161
            sql = 'SELECT distinct category FROM SymbolType ORDER BY Category'
162
            try:
163
                cursor.execute(sql)
164
                rows = cursor.fetchall()
165
                for row in rows:
166
                    symbolCategoryList.append((row[0]))
167
            except Exception as ex:
168
                from App import App
169
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
170
                                                               sys.exc_info()[-1].tb_lineno)
171
                App.mainWnd().addMessage.emit(MessageType.Error, message)
172

    
173
        return symbolCategoryList
174

    
175
    def getTemplateSymbolTypeList(self, category):
176
        symbolCategoryList = []
177

    
178
        conn = sqlite3.connect(self.getTemplateDbPath())
179
        with conn:
180
            cursor = conn.cursor()
181
            sql = 'SELECT UID, Type FROM SymbolType Where Category = ? ORDER BY Type'
182

    
183
            try:
184
                param = (category,)
185
                cursor.execute(sql, param)
186
                rows = cursor.fetchall()
187
                for row in rows:
188
                    symbolCategoryList.append((row[0], row[1]))
189
            except Exception as ex:
190
                from App import App
191
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
192
                                                               sys.exc_info()[-1].tb_lineno)
193
                App.mainWnd().addMessage.emit(MessageType.Error, message)
194

    
195
        return symbolCategoryList
196

    
197
    def updateTemplateSymbol(self, uid, originalPoint, connectionPoint):
198
        isUpdated = False
199

    
200
        try:
201
            conn = sqlite3.connect(self.getTemplateDbPath())
202
            conn.execute('PRAGMA foreign_keys = ON')
203
            # Get a cursor object
204
            cursor = conn.cursor()
205

    
206
            sql = """Update Symbols
207
                        set OriginalPoint = ?
208
                          , ConnectionPoint = ?
209
                      where UID = ?"""
210

    
211
            param = (originalPoint, connectionPoint, uid)
212
            cursor.execute(sql, param)
213
            conn.commit()
214
            isUpdated = True
215
        # Catch the exception
216
        except Exception as ex:
217
            from App import App
218
            # Roll back any change if something goes wrong
219
            conn.rollback()
220

    
221
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
222
                                                           sys.exc_info()[-1].tb_lineno)
223
            App.mainWnd().addMessage.emit(MessageType.Error, message)
224
        finally:
225
            # Close the db connection
226
            conn.close()
227
            return isUpdated
228

    
229
    def getTemplateSymbol(self, UID):
230
        symbolList = []
231

    
232
        conn = sqlite3.connect(self.getTemplateDbPath())
233
        with conn:
234
            cursor = conn.cursor()
235
            sql = 'SELECT UID, Name, OriginalPoint, ConnectionPoint FROM Symbols Where UID = ? ORDER BY Name'
236

    
237
            try:
238
                param = (UID,)
239
                cursor.execute(sql, param)
240
                rows = cursor.fetchall()
241
                for row in rows:
242
                    symbolList.append((row[0], row[1], row[2], row[3]))
243
            except Exception as ex:
244
                from App import App
245
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
246
                                                               sys.exc_info()[-1].tb_lineno)
247
                App.mainWnd().addMessage.emit(MessageType.Error, message)
248

    
249
        return symbolList
250

    
251
    def getTemplateSymbolNameList(self, typeUID):
252
        symbolCategoryList = []
253

    
254
        conn = sqlite3.connect(self.getTemplateDbPath())
255
        with conn:
256
            cursor = conn.cursor()
257
            sql = 'SELECT UID, Name FROM Symbols Where SymbolType_UID = ? ORDER BY Name'
258

    
259
            try:
260
                param = (typeUID,)
261
                cursor.execute(sql, param)
262
                rows = cursor.fetchall()
263
                for row in rows:
264
                    symbolCategoryList.append((row[0], row[1]))
265
            except Exception as ex:
266
                from App import App
267
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
268
                                                               sys.exc_info()[-1].tb_lineno)
269
                App.mainWnd().addMessage.emit(MessageType.Error, message)
270

    
271
        return symbolCategoryList
272

    
273
    def getAppDbPath(self):
274
        """
275
        @brief      Get application DB file path in ProgramData
276
        @author     humkyung
277
        @date       2018.10.01
278
        """
279

    
280
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
281
        app_database = os.path.join(path, 'App.db')
282
        return app_database
283

    
284
    '''
285
        @brief  build application database
286
        @author humkyung
287
        @date   2018.04.20
288
    '''
289

    
290
    def buildAppDatabase(self):
291
        try:
292
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'HYTOS')
293
            appDatabaseFilePath = os.path.join(path, 'App.db')
294

    
295
            # Creates or opens a file called mydb with a SQLite3 DB
296
            conn = sqlite3.connect(appDatabaseFilePath)
297
            conn.execute('PRAGMA foreign_keys = ON')
298
            with conn:
299
                # Get a cursor object
300
                cursor = conn.cursor()
301

    
302
                sqlFiles = ['App.sql']
303
                for sqlFile in sqlFiles:
304
                    filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', sqlFile)
305
                    try:
306
                        file = QFile(filePath)
307
                        file.open(QFile.ReadOnly)
308
                        sql = file.readAll()
309
                        sql = str(sql, encoding='utf8')
310
                        cursor.executescript(sql)
311
                    finally:
312
                        file.close()
313
                conn.commit()
314
        # Catch the exception
315
        except Exception as ex:
316
            from App import App
317
            # Roll back any change if something goes wrong
318
            conn.rollback()
319

    
320
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
321
                                                           sys.exc_info()[-1].tb_lineno)
322
            App.mainWnd().addMessage.emit(MessageType.Error, message)
323

    
324
    '''
325
        @brief  load app style
326
        @author humkyung
327
        @date   2018.04.20
328
    '''
329

    
330
    def loadAppStyle(self):
331
        style = 'Fusion'
332

    
333
        self.buildAppDatabase()
334

    
335
        return style
336

    
337
    @property
338
    def border_file_path(self):
339
        """ return border file path """
340

    
341
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
342
        return os.path.join(path, 'Border.png')
343

    
344
    @property
345
    def symbol_file_path(self):
346
        """ return svg symbol file path """
347

    
348
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
349
        return os.path.join(path, 'svg')
350

    
351
    def update_symbol_shape(self, drawing, symbol, svg_file):
352
        """update symbol shape"""
353

    
354
        conn = sqlite3.connect(drawing)
355
        conn.execute('PRAGMA foreign_keys = ON')
356
        with conn:
357
            try:
358
                conn.row_factory = sqlite3.Row
359
                # Get a cursor object
360
                cursor = conn.cursor()
361

    
362
                sql = f"update Symbols set Shape = ? where UID='{symbol}'"
363

    
364
                blob_data = None
365
                with open(svg_file, 'rb') as file:
366
                    blob_data = file.read()
367

    
368
                # Convert data into tuple format
369
                params = (blob_data,)
370
                cursor.execute(sql, params)
371
                conn.commit()
372

    
373
            # Catch the exception
374
            except Exception as ex:
375
                from App import App
376
                # Roll back any change if something goes wrong
377
                conn.rollback()
378

    
379
                message = 'error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename,
380
                                                               sys.exc_info()[-1].tb_lineno)
381
                App.mainWnd().addMessage.emit(MessageType.Error, message)
382

    
383
    def read_symbol_shape(self, drawing, symbol):
384
        """read symbol shape"""
385

    
386
        res = None
387

    
388
        with sqlite3.connect(drawing) as conn:
389
            conn.execute('PRAGMA foreign_keys = ON')
390
            try:
391
                conn.row_factory = sqlite3.Row
392
                # Get a cursor object
393
                cursor = conn.cursor()
394

    
395
                sql = f"select Shape from Symbols where UID='{symbol}'"
396
                cursor.execute(sql)
397
                records = cursor.fetchall()
398
                for record in records:
399
                    res = record[0]
400
                    break
401

    
402
            # Catch the exception
403
            except Exception as ex:
404
                from App import App
405
                # Roll back any change if something goes wrong
406
                conn.rollback()
407

    
408
                message = 'error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename,
409
                                                               sys.exc_info()[-1].tb_lineno)
410
                App.mainWnd().addMessage.emit(MessageType.Error, message)
411

    
412
        return res
413

    
414
    def getRoughness(self, phase_type):
415
        res = []
416

    
417
        conn = sqlite3.connect(self.activeDrawing.path)
418
        conn.execute('PRAGMA foreign_keys = ON')
419
        with conn:
420
            try:
421
                conn.row_factory = sqlite3.Row
422
                # Get a cursor object
423
                cursor = conn.cursor()
424

    
425
                sql = "select UID, Material, Meter, Inch, Feet, Milimeter from Roughness where phase_type = ?"
426
                param = (phase_type, )
427
                cursor.execute(sql, param)
428
                rows = cursor.fetchall()
429
                for row in rows:
430
                    res.append((row[0], row[1], row[2], row[3], row[4], row[5]))
431
            # Catch the exception
432
            except Exception as ex:
433
                from App import App
434
                # Roll back any change if something goes wrong
435
                conn.rollback()
436

    
437
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
438
                                                               sys.exc_info()[-1].tb_lineno)
439
                App.mainWnd().addMessage.emit(MessageType.Error, message)
440

    
441
        return res
442

    
443
    def get_selected_nd(self, row_id, unit):
444
        res = None
445

    
446
        try:
447
            conn = sqlite3.connect(self.activeDrawing.path)
448
            conn.execute('PRAGMA foreign_keys = ON')
449
            # Get a cursor object
450
            cursor = conn.cursor()
451

    
452
            if unit == 'in':
453
                sql = 'select Inch from NominalDiameter where rowid <= ?'
454
            elif unit == 'mm':
455
                sql = 'select Milimeter from NominalDiameter where rowid <= ?'
456

    
457
            param = (row_id,)
458
            cursor.execute(sql, param)
459
            rows = cursor.fetchall()
460
            for row in rows:
461
                res = row[0]
462
        except Exception as ex:
463
            from App import App
464
            # Roll back any change if something goes wrong
465
            conn.rollback()
466

    
467
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
468
                                                           sys.exc_info()[-1].tb_lineno)
469
            App.mainWnd().addMessage.emit(MessageType.Error, message)
470
        finally:
471
            # Close the db connection
472
            conn.close()
473

    
474
        return res
475

    
476
    def get_row_id(self, size, unit):
477
        res = None
478

    
479
        try:
480
            conn = sqlite3.connect(self.activeDrawing.path)
481
            conn.execute('PRAGMA foreign_keys = ON')
482
            # Get a cursor object
483
            cursor = conn.cursor()
484

    
485
            if unit == 'in':
486
                sql = 'select count(*) from NominalDiameter where Inch <= ?'
487
            elif unit == 'mm':
488
                sql = 'select count(*) from NominalDiameter where Milimeter <= ?'
489

    
490
            param = (size,)
491
            cursor.execute(sql, param)
492
            rows = cursor.fetchall()
493
            for row in rows:
494
                res = row[0]
495
        except Exception as ex:
496
            from App import App
497
            # Roll back any change if something goes wrong
498
            conn.rollback()
499

    
500
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
501
                                                           sys.exc_info()[-1].tb_lineno)
502
            App.mainWnd().addMessage.emit(MessageType.Error, message)
503
        finally:
504
            # Close the db connection
505
            conn.close()
506

    
507
        return res
508

    
509
    def getInsideDiameter(self, nominaldiameter_uid, schedule_uid):
510
        res = []
511
        try:
512
            conn = sqlite3.connect(self.activeDrawing.path)
513
            conn.execute('PRAGMA foreign_keys = ON')
514
            # Get a cursor object
515
            cursor = conn.cursor()
516

    
517
            sql = """select UID
518
                          , Milimeter
519
                          , Inch 
520
                       from InsideDiameter
521
                      where NominalDiameter_UID = ?
522
                        and Schedule_UID = ?"""
523

    
524
            param = (nominaldiameter_uid, schedule_uid)
525
            cursor.execute(sql, param)
526
            rows = cursor.fetchall()
527
            for row in rows:
528
                res.append((row[0], row[1], row[2]))
529
        # Catch the exception
530
        except Exception as ex:
531
            from App import App
532
            # Roll back any change if something goes wrong
533
            conn.rollback()
534

    
535
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
536
                                                           sys.exc_info()[-1].tb_lineno)
537
            App.mainWnd().addMessage.emit(MessageType.Error, message)
538
        finally:
539
            # Close the db connection
540
            conn.close()
541

    
542
        return res
543

    
544
    def getSchedule(self):
545
        res = []
546

    
547
        conn = sqlite3.connect(self.activeDrawing.path)
548
        conn.execute('PRAGMA foreign_keys = ON')
549
        with conn:
550
            try:
551
                # Get a cursor object
552
                cursor = conn.cursor()
553

    
554
                sql = "select UID, No from Schedule"
555
                cursor.execute(sql)
556
                rows = cursor.fetchall()
557
                for row in rows:
558
                    res.append((row[0], row[1]))
559
            # Catch the exception
560
            except Exception as ex:
561
                from App import App
562
                # Roll back any change if something goes wrong
563
                conn.rollback()
564

    
565
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
566
                                                               sys.exc_info()[-1].tb_lineno)
567
                App.mainWnd().addMessage.emit(MessageType.Error, message)
568
        return res
569

    
570
    def getNominalDiameterByUid(self, uid):
571
        res = []
572

    
573
        # Creates or opens a file called mydb with a SQLite3 DB
574
        conn = sqlite3.connect(self.activeDrawing.path)
575
        conn.execute('PRAGMA foreign_keys = ON')
576
        with conn:
577
            try:
578
                # Get a cursor object
579
                cursor = conn.cursor()
580

    
581
                sql = "select UID, Milimeter, Inch, Friction_Factor from NominalDiameter where uid = ?"
582
                param = (uid,)
583
                cursor.execute(sql, param)
584
                rows = cursor.fetchall()
585
                for row in rows:
586
                    res.append((row[0], row[1], row[2], row[3]))
587
            # Catch the exception
588
            except Exception as ex:
589
                from App import App
590

    
591
                # Roll back any change if something goes wrong
592
                conn.rollback()
593

    
594
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
595
                                                               sys.exc_info()[-1].tb_lineno)
596
                App.mainWnd().addMessage.emit(MessageType.Error, message)
597
        return res
598

    
599
    def getNominalDiameter(self):
600
        res = []
601

    
602
        # Creates or opens a file called mydb with a SQLite3 DB
603
        conn = sqlite3.connect(self.activeDrawing.path)
604
        conn.execute('PRAGMA foreign_keys = ON')
605
        with conn:
606
            try:
607
                # Get a cursor object
608
                cursor = conn.cursor()
609

    
610
                sql = "select UID, Milimeter, Inch from NominalDiameter"
611
                cursor.execute(sql)
612
                rows = cursor.fetchall()
613
                for row in rows:
614
                    res.append((row[0], row[1], row[2]))
615
            # Catch the exception
616
            except Exception as ex:
617
                from App import App
618

    
619
                # Roll back any change if something goes wrong
620
                conn.rollback()
621

    
622
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
623
                                                               sys.exc_info()[-1].tb_lineno)
624
                App.mainWnd().addMessage.emit(MessageType.Error, message)
625
        return res
626

    
627
    def getAppDrawing(self, uid):
628
        res = []
629

    
630
        try:
631
            # Creates or opens a file called mydb with a SQLite3 DB
632
            dbPath = self.getAppDbPath()
633
            conn = sqlite3.connect(dbPath)
634
            conn.execute('PRAGMA foreign_keys = ON')
635
            # Get a cursor object
636
            cursor = conn.cursor()
637

    
638
            sql = "select * from Drawings where uid=?"
639
            param = (uid,)
640

    
641
            cursor.execute(sql, param)
642
            rows = cursor.fetchall()
643
            for row in rows:
644
                res.append([row[0], row[1], row[2]])
645
        # Catch the exception
646
        except Exception as ex:
647
            from App import App
648
            # Roll back any change if something goes wrong
649
            conn.rollback()
650

    
651
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
652
                                                           sys.exc_info()[-1].tb_lineno)
653
            App.mainWnd().addMessage.emit(MessageType.Error, message)
654
        finally:
655
            # Close the db connection
656
            conn.close()
657

    
658
        return res
659

    
660
    def getAppConfigs(self, section, key=None):
661
        """
662
            @brief  get application configurations
663
            @author humkyung
664
            @date   2018.11.01
665
        """
666

    
667
        res = []
668

    
669
        try:
670
            # Creates or opens a file called mydb with a SQLite3 DB
671
            dbPath = self.getAppDbPath()
672
            with sqlite3.connect(dbPath) as conn:
673
                conn.execute('PRAGMA foreign_keys = ON')
674
                # Get a cursor object
675
                cursor = conn.cursor()
676

    
677
                if key is not None:
678
                    sql = "select * from configuration where section=? and key=?"
679
                    param = (section, key)
680
                else:
681
                    sql = "select * from configuration where section=?"
682
                    param = (section,)
683

    
684
                cursor.execute(sql, param)
685
                rows = cursor.fetchall()
686
                for row in rows:
687
                    res.append(Config(row[0], row[1], row[2]))
688
        # Catch the exception
689
        except Exception as ex:
690
            from App import App
691
            # Roll back any change if something goes wrong
692
            conn.rollback()
693

    
694
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
695
                                                           sys.exc_info()[-1].tb_lineno)
696
            App.mainWnd().addMessage.emit(MessageType.Error, message)
697
        finally:
698
            # Close the db connection
699
            conn.close()
700

    
701
        return res
702

    
703
    def getConfigs(self, section, key=None):
704
        """
705
            @brief  get application configurations
706
            @author humkyung
707
            @date   2018.11.01
708
        """
709

    
710
        res = []
711

    
712
        try:
713
            # Creates or opens a file called mydb with a SQLite3 DB
714
            conn = sqlite3.connect(self.activeDrawing.path)
715
            conn.execute('PRAGMA foreign_keys = ON')
716
            # Get a cursor object
717
            cursor = conn.cursor()
718

    
719
            if key is not None:
720
                sql = "select Section, Key, Value from configuration where section=? and key=?"
721
                param = (section, key)
722
            else:
723
                sql = "select Section, Key, Value from configuration where section=?"
724
                param = (section,)
725

    
726
            cursor.execute(sql, param)
727
            rows = cursor.fetchall()
728
            for row in rows:
729
                res.append(Config(row[0], row[1], row[2]))
730
        # Catch the exception
731
        except Exception as ex:
732
            from App import App
733

    
734
            # Roll back any change if something goes wrong
735
            conn.rollback()
736

    
737
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
738
                                                           sys.exc_info()[-1].tb_lineno)
739
            App.mainWnd().addMessage.emit(MessageType.Error, message)
740
        finally:
741
            # Close the db connection
742
            conn.close()
743

    
744
        return res
745

    
746
    def saveAppConfigs(self, configs):
747
        """
748
        @brief      save application configurations
749
        @author     humkyung
750
        @date       2018.10.01
751
        """
752

    
753
        try:
754
            # Creates or opens a file called mydb with a SQLite3 DB
755
            dbPath = self.getAppDbPath()
756
            with sqlite3.connect(dbPath) as conn:
757
                conn.execute('PRAGMA foreign_keys = ON')
758
                # Get a cursor object
759
                cursor = conn.cursor()
760

    
761
                for config in configs:
762
                    value = config.value
763
                    if type(value) is str and "'" in value:
764
                        value = value.replace("'", "''")
765

    
766
                    sql = "insert or replace into configuration values(?,?,?)"
767
                    param = (config.section, config.key, value)
768

    
769
                    cursor.execute(sql, param)
770
                conn.commit()
771
        # Catch the exception
772
        except Exception as ex:
773
            from App import App
774
            # Roll back any change if something goes wrong
775
            conn.rollback()
776

    
777
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
778
                                                           sys.exc_info()[-1].tb_lineno)
779
            App.mainWnd().addMessage.emit(MessageType.Error, message)
780

    
781
    def update_roughness(self, roughness):
782
        try:
783
            # Creates or opens a file called mydb with a SQLite3 DB
784
            conn = sqlite3.connect(self.activeDrawing.path)
785
            conn.execute('PRAGMA foreign_keys = ON')
786
            # Get a cursor object
787
            cursor = conn.cursor()
788

    
789
            for r in roughness:
790
                uid = r[0]
791
                material = r[1]
792
                meter = r[2]
793
                inch = r[3]
794
                feet = r[4]
795
                millimeter = r[5]
796

    
797
                sql = """Update Roughness
798
                            Set Material = ?
799
                              , Meter = ?
800
                              , Inch = ?
801
                              , Feet = ?
802
                              , Milimeter = ? 
803
                          Where UID = ?"""
804
                param = (material, meter, inch, feet, millimeter, uid)
805

    
806
                cursor.execute(sql, param)
807
            conn.commit()
808
        except Exception as ex:
809
            from App import App
810
            # Roll back any change if something goes wrong
811
            conn.rollback()
812

    
813
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
814
                                                           sys.exc_info()[-1].tb_lineno)
815
            App.mainWnd().addMessage.emit(MessageType.Error, message)
816
        finally:
817
            # Close the db connection
818
            conn.close()
819

    
820
    def update_fittings(self, fittings):
821
        try:
822
            # Creates or opens a file called mydb with a SQLite3 DB
823
            with sqlite3.connect(self.activeDrawing.path) as conn:
824
                conn.execute('PRAGMA foreign_keys = ON')
825
                # Get a cursor object
826
                cursor = conn.cursor()
827

    
828
                for fitting in fittings:
829
                    uid = fitting[0]
830
                    k = fitting[1]
831

    
832
                    sql = """Update Fittings
833
                                Set K = ?
834
                              Where UID = ?"""
835
                    param = (k, uid)
836

    
837
                    cursor.execute(sql, param)
838

    
839
                sql = "insert or replace into SymbolType(UID,Category,Type) values(?,?,?)"
840
                param = ('8502d693-2e13-422f-b81a-67edf19dc07d', 'Callout', 'Callout')
841
                cursor.execute(sql, param)
842

    
843
                sql = "insert or replace into Symbols(UID,Name,Display_Name,SymbolType_UID,OriginalPoint) " \
844
                      "values(?,?,?,?,?)"
845
                param = ('c288afbb-2612-4b8e-9932-2a84815cfa4e', 'Callout', 'Callout',
846
                         '8502d693-2e13-422f-b81a-67edf19dc07d', '0,0,0,0')
847

    
848
                sql = "insert or replace into Symbols(UID,Name,Display_Name,SymbolType_UID,OriginalPoint) " \
849
                      "values(?,?,?,?,?)"
850
                param = ('22384e9d-74d7-4639-b500-73ac6285ff8a', 'Dimension', 'Dimension',
851
                         '8502d693-2e13-422f-b81a-67edf19dc07d', '0,0,0,0')
852
                cursor.execute(sql, param)
853

    
854
                conn.commit()
855
        except Exception as ex:
856
            from App import App
857
            # Roll back any change if something goes wrong
858
            conn.rollback()
859

    
860
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
861
                                                           sys.exc_info()[-1].tb_lineno)
862
            App.mainWnd().addMessage.emit(MessageType.Error, message)
863

    
864
    def saveConfigs(self, configs):
865
        """
866
        @brief      save application configurations
867
        @author     humkyung
868
        @date       2018.10.01
869
        """
870

    
871
        try:
872
            # Creates or opens a file called mydb with a SQLite3 DB
873
            conn = sqlite3.connect(self.activeDrawing.path)
874
            conn.execute('PRAGMA foreign_keys = ON')
875
            # Get a cursor object
876
            cursor = conn.cursor()
877

    
878
            for config in configs:
879
                value = config.value
880
                if type(value) is str and "'" in value:
881
                    value = value.replace("'", "''")
882

    
883
                sql = "insert or replace into configuration values(?,?,?)"
884
                param = (config.section, config.key, value)
885

    
886
                cursor.execute(sql, param)
887
            conn.commit()
888
        # Catch the exception
889
        except Exception as ex:
890
            from App import App
891
            # Roll back any change if something goes wrong
892
            conn.rollback()
893

    
894
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
895
                                                           sys.exc_info()[-1].tb_lineno)
896
            App.mainWnd().addMessage.emit(MessageType.Error, message)
897
        finally:
898
            # Close the db connection
899
            conn.close()
900

    
901
    def initializeDataByDrawingUID(self, uid):
902
        try:
903
            # Creates or opens a file called mydb with a SQLite3 DB
904
            conn = sqlite3.connect(self.activeDrawing.path)
905
            conn.execute('PRAGMA foreign_keys = ON')
906
            # Get a cursor object
907
            cursor = conn.cursor()
908

    
909
            sql = "delete from Components"
910
            cursor.execute(sql)
911

    
912
            conn.commit()
913
        # Catch the exception
914
        except Exception as ex:
915
            from App import App
916
            # Roll back any change if something goes wrong
917
            conn.rollback()
918
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
919
                                                           sys.exc_info()[-1].tb_lineno)
920
            App.mainWnd().addMessage.emit(MessageType.Error, message)
921
        finally:
922
            # Close the db connection
923
            conn.close()
924

    
925
    def deleteDrawingByName(self, drawingName):
926
        """ delete given drawing """
927
        conn = sqlite3.connect(self.getAppDbPath())
928
        conn.execute('PRAGMA foreign_keys = ON')
929
        with conn:
930
            try:
931
                # Get a cursor object
932
                cursor = conn.cursor()
933

    
934
                sql = 'delete from Drawings where Name=?'
935
                param = (drawingName,)
936
                cursor.execute(sql, param)
937

    
938
                conn.commit()
939
            # Catch the exception
940
            except Exception as ex:
941
                from App import App
942
                # Roll back any change if something goes wrong
943
                conn.rollback()
944

    
945
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
946
                                                               sys.exc_info()[-1].tb_lineno)
947
                App.mainWnd().addMessage.emit(MessageType.Error, message)
948

    
949
    def deleteAppConfigs(self, section, key=None):
950
        """
951
        @brief  delete application configurations
952
        @author humkyung
953
        @date   2018.11.01
954
        """
955

    
956
        try:
957
            # Creates or opens a file called mydb with a SQLite3 DB
958
            dbPath = self.getAppDbPath()
959
            conn = sqlite3.connect(dbPath)
960
            conn.execute('PRAGMA foreign_keys = ON')
961
            # Get a cursor object
962
            cursor = conn.cursor()
963

    
964
            if key is not None:
965
                sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
966
            else:
967
                sql = "delete from configuration where section='{}'".format(section)
968
            cursor.execute(sql)
969

    
970
            conn.commit()
971
        # Catch the exception
972
        except Exception as ex:
973
            from App import App
974

    
975
            # Roll back any change if something goes wrong
976
            conn.rollback()
977

    
978
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
979
                                                           sys.exc_info()[-1].tb_lineno)
980
            App.mainWnd().addMessage.emit(MessageType.Error, message)
981
        finally:
982
            # Close the db connection
983
            conn.close()
984

    
985
    '''
986
        @brief  get symbol name
987
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
988
    '''
989

    
990
    def getSymbolByQuery(self, fieldName, param):
991
        ret = None
992

    
993
        conn = sqlite3.connect(self.activeDrawing.path)
994
        conn.execute('PRAGMA foreign_keys = ON')
995
        with conn:
996
            cursor = conn.cursor()
997

    
998
            sql = """select s.UID
999
                            , s.Name
1000
                            , t.Category
1001
                            , t.Type
1002
                            , s.OriginalPoint
1003
                            , s.ConnectionPoint
1004
                        from Symbols s
1005
                        inner join SymbolType t
1006
                            on s.SymbolType_UID = t.UID 
1007
                        where """ + "s." + fieldName + '=?'
1008

    
1009
            try:
1010
                cursor.execute(sql, (param,))
1011
                rows = cursor.fetchall()
1012
                if rows is not None and len(rows) > 0:
1013
                    symbolTuple = rows[0]
1014
                    ret = symbol.SymbolBase(symbolTuple[0], symbolTuple[1], symbolTuple[2], symbolTuple[3],
1015
                                            symbolTuple[4], symbolTuple[5])
1016
            except Exception as ex:
1017
                from App import App
1018

    
1019
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1020
                                                               sys.exc_info()[-1].tb_lineno)
1021
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1022

    
1023
        return ret
1024

    
1025
    def getSymbolListByUID(self, uid):
1026
        """ get symbol list by given uid """
1027
        ret = []
1028

    
1029
        conn = sqlite3.connect(self.activeDrawing.path)
1030
        conn.execute('PRAGMA foreign_keys = ON')
1031
        with conn:
1032
            cursor = conn.cursor()
1033

    
1034
            sql = """select s.UID
1035
                            , s.Name
1036
                            , t.Category
1037
                            , t.Type
1038
                            , s.OriginalPoint
1039
                            , s.ConnectionPoint
1040
                        from Symbols s
1041
                        inner join SymbolType t
1042
                            on s.SymbolType_UID = t.uid 
1043
                        where s.SymbolType_UID = ?"""
1044

    
1045
            try:
1046
                cursor.execute(sql, (uid,))
1047
                rows = cursor.fetchall()
1048
                if rows is not None and len(rows) > 0:
1049
                    for row in rows:
1050
                        sym = symbol.SymbolBase(row[0], row[1], row[2], row[3], row[4], row[5])
1051

    
1052
                        ret.append(sym)
1053
            except Exception as ex:
1054
                from App import App
1055

    
1056
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1057
                                                               sys.exc_info()[-1].tb_lineno)
1058
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1059

    
1060
        return ret
1061

    
1062
    def get_mixed_pressure_variation(self, uid):
1063
        res = []
1064
        try:
1065
            # Creates or opens a file called mydb with a SQLite3 DB
1066
            dbPath = os.path.join(self.activeDrawing.path)
1067
            conn = sqlite3.connect(dbPath)
1068
            conn.execute('PRAGMA foreign_keys = ON')
1069
            conn.row_factory = sqlite3.Row
1070
            # Get a cursor object
1071
            cursor = conn.cursor()
1072

    
1073
            sql = """select Element
1074
                          , Inside_Pipe_Size
1075
                          , Length
1076
                          , Angle
1077
                          , K
1078
                          , Pressure
1079
                          , Void
1080
                          , Quality
1081
                          , Density
1082
                          , V_Den
1083
                          , Mean_Vel
1084
                          , Max_Vel
1085
                          , Ero_Vel
1086
                          , Pattern_X
1087
                          , Pattern_Y
1088
                          , Regime
1089
                          , Friction
1090
                          , Gravity
1091
                          , Momentum
1092
                          , Total
1093
                       from PressureVariation
1094
                      where Components_UID = ?
1095
                      order by rowid"""
1096

    
1097
            param = (uid,)
1098
            cursor.execute(sql, param)
1099
            rows = cursor.fetchall()
1100
            for row in rows:
1101
                res.append((row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9],
1102
                            row[10], row[11], row[12], row[13], row[14], row[15], row[16], row[17], row[18], row[19]))
1103
        # Catch the exception
1104
        except Exception as ex:
1105
            from App import App
1106

    
1107
            # Roll back any change if something goes wrong
1108
            conn.rollback()
1109

    
1110
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1111
                                                           sys.exc_info()[-1].tb_lineno)
1112
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1113

    
1114
        finally:
1115
            # Close the db connection
1116
            conn.close()
1117

    
1118
        return res
1119

    
1120
    def get_geometry_input(self, uid):
1121
        res = []
1122
        try:
1123
            # Creates or opens a file called mydb with a SQLite3 DB
1124
            dbPath = os.path.join(self.activeDrawing.path)
1125
            conn = sqlite3.connect(dbPath)
1126
            conn.execute('PRAGMA foreign_keys = ON')
1127
            conn.row_factory = sqlite3.Row
1128
            # Get a cursor object
1129
            cursor = conn.cursor()
1130

    
1131
            sql = """select Element
1132
                          , Nominal_Pipe_Size
1133
                          , Schedule_No
1134
                          , Inside_Pipe_Size
1135
                          , Roughness
1136
                          , Length
1137
                          , Angle
1138
                          , RPD
1139
                          , D1_D2
1140
                          , K
1141
                       from Geometry_Input
1142
                      where Components_UID = ?
1143
                      order by rowid"""
1144

    
1145
            param = (uid,)
1146
            cursor.execute(sql, param)
1147
            rows = cursor.fetchall()
1148
            for row in rows:
1149
                res.append((row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9]))
1150
        # Catch the exception
1151
        except Exception as ex:
1152
            from App import App
1153

    
1154
            # Roll back any change if something goes wrong
1155
            conn.rollback()
1156

    
1157
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1158
                                                           sys.exc_info()[-1].tb_lineno)
1159
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1160

    
1161
        finally:
1162
            # Close the db connection
1163
            conn.close()
1164

    
1165
        return res
1166

    
1167
    def get_fittings_input(self, uid):
1168
        res = []
1169
        try:
1170
            # Creates or opens a file called mydb with a SQLite3 DB
1171
            dbPath = os.path.join(self.activeDrawing.path)
1172
            conn = sqlite3.connect(dbPath)
1173
            conn.execute('PRAGMA foreign_keys = ON')
1174
            conn.row_factory = sqlite3.Row
1175
            # Get a cursor object
1176
            cursor = conn.cursor()
1177

    
1178
            sql = """select Fittings_UID
1179
                          , Method
1180
                          , Sub_Size
1181
                          , Angle
1182
                          , Count
1183
                       from Fittings_Input
1184
                      where Components_UID = ?
1185
                      order by rowid"""
1186

    
1187
            param = (uid,)
1188
            cursor.execute(sql, param)
1189
            rows = cursor.fetchall()
1190
            for row in rows:
1191
                res.append((row[0], row[1], row[2], row[3], row[4]))
1192
        # Catch the exception
1193
        except Exception as ex:
1194
            from App import App
1195

    
1196
            # Roll back any change if something goes wrong
1197
            conn.rollback()
1198

    
1199
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1200
                                                           sys.exc_info()[-1].tb_lineno)
1201
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1202

    
1203
        finally:
1204
            # Close the db connection
1205
            conn.close()
1206

    
1207
        return res
1208

    
1209
    def get_fittings_by_uid(self, uid):
1210
        res = None
1211
        try:
1212
            # Creates or opens a file called mydb with a SQLite3 DB
1213
            dbPath = os.path.join(self.activeDrawing.path)
1214
            conn = sqlite3.connect(dbPath)
1215
            conn.execute('PRAGMA foreign_keys = ON')
1216
            conn.row_factory = sqlite3.Row
1217
            # Get a cursor object
1218
            cursor = conn.cursor()
1219

    
1220
            sql = """select UID
1221
                          , Method
1222
                          , Category
1223
                          , Type
1224
                          , Name
1225
                          , K 
1226
                          , Image
1227
                       from Fittings 
1228
                      where UID = ?
1229
                      order by rowid"""
1230

    
1231
            param = (uid,)
1232
            cursor.execute(sql, param)
1233
            rows = cursor.fetchall()
1234
            if rows:
1235
                res = rows[0]
1236
        # Catch the exception
1237
        except Exception as ex:
1238
            from App import App
1239

    
1240
            # Roll back any change if something goes wrong
1241
            conn.rollback()
1242

    
1243
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1244
                                                           sys.exc_info()[-1].tb_lineno)
1245
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1246

    
1247
        finally:
1248
            # Close the db connection
1249
            conn.close()
1250

    
1251
        return res
1252

    
1253
    def get_fittings_by_method(self, method):
1254
        res = []
1255
        try:
1256
            # Creates or opens a file called mydb with a SQLite3 DB
1257
            dbPath = os.path.join(self.activeDrawing.path)
1258
            conn = sqlite3.connect(dbPath)
1259
            conn.execute('PRAGMA foreign_keys = ON')
1260
            conn.row_factory = sqlite3.Row
1261
            # Get a cursor object
1262
            cursor = conn.cursor()
1263

    
1264
            sql = """select UID
1265
                          , Method
1266
                          , Category
1267
                          , Type
1268
                          , Name
1269
                          , K 
1270
                          , Image
1271
                       from Fittings 
1272
                      where Method = ?
1273
                      order by rowid"""
1274

    
1275
            param = (method,)
1276
            cursor.execute(sql, param)
1277
            rows = cursor.fetchall()
1278
            for row in rows:
1279
                res.append((row[0], row[1], row[2], row[3], row[4], row[5], row[6]))
1280
        # Catch the exception
1281
        except Exception as ex:
1282
            from App import App
1283

    
1284
            # Roll back any change if something goes wrong
1285
            conn.rollback()
1286

    
1287
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1288
                                                           sys.exc_info()[-1].tb_lineno)
1289
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1290

    
1291
        finally:
1292
            # Close the db connection
1293
            conn.close()
1294

    
1295
        return res
1296

    
1297
    '''
1298
        @brief      save to database
1299
        @author     yjkim
1300
        @date       2019.08.28
1301
    '''
1302

    
1303
    def saveToDatabase(self, items, show_progress=None):
1304
        """ save given items to database """
1305

    
1306
        queries = []
1307
        for item in items:
1308
            queries.append(item.toSql())
1309

    
1310
        with sqlite3.connect(self.activeDrawing.path, isolation_level=None) as conn:
1311
            conn.execute('PRAGMA foreign_keys = ON')
1312
            try:
1313
                # Get a cursor object
1314
                cursor = conn.cursor()
1315
                cursor.execute('begin')
1316

    
1317
                # delete Components
1318
                sql = 'delete from Components'
1319
                cursor.execute(sql)
1320

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

    
1332
                    if show_progress:
1333
                        show_progress(int((progress / length) * 100))
1334
                    progress += 1
1335

    
1336
                cursor.execute('commit')
1337
            # Catch the exception
1338
            except Exception as ex:
1339
                from App import App
1340
                # Roll back any change if something goes wrong
1341
                conn.rollback()
1342

    
1343
                message = 'error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename,
1344
                                                               sys.exc_info()[-1].tb_lineno)
1345
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1346
            finally:
1347
                if show_progress:
1348
                    show_progress(100)
1349

    
1350
    def getDrawings(self):
1351
        """
1352
        @brief      get drawings
1353
        @author     humkyung
1354
        @date       2018.11.03
1355
        """
1356
        from Drawing import Drawing
1357

    
1358
        res = []
1359
        # Creates or opens a file called mydb with a SQLite3 DB
1360
        dbPath = self.getAppDbPath()
1361
        conn = sqlite3.connect(dbPath)
1362
        conn.execute('PRAGMA foreign_keys = ON')
1363
        with conn:
1364
            try:
1365
                conn.row_factory = sqlite3.Row
1366
                # Get a cursor object
1367
                cursor = conn.cursor()
1368

    
1369
                sql = 'select UID,[NAME],[DATETIME] from Drawings'
1370
                cursor.execute(sql)
1371
                rows = cursor.fetchall()
1372
                for row in rows:
1373
                    if os.path.exists(row[1]):
1374
                        res.append(Drawing(row[0], row[1], row[2]))
1375
            # Catch the exception
1376
            except Exception as ex:
1377
                # Roll back any change if something goes wrong
1378
                conn.rollback()
1379
                from App import App
1380

    
1381
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1382
                                                               sys.exc_info()[-1].tb_lineno)
1383
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1384

    
1385
        return res
1386

    
1387
    '''
1388
        @brief      update drawings
1389
        @author     yeonjin
1390
        @date       2019.08.07
1391
    '''
1392

    
1393
    def updateDrawing(self, drawing):
1394
        import uuid
1395

    
1396
        # Creates or opens a file called mydb with a SQLite3 DB
1397
        dbPath = self.getAppDbPath()
1398
        conn = sqlite3.connect(dbPath)
1399
        conn.execute('PRAGMA foreign_keys = ON')
1400
        with conn:
1401
            try:
1402
                # Get a cursor object
1403
                cursor = conn.cursor()
1404

    
1405
                sql = """update Drawings
1406
                            set Name = ?
1407
                                , DateTime = ?
1408
                            where uid = ?"""
1409
                param = (drawing[0][1], drawing[0][2], drawing[0][0])
1410
                cursor.execute(sql, param)
1411

    
1412
                conn.commit()
1413

    
1414
            # Catch the exception
1415
            except Exception as ex:
1416
                # Roll back any change if something goes wrong
1417
                conn.rollback()
1418
                from App import App
1419

    
1420
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1421
                                                               sys.exc_info()[-1].tb_lineno)
1422
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1423

    
1424
    '''
1425
        @brief      save drawings
1426
        @author     humkyung
1427
        @date       2018.11.03
1428
    '''
1429

    
1430
    def saveDrawing(self, drawing):
1431
        import uuid
1432
        from shutil import copyfile
1433

    
1434
        with sqlite3.connect(self.getAppDbPath()) as conn:
1435
            conn.execute('PRAGMA foreign_keys = ON')
1436
            try:
1437
                # Get a cursor object
1438
                cursor = conn.cursor()
1439

    
1440
                sql = 'insert or replace into Drawings(UID, [NAME], [DATETIME]) values(?, ?, ?)'
1441
                param = (drawing.UID, drawing.path, drawing.date_time)
1442
                cursor.execute(sql, param)
1443

    
1444
                conn.commit()
1445

    
1446
                if not os.path.exists(drawing.path): copyfile(self.getTemplateDbPath(), drawing.path)
1447
            # Catch the exception
1448
            except Exception as ex:
1449
                # Roll back any change if something goes wrong
1450
                conn.rollback()
1451
                from App import App
1452

    
1453
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1454
                                                               sys.exc_info()[-1].tb_lineno)
1455
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1456

    
1457
    '''
1458
        @brief      Return Symbol Category Items
1459
        @author     yeonjin
1460
        @date       19.07.11
1461
    '''
1462

    
1463
    def getSymbolCategoryList(self):
1464
        SymbolCategoryList = []
1465

    
1466
        conn = sqlite3.connect(self.activeDrawing.path)
1467
        conn.execute('PRAGMA foreign_keys = ON')
1468
        with conn:
1469
            cursor = conn.cursor()
1470
            sql = 'SELECT DISTINCT CATEGORY FROM SymbolType ORDER BY type ASC'
1471
            try:
1472
                cursor.execute(sql)
1473
                rows = cursor.fetchall()
1474
                for row in rows:
1475
                    SymbolCategoryList.append((row[0]))  # category
1476
            except Exception as ex:
1477
                from App import App
1478

    
1479
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1480
                                                               sys.exc_info()[-1].tb_lineno)
1481
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1482

    
1483
        return SymbolCategoryList
1484

    
1485
    def getComponentByComponentUID(self, uid):
1486

    
1487
        with sqlite3.connect(self.activeDrawing.path) as conn:
1488
            conn.execute('PRAGMA foreign_keys = ON')
1489
            try:
1490
                conn.row_factory = sqlite3.Row
1491
                cursor = conn.cursor()
1492

    
1493
                sql = """select c.UID as Comp_UID
1494
                                , c.Name
1495
                                , c.[Index] as Comp_Index
1496
                                , c.Symbols_UID
1497
                                , t.Category
1498
                                , t.type
1499
                                , s.Name as Symbol_Name
1500
                                , s.OriginalPoint
1501
                                , c.X as Comp_X
1502
                                , c.Y as Comp_Y
1503
                                , c.Rotation
1504
                                , c.Scale
1505
                                , p.UID as Point_UID
1506
                                , p.[Index]
1507
                                , p.X
1508
                                , p.Y
1509
                                , p.ConnectedItem_UID
1510
                            from points p
1511
                            left join components c
1512
                                on p.components_uid = c.uid
1513
                            left join symbols s
1514
                                on c.Symbols_UID = s.UID    
1515
                            left join SymbolType t
1516
                                on s.symboltype_uid = t.uid
1517
                            where c.uid = ?
1518
                            order by p.[Index]"""
1519
                param = (uid,)
1520
                cursor.execute(sql, param)
1521
                return cursor.fetchall()
1522
            except Exception as ex:
1523
                from App import App
1524

    
1525
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1526
                                                               sys.exc_info()[-1].tb_lineno)
1527
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1528

    
1529
        return None
1530

    
1531
    def get_nozzle_data(self, uid):
1532
        """ get nozzle data of given uid """
1533
        from EngineeringConnectorItem import NozzleData
1534

    
1535
        res = None
1536
        with sqlite3.connect(self.activeDrawing.path) as conn:
1537
            conn.execute('PRAGMA foreign_keys = ON')
1538
            conn.row_factory = sqlite3.Row
1539
            cursor = conn.cursor()
1540
            sql = 'select Pressure, Pressure_Drop, Elevation, Over_Design_CV, CV_Type, ' \
1541
                  'B.Name, B.X, B.Y from Nozzles A ' \
1542
                  'left join Components B on A.Points_UID=B.UID where Points_UID=?'
1543
            param = (uid,)
1544
            cursor.execute(sql, param)
1545
            rows = cursor.fetchall()
1546
            if rows:
1547
                res = NozzleData()
1548
                res.parse(rows[0])
1549

    
1550
        return res
1551

    
1552
    '''
1553
        @brief      Return Components By DrawingUID
1554
        @author     yeonjin
1555
        @date       19.07.29
1556
    '''
1557

    
1558
    def getComponentListByDrawingUID(self):
1559
        ComponentList = []
1560

    
1561
        with sqlite3.connect(self.activeDrawing.path) as conn:
1562
            conn.execute('PRAGMA foreign_keys = ON')
1563
            try:
1564
                conn.row_factory = sqlite3.Row
1565
                cursor = conn.cursor()
1566
                sql = 'select UID from Components order by x desc'
1567
                cursor.execute(sql)
1568
                rows = cursor.fetchall()
1569
                for row in rows:
1570
                    ComponentList.append((row[0]))  # Components_UID
1571
            except Exception as ex:
1572
                from App import App
1573

    
1574
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1575
                                                               sys.exc_info()[-1].tb_lineno)
1576
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1577

    
1578
        return ComponentList
1579

    
1580
    '''
1581
        @brief      Return Symbol Type Items By Category
1582
        @author     yeonjin
1583
        @date       19.07.11
1584
    '''
1585

    
1586
    def getSymbolTypeListByCategory(self, category):
1587
        symbolTypeList = []
1588

    
1589
        conn = sqlite3.connect(self.activeDrawing.path)
1590
        conn.execute('PRAGMA foreign_keys = ON')
1591
        with conn:
1592
            cursor = conn.cursor()
1593
            sql = 'SELECT UID, Category, Type FROM SymbolType WHERE Category = "' + category + '"'
1594
            try:
1595
                cursor.execute(sql)
1596
                rows = cursor.fetchall()
1597
                for row in rows:
1598
                    symbolTypeList.append((row[0], row[1], row[2]))  # UID, Category, Type
1599
            except Exception as ex:
1600
                from App import App
1601

    
1602
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1603
                                                               sys.exc_info()[-1].tb_lineno)
1604
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1605

    
1606
        return symbolTypeList
1607

    
1608
    def get_sheet_history(self):
1609
        """get sheet history from database"""
1610

    
1611
        with sqlite3.connect(self.activeDrawing.path) as conn:
1612
            conn.row_factory = sqlite3.Row
1613
            conn.execute('PRAGMA foreign_keys = ON')
1614
            cursor = conn.cursor()
1615
            sql = 'Select UID, Activity, Date, User, IP From SheetHistory Order by Date Desc'
1616
            try:
1617
                cursor.execute(sql)
1618
                rows = cursor.fetchall()
1619
                return rows
1620
            except Exception as ex:
1621
                from App import App
1622

    
1623
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1624
                                                               sys.exc_info()[-1].tb_lineno)
1625
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1626

    
1627
        return None
1628

    
1629
    def save_sheet_history(self, activity):
1630
        """save sheet history data to database"""
1631
        from datetime import datetime
1632

    
1633
        configs = self.getAppConfigs('app', 'SingleID')
1634
        user_name = configs[0].value
1635
        configs = self.getAppConfigs('app', 'IP')
1636
        IP = configs[0].value
1637

    
1638
        with sqlite3.connect(self.activeDrawing.path) as conn:
1639
            try:
1640
                conn.row_factory = sqlite3.Row
1641
                conn.execute('PRAGMA foreign_keys = ON')
1642
                cursor = conn.cursor()
1643
                sql = 'insert into SheetHistory(Activity, Date, User, IP) values(?,?,?,?)'
1644
                param = (activity, datetime.now().strftime("%Y-%m-%d %H:%M:%S"), user_name, IP)
1645
                cursor.execute(sql, param)
1646
                conn.commit()
1647
            except Exception as ex:
1648
                from App import App
1649

    
1650
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1651
                                                               sys.exc_info()[-1].tb_lineno)
1652
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1653

    
1654
    def getUnits(self):
1655
        unitsList = []
1656

    
1657
        try:
1658
            conn = sqlite3.connect(self.activeDrawing.path)
1659
            conn.execute('PRAGMA foreign_keys = ON')
1660
            cursor = conn.cursor()
1661
            sql = 'Select UID, Key, Value From Units'
1662
            try:
1663
                cursor.execute(sql)
1664
                rows = cursor.fetchall()
1665
                for row in rows:
1666
                    unitsList.append((row[0], row[1], row[2]))  # UID, Key, Value
1667
            except Exception as ex:
1668
                from App import App
1669

    
1670
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1671
                                                               sys.exc_info()[-1].tb_lineno)
1672
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1673
        finally:
1674
            conn.close()
1675

    
1676
        return unitsList
1677

    
1678
    def getHMBDisplayNameAndUnitsExpression(self):
1679
        res = []
1680

    
1681
        if self.activeDrawing:
1682
            conn = sqlite3.connect(self.activeDrawing.path)
1683
            conn.execute('PRAGMA foreign_keys = ON')
1684
            with conn:
1685
                cursor = conn.cursor()
1686
                sql = """SELECT dn.DISPLAY_NAME
1687
                                , hu.Units_Expression
1688
                            FROM DisplayNames dn
1689
                            left join HMBUnits hu
1690
                                on dn.COLUMN_NAME = Hu.Column_Name
1691
                            where dn.Table_Name = 'HMB'
1692
                            order by dn.[Order]"""
1693
                try:
1694
                    cursor.execute(sql)
1695
                    rows = cursor.fetchall()
1696
                    for row in rows:
1697
                        res.append((row[0], row[1]))
1698
                except Exception as ex:
1699
                    from App import App
1700

    
1701
                    message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1702
                                                                   sys.exc_info()[-1].tb_lineno)
1703
                    App.mainWnd().addMessage.emit(MessageType.Error, message)
1704

    
1705
        return res
1706

    
1707
    '''
1708
        @brief      Get Symbol Category by Symbol Type
1709
        @author     Jeongwoo
1710
        @date       2018.05.09
1711
    '''
1712

    
1713
    def getSymbolCategoryByType(self, type):
1714
        category = None
1715

    
1716
        conn = sqlite3.connect(self.activeDrawing.path)
1717
        conn.execute('PRAGMA foreign_keys = ON')
1718
        with conn:
1719
            try:
1720
                cursor = conn.cursor()
1721
                sql = 'SELECT Category FROM SymbolType WHERE type = "' + type + '"'
1722
                cursor.execute(sql)
1723
                rows = cursor.fetchall()
1724
                if rows is not None and len(rows) > 0:
1725
                    category = rows[0][0]
1726
            except Exception as ex:
1727
                from App import App
1728

    
1729
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1730
                                                               sys.exc_info()[-1].tb_lineno)
1731
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1732

    
1733
        return category
1734

    
1735
    '''
1736
        @brief  getter of activeDrawing
1737
        @author humkyung
1738
        @date   2018.07.07
1739
    '''
1740

    
1741
    @property
1742
    def activeDrawing(self):
1743
        return self._activeDrawing
1744

    
1745
    '''
1746
        @brief  setter of activeDrawing
1747
        @author humkyung
1748
        @date   2018.07.07
1749
    '''
1750

    
1751
    @activeDrawing.setter
1752
    def activeDrawing(self, value):
1753
        self._activeDrawing = value
클립보드 이미지 추가 (최대 크기: 500 MB)