프로젝트

일반

사용자정보

개정판 a6a2273e

IDa6a2273e098206cdc0bfed59fd19d5ef09e65870
상위 bee1327f
하위 2b9f1680, 19bf814f

백흠경이(가) 5년 이상 전에 추가함

issue #1196: 최근에 작업한 도면 리스트를 보여준다

Change-Id: I4ffc680d72c1c7c0293a7a40444bbd578de393c3

차이점 보기:

HYTOS/HYTOS/AppDocData.py
152 152
        self._titleBlockProperties = None
153 153

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

  
171
        return drawingFileList
172

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

  
189
        return drawingFileList
190

  
191
    '''
192 155
        @brief      Get DB file path in ProgramData
193 156
        @author     Jeongwoo
194 157
        @date       2018.06.27
......
491 454

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

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

  
518
        configs = [Config('app', 'mode', 'advanced'), Config('app', 'error origin point', '51,72')]
519
        self.saveAppConfigs(configs)
520 478

  
521 479
    '''
522 480
        @brief  load app style
......
593 551
    '''
594 552
    def setCurrentProject(self, project):
595 553
        self.project = project
596
        self.makeChildDir()
597
        self.copySvg()
598 554
        try:
599 555
            # Creates or opens a file called mydb with a SQLite3 DB
600 556
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath() , App.NAME + '.db')
......
632 588
        finally:
633 589
            pass
634 590

  
635
    '''
636
        @brief      Copy Svg
637
        @author     yeonjin
638
        @date       19.07.31
639
    '''
640
    def copySvg(self):
641
        from shutil import copyfile
591

  
592
    @property
593
    def border_file_path(self):
594
        """ return border file path """
642 595

  
643 596
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
644
        sourceDir = os.path.join(path, 'svg')
645
        if not os.path.exists(sourceDir): 
646
            return
647
        
648
        project = AppDocData.instance().getCurrentProject()
649
        targetDir = project.getSvgFilePath()
597
        return os.path.join(path, 'Border.png')
650 598

  
651
        for root, dirs, files in os.walk(sourceDir):
652
            for file in files: # loops through directories and files
653
                sourceFile = os.path.join(root, file)
654
                targetFile = sourceFile.replace(sourceDir, targetDir)
655
                if not os.path.exists(targetFile):
656
                    dir = os.path.dirname(targetFile)
657
                    if not os.path.exists(dir):
658
                        os.makedirs(dir)
599
    @property
600
    def symbol_file_path(self):
601
        """ return svg symbol file path """
659 602

  
660
                    copyfile(sourceFile, targetFile)
603
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
604
        return os.path.join(path, 'svg')
661 605

  
662 606
    '''
663
        @brief      Make Directory
664
        @author     Jeongwoo
665
        @date       18.05.08
666
        @history    humkyung 2018.06.19 make 'Tile' directory
667
                    humkyung 2018.07.09 make drawing folder if not exists
668
                    euisung 2018.09.28 make training folder if not exists
669
    '''
670
    def makeChildDir(self):
671
        project = AppDocData.instance().getCurrentProject()
672
        dbDir = project.getDbFilePath()
673
        if not os.path.exists(dbDir):
674
            os.makedirs(dbDir)
675
        imgDir = project.getImageFilePath()
676
        if not os.path.exists(imgDir):
677
            os.makedirs(imgDir)
678
        svgDir = project.getSvgFilePath()
679
        if not os.path.exists(svgDir):
680
            os.makedirs(svgDir)
681
        outputDir = project.getOutputPath()
682
        if not os.path.exists(outputDir):
683
            os.makedirs(outputDir)
684
        tempDir = project.getTempPath()
685
        if not os.path.exists(tempDir):
686
            os.makedirs(tempDir)
687
        drawingPath = project.getDrawingFilePath()
688
        if not os.path.exists(drawingPath):
689
            os.makedirs(drawingPath)
690
        trainingPath = project.getTrainingFilePath()
691
        if not os.path.exists(trainingPath):
692
            os.makedirs(trainingPath)
693
        
694
        path = os.path.join(tempDir, 'Tile')
695
        if not os.path.exists(path):
696
            os.makedirs(path)
697
        borderDir = project.getBorderFilePath()    
698
        if not os.path.exists(borderDir):
699
            os.makedirs(borderDir)
700
    '''
701 607
        @brief  Get current Project
702 608
    '''
703 609
    def getCurrentProject(self):
......
1500 1406
            # Close the db connection
1501 1407
            conn.close()
1502 1408

  
1503
    def deleteDrawingByUID(self, uid):
1504
        try:
1505
            # Creates or opens a file called mydb with a SQLite3 DB
1506
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1507
            conn = sqlite3.connect(dbPath)
1508
            # Get a cursor object
1509
            cursor = conn.cursor()
1510

  
1511
            # 0. Delete Points
1512
            sql = "delete from Points where Components_UID in (select UID from Components where Drawings_UID = '{}')".format(uid)
1513
            cursor.execute(sql)
1514

  
1515
            # 1. Delete HMB
1516
            sql = "delete from HMB where Components_UID in (select UID from Components where Drawings_UID = '{}')".format(uid)
1517
            cursor.execute(sql)
1409
    def deleteDrawingByUID(self, drawing):
1410
        """ delete given drawing """
1411
        conn = sqlite3.connect(self.getAppDbPath())
1412
        with conn:
1413
            try:
1414
                # Get a cursor object
1415
                cursor = conn.cursor()
1518 1416

  
1519
            # 2. Delete Components
1520
            sql = "delete from Components where Drawings_UID='{}'".format(uid)
1521
            cursor.execute(sql)
1522
            # 3. Delete DrawingsUnits
1523
            sql = "delete from DrawingsUnits where Drawings_UID='{}'".format(uid)
1524
            cursor.execute(sql)
1525
            
1526
            # 4. Delete Drawings
1527
            sql = "delete from Drawings where UID='{}'".format(uid)
1528
            cursor.execute(sql)
1529
            
1530
            conn.commit()
1531
        # Catch the exception
1532
        except Exception as ex:
1533
            # Roll back any change if something goes wrong
1534
            conn.rollback()
1535
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1536
        finally:
1537
            # Close the db connection
1538
            conn.close()
1417
                sql = 'delete from Drawings where UID=?'
1418
                param = (drawing.UID,)
1419
                cursor.execute(sql, param)
1420
                
1421
                conn.commit()
1422
            # Catch the exception
1423
            except Exception as ex:
1424
                # Roll back any change if something goes wrong
1425
                conn.rollback()
1426
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1539 1427

  
1540 1428
    '''
1541 1429
        @brief  delete configurations
......
2941 2829
    '''
2942 2830
    def saveToDatabase(self, item, index):
2943 2831
        """ save given items to database """
2944
        try:
2945
            # Creates or opens a file called mydb with a SQLite3 DB
2946
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2947
            conn = sqlite3.connect(dbPath, isolation_level=None)
2948
            # Get a cursor object
2949
            cursor = conn.cursor()
2950

  
2951
            uid = self.activeDrawing.UID
2832
        conn = sqlite3.connect(self.activeDrawing.path, isolation_level=None)
2833
        with conn:
2834
            try:
2835
                # Get a cursor object
2836
                cursor = conn.cursor()
2952 2837

  
2953
            if index == 0:
2954
                # delete Points
2955
                sql = "delete from Points where Components_UID in (select UID from Components where Drawings_UID = '{}')".format(uid)
2956
                cursor.execute(sql)
2838
                if index == 0:
2839
                    # delete Points
2840
                    sql = 'delete from Points'
2841
                    cursor.execute(sql)
2957 2842

  
2958
                # delete HMB
2959
                sql = "delete from HMB where Components_UID in (select UID from Components where Drawings_UID = '{}')".format(uid)
2960
                cursor.execute(sql)
2843
                    # delete HMB
2844
                    sql = 'delete from HMB'
2845
                    cursor.execute(sql)
2961 2846

  
2962
                # delete Components 
2963
                sql = "delete from Components where Drawings_UID = '{}'".format(uid)
2964
                cursor.execute(sql)
2965
            
2966
            sql = item.toSql()
2967
            if type(sql) is list:
2968
                for item in sql:
2969
                    if item is not None and 2 == len(item):
2970
                        cursor.execute(item[0], item[1])
2971
            else:
2972
                if sql is not None and 2 == len(sql):
2973
                    cursor.execute(sql[0], sql[1])
2847
                    # delete Components 
2848
                    sql = 'delete from Components'
2849
                    cursor.execute(sql)
2850
                
2851
                sql = item.toSql()
2852
                if type(sql) is list:
2853
                    for item in sql:
2854
                        if item is not None and 2 == len(item):
2855
                            cursor.execute(item[0], item[1])
2856
                else:
2857
                    if sql is not None and 2 == len(sql):
2858
                        cursor.execute(sql[0], sql[1])
2974 2859

  
2975
            conn.commit()
2976
        # Catch the exception
2977
        except Exception as ex:
2978
            from App import App
2979
            # Roll back any change if something goes wrong
2980
            conn.rollback()
2860
                conn.commit()
2861
            # Catch the exception
2862
            except Exception as ex:
2863
                from App import App
2864
                # Roll back any change if something goes wrong
2865
                conn.rollback()
2981 2866

  
2982
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2983
            print(message)
2984
            print(sql)
2985
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2986
        finally:
2987
            # Close the db connection
2988
            conn.close()
2867
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2868
                print(message)
2869
                print(sql)
2870
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2989 2871

  
2990 2872
    '''
2991 2873
        @brief      set equipment data list
......
3052 2934
        @author     humkyung
3053 2935
        @date       2018.11.03
3054 2936
        """
2937
        from Drawing import Drawing
3055 2938

  
3056 2939
        res = []
3057
        try:
3058
            # Creates or opens a file called mydb with a SQLite3 DB
3059
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3060
            conn = sqlite3.connect(dbPath)
3061
            # Get a cursor object
3062
            cursor = conn.cursor()
3063

  
3064
            sql = 'select UID,[NAME],[DATETIME] from Drawings'
3065
            cursor.execute(sql)
3066
            rows = cursor.fetchall()
3067
            for row in rows:
3068
                res.append([row[0], row[1], row[2]])
2940
        # Creates or opens a file called mydb with a SQLite3 DB
2941
        dbPath = self.getAppDbPath()
2942
        conn = sqlite3.connect(dbPath)
2943
        with conn:
2944
            try:
2945
                conn.row_factory = sqlite3.Row
2946
                # Get a cursor object
2947
                cursor = conn.cursor()
3069 2948

  
3070
        # Catch the exception
3071
        except Exception as ex:
3072
            # Roll back any change if something goes wrong
3073
            conn.rollback()
3074
            from App import App
2949
                sql = 'select UID,[NAME],[DATETIME] from Drawings'
2950
                cursor.execute(sql)
2951
                rows = cursor.fetchall()
2952
                for row in rows:
2953
                    res.append(Drawing(row[0], row[1], row[2]))
2954
            # Catch the exception
2955
            except Exception as ex:
2956
                # Roll back any change if something goes wrong
2957
                conn.rollback()
2958
                from App import App
3075 2959

  
3076
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3077
            App.mainWnd().addMessage.emit(MessageType.Error, message)
3078
        finally:
3079
            # Close the db connection
3080
            conn.close()
2960
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2961
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3081 2962

  
3082 2963
        return res
3083 2964

  
......
3089 2970
    def updateDrawing(self, drawing):
3090 2971
        import uuid
3091 2972
        
3092
        try:
3093
            # Creates or opens a file called mydb with a SQLite3 DB
3094
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3095
            conn = sqlite3.connect(dbPath)
3096
            # Get a cursor object
3097
            cursor = conn.cursor()
3098
              
3099
            sql = """update Drawings
3100
                        set Name = ?
3101
                          , DateTime = ?
3102
                      where uid = ?"""
3103
            param = (drawing[0][1], drawing[0][2], drawing[0][0])
3104
            cursor.execute(sql, param)
2973
        # Creates or opens a file called mydb with a SQLite3 DB
2974
        dbPath = self.getAppDbPath()
2975
        conn = sqlite3.connect(dbPath)
2976
        with conn:
2977
            try:
2978
                # Get a cursor object
2979
                cursor = conn.cursor()
2980
                    
2981
                sql = """update Drawings
2982
                            set Name = ?
2983
                                , DateTime = ?
2984
                            where uid = ?"""
2985
                param = (drawing[0][1], drawing[0][2], drawing[0][0])
2986
                cursor.execute(sql, param)
3105 2987

  
3106
            conn.commit()
2988
                conn.commit()
3107 2989

  
3108
        # Catch the exception
3109
        except Exception as ex:
3110
            # Roll back any change if something goes wrong
3111
            conn.rollback()
3112
            from App import App
2990
            # Catch the exception
2991
            except Exception as ex:
2992
                # Roll back any change if something goes wrong
2993
                conn.rollback()
2994
                from App import App
2995

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

  
3114
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3115
            App.mainWnd().addMessage.emit(MessageType.Error, message)
3116
        finally:
3117
            # Close the db connection
3118
            conn.close()
3119 2999
    '''
3120 3000
        @brief      save drawings
3121 3001
        @author     humkyung
......
3123 3003
    '''
3124 3004
    def saveDrawing(self, drawing):
3125 3005
        import uuid
3126
        
3127
        try:
3128
            # Creates or opens a file called mydb with a SQLite3 DB
3129
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3130
            conn = sqlite3.connect(dbPath)
3131
            # Get a cursor object
3132
            cursor = conn.cursor()
3133
              
3134
            sql = 'insert or replace into Drawings(UID, [NAME], [DATETIME]) values(?, ?, ?)'
3135
            param = (drawing[0][0], drawing[0][1], drawing[0][2])
3136
            cursor.execute(sql, param)
3006
        from shutil import copyfile       
3137 3007

  
3138
            sql = "select Units, Units_UID from DrawingsUnits where drawings_UID = '00000000-0000-0000-0000-000000000000'"
3139
            cursor.execute(sql)
3140
            rows = cursor.fetchall()
3141
            for row in rows:
3142
                sql = """insert or replace into DrawingsUnits
3143
                            (
3144
                                UID
3145
                                , Drawings_UID
3146
                                , Units
3147
                                , Units_UID
3148
                             )
3149
                             values 
3150
                             (
3151
                                ?
3152
                                , ?
3153
                                , ?
3154
                                , ?
3155
                             )"""
3156
                param = (str(uuid.uuid4()), drawing[0][0], row[0], row[1])
3008
        conn = sqlite3.connect(self.getAppDbPath())
3009
        with conn:
3010
            try:
3011
                # Get a cursor object
3012
                cursor = conn.cursor()
3013
                    
3014
                sql = 'insert or replace into Drawings(UID, [NAME], [DATETIME]) values(?, ?, ?)'
3015
                param = (drawing.UID, drawing.path, drawing.date_time)
3157 3016
                cursor.execute(sql, param)
3158 3017

  
3159
            conn.commit()
3160

  
3161
        # Catch the exception
3162
        except Exception as ex:
3163
            # Roll back any change if something goes wrong
3164
            conn.rollback()
3165
            from App import App
3166

  
3167
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3168
            App.mainWnd().addMessage.emit(MessageType.Error, message)
3169
        finally:
3170
            # Close the db connection
3171
            conn.close()
3018
                conn.commit()
3172 3019

  
3173
    '''
3174
        @brief  get IsOriginDetect ComboBox Items
3175
    '''
3176
    def getIsOriginDetectComboBoxItems(self):
3177
        return [("원본 도면", 0), ("텍스트 제거 도면", 1)]
3020
                if not os.path.exists(drawing.path): copyfile(self.getTemplateDbPath(), drawing.path)
3021
            # Catch the exception
3022
            except Exception as ex:
3023
                # Roll back any change if something goes wrong
3024
                conn.rollback()
3025
                from App import App
3178 3026

  
3179
    '''
3180
        @brief  get IsOriginDetect ComboBox Items
3181
    '''
3182
    def getOcrOptionComboBoxItems(self):
3183
        return [("OCR 미적용", 0), ("일반 심볼", 1), ("Instrument 계통", 2)]
3184
    
3027
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3028
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3185 3029

  
3186 3030
    '''
3187 3031
        @brief      Return Symbol Category Items
......
3216 3060
    def getComponentByComponentUID(self, uid):
3217 3061
        ComponentList = []
3218 3062

  
3219
        try:
3220
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3221

  
3222
            conn = sqlite3.connect(dbPath)
3223
            cursor = conn.cursor()
3224
            
3225
            sql = """select c.uid
3226
                          , c.Name
3227
                          , c.Symbols_UID
3228
                          , t.Category
3229
                          , t.type
3230
                          , s.Name
3231
                          , s.OriginalPoint
3232
                          , c.X
3233
                          , c.Y
3234
                          , c.Rotation
3235
                          , c.Scale
3236
                          , p.uid
3237
                          , p.[Index]
3238
                          , p.x
3239
                          , p.y
3240
                          , p.ConnectedItem_UID
3241
                       from points p
3242
                       left join components c
3243
                         on p.components_uid = c.uid
3244
                       left join symbols s
3245
                         on c.Symbols_UID = s.UID    
3246
                       left join SymbolType t
3247
                         on s.symboltype_uid = t.uid
3248
                      where c.uid = ?
3249
                      order by p.[Index]"""
3250
            param = (uid,)                      
3063
        conn = sqlite3.connect(self.activeDrawing.path)
3064
        with conn:
3251 3065
            try:
3066
                conn.row_factory = sqlite3.Row
3067
                cursor = conn.cursor()
3068
                
3069
                sql = """select c.uid
3070
                                , c.Name
3071
                                , c.Symbols_UID
3072
                                , t.Category
3073
                                , t.type
3074
                                , s.Name
3075
                                , s.OriginalPoint
3076
                                , c.X
3077
                                , c.Y
3078
                                , c.Rotation
3079
                                , c.Scale
3080
                                , p.uid
3081
                                , p.[Index]
3082
                                , p.x
3083
                                , p.y
3084
                                , p.ConnectedItem_UID
3085
                            from points p
3086
                            left join components c
3087
                                on p.components_uid = c.uid
3088
                            left join symbols s
3089
                                on c.Symbols_UID = s.UID    
3090
                            left join SymbolType t
3091
                                on s.symboltype_uid = t.uid
3092
                            where c.uid = ?
3093
                            order by p.[Index]"""
3094
                param = (uid,)                      
3252 3095
                cursor.execute(sql, param)
3253 3096
                rows = cursor.fetchall()
3254 3097
                for row in rows:
......
3261 3104

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

  
3267 3108
        return ComponentList
3268 3109

  
......
3330 3171
        @author     yeonjin
3331 3172
        @date       19.07.29
3332 3173
    '''
3333
    def getComponentListByDrawingUID(self, uid):
3174
    def getComponentListByDrawingUID(self, drawing):
3334 3175
        ComponentList = []
3335 3176

  
3336
        try:
3337
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3338

  
3339
            conn = sqlite3.connect(dbPath)
3340
            cursor = conn.cursor()
3341
            sql = 'select UID from Components where Drawings_UID = ? order by x desc'
3177
        conn = sqlite3.connect(drawing.path)
3178
        with conn:
3342 3179
            try:
3343
                param = (uid, )
3344
                cursor.execute(sql, param)
3180
                conn.row_factory = sqlite3.Row
3181
                cursor = conn.cursor()
3182
                sql = 'select UID from Components order by x desc'
3183
                cursor.execute(sql)
3345 3184
                rows = cursor.fetchall()
3346 3185
                for row in rows:
3347 3186
                    ComponentList.append((row[0])) # Components_UID
......
3350 3189

  
3351 3190
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3352 3191
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3353
        finally:
3354
            conn.close()
3355 3192

  
3356 3193
        return ComponentList
3357 3194

  
HYTOS/HYTOS/Drawing.py
9 9
        @author humkyung
10 10
        @date   2018.07.07
11 11
    '''
12
    def __init__(self, name):
12
    def __init__(self, UID, path, date_time):
13 13
        app_doc_data = AppDocData.instance()
14 14

  
15
        self.name = name
16 15
        self._attrs = [['Drawing No', ''], ['Rev No', ''], ['Units', '']] # attributes
17 16

  
18
        ''' set drawing uid '''
19
        drawings = app_doc_data.getDrawings()
20
        drawing = [drawing for drawing in drawings if self.name == os.path.splitext(drawing[1])[0]]
21
        self.UID = drawing[0][0] if drawing else uuid.uuid4()
22
        ''' up to here '''
17
        self.UID = UID
18
        self.path = path
19
        self.name = os.path.splitext(os.path.split(path)[1])[0]
20
        self.date_time = date_time
23 21

  
24 22
        self.allItems = []
25 23
        self._hmbTable = None
HYTOS/HYTOS/DrawingDialog.py
11 11
import Drawing_UI
12 12

  
13 13
class QDrawingDialog(QDialog):    
14
    """ This is drawing dialog """
14 15
    def __init__(self, uid = None):        
15 16
        QDialog.__init__(self, uid)
16 17
        #_translate = QtCore.QCoreApplication.translate
......
20 21
        self.ui = Drawing_UI.Ui_DrawingDialog()
21 22
        self.ui.setupUi(self)    
22 23
        self.ui.lineEditName.setFocus()
23
        #self.setWindowTitle(_translate('New Drawing Dialog', 'New Drawing'))
24 24
        
25 25
    def showDialog(self, uid=None):
26 26
        _translate = QtCore.QCoreApplication.translate
......
85 85
        from App import App
86 86
        app = App(sys.argv)
87 87

  
88

  
89 88
        if True:
90 89
            dlg = QDrawingDialog()
91 90
            dlg.exec_()
HYTOS/HYTOS/HMBTable.py
510 510
        if self._hmbs is None:
511 511
            return
512 512

  
513
        try:
514
            appDocData = AppDocData.instance()
515
            # Creates or opens a file called mydb with a SQLite3 DB
516
            dbPath = os.path.join(appDocData.getCurrentProject().getDbFilePath(), App.NAME + '.db')
517
            conn = sqlite3.connect(dbPath)
518
            # Get a cursor object
519
            cursor = conn.cursor()
520

  
521
            for data in self._hmbs:
522
                if data.isDeleted == False:
523
                    cols = ['UID', 'Components_UID', 'Stream_No', 'Phase_Type', 'Flowrate_Mass', 'Flowrate_Volume', 'Density', 'Viscosity',
524
                            'Temperature', 'Molecular_Weight', 'Specific_Heat_Ratio', 'Compress_Factor', 'Nominal_Pipe_Size', 'Inside_Pipe_Size',
525
                            'Schedule_No', 'Straight_Length', 'Equivalent_Length', 'Roughness', 'Limitation_Velocity', 'Limitation_Pressure_Drop',
526
                            'Velocity', 'Reynolds', 'Friction_Factor', 'Pressure_Drop', 'Pressure_Drop_Friction', 'Pressure_Drop_Static', 'Pressure_Pipe_End_Point', 'Power']
527
                    values = ['?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?']
528
                    param = (str(data.uid), str(data.components_uid), data.stream_no, data.phase_type, data.flowrate_mass, data.flowrate_volume, data.density,
529
                             data.viscosity, data.temperature, data.molecular_weight, data.specific_heat_ratio, data.compress_factor, data.nominal_pipe_size,
530
                             data.inside_pipe_size, data.schedule_no, data.straight_length, data.equivalent_length, data.roughness, data.limitation_velocity,
531
                             data.limitation_pressure_drop, data.velocity, data.reynolds, data.friction_factor, data.pressure_drop, data.pressure_drop_friction,
532
                             data.pressure_drop_static, data.pressure_pipe_end_point, data.power)
533

  
534
                    sql = 'insert or replace into HMB({}) values({})'.format(','.join(cols), ','.join(values))                  
535
                    cursor.execute(sql, param)
536
                else:
537
                    sql = "delete from HMB where uid=?"
538
                    param = (data.uid,)
539
                    cursor.execute(sql, param)
540

  
541
            conn.commit()
542
        # Catch the exception
543
        except Exception as ex:
544
            # Roll back any change if something goes wrong
545
            conn.rollback()
546
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
547
        finally:
548
            # Close the db connection
549
            conn.close()
513
        app_doc_data = AppDocData.instance()
514
        conn = sqlite3.connect(app_doc_data.activeDrawing.path)
515
        with conn:
516
            try:
517
                # Get a cursor object
518
                cursor = conn.cursor()
519

  
520
                for data in self._hmbs:
521
                    if data.isDeleted == False:
522
                        cols = ['UID', 'Components_UID', 'Stream_No', 'Phase_Type', 'Flowrate_Mass', 'Flowrate_Volume', 'Density', 'Viscosity',
523
                                'Temperature', 'Molecular_Weight', 'Specific_Heat_Ratio', 'Compress_Factor', 'Nominal_Pipe_Size', 'Inside_Pipe_Size',
524
                                'Schedule_No', 'Straight_Length', 'Equivalent_Length', 'Roughness', 'Limitation_Velocity', 'Limitation_Pressure_Drop',
525
                                'Velocity', 'Reynolds', 'Friction_Factor', 'Pressure_Drop', 'Pressure_Drop_Friction', 'Pressure_Drop_Static', 'Pressure_Pipe_End_Point', 'Power']
526
                        values = ['?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?']
527
                        param = (str(data.uid), str(data.components_uid), data.stream_no, data.phase_type, data.flowrate_mass, data.flowrate_volume, data.density,
528
                                    data.viscosity, data.temperature, data.molecular_weight, data.specific_heat_ratio, data.compress_factor, data.nominal_pipe_size,
529
                                    data.inside_pipe_size, data.schedule_no, data.straight_length, data.equivalent_length, data.roughness, data.limitation_velocity,
530
                                    data.limitation_pressure_drop, data.velocity, data.reynolds, data.friction_factor, data.pressure_drop, data.pressure_drop_friction,
531
                                    data.pressure_drop_static, data.pressure_pipe_end_point, data.power)
532

  
533
                        sql = 'insert or replace into HMB({}) values({})'.format(','.join(cols), ','.join(values))                  
534
                        cursor.execute(sql, param)
535
                    else:
536
                        sql = "delete from HMB where uid=?"
537
                        param = (data.uid,)
538
                        cursor.execute(sql, param)
539

  
540
                conn.commit()
541
            # Catch the exception
542
            except Exception as ex:
543
                # Roll back any change if something goes wrong
544
                conn.rollback()
545
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
550 546

  
551 547
    '''
552 548
        @brief      return stream no collection which are not duplicated 
HYTOS/HYTOS/MainWindow.py
108 108
        self.actionGroup.triggered.connect(self.actionGroupTriggered)
109 109
        self.actionClose.triggered.connect(self.close)
110 110
        self.actionNew.triggered.connect(self.new_drawing)
111
        self.actionOpen.triggered.connect(self.open_drawing)
111 112
        self.actionSave.triggered.connect(self.actionSaveCliked)
112 113
        self.actionCalculation.triggered.connect(self.calculation)
113 114
        self.actionLine.triggered.connect(self.onPlaceLine)
......
196 197
        if drawingName:
197 198
            self.load_drawing_list()
198 199

  
199

  
200 200
    def deleteDrawingActionClickEvent(self, item):
201
        """ delete selected drawing """
201 202
        try:
202 203
            msg = QMessageBox(self)
203 204
            msg.setIcon(QMessageBox.Question)
......
206 207
            msg.setStandardButtons(QMessageBox.Ok|QMessageBox.Cancel)
207 208

  
208 209
            if QMessageBox.Ok == msg.exec_():
209
                uid = item.text(2)
210
                appDocData = AppDocData.instance()
210
                drawing = item.data(0, Qt.UserRole)
211
                app_doc_data = AppDocData.instance()
211 212
                
212
                if appDocData.activeDrawing is not None:                    
213
                    appDocData.activeDrawing = None
213
                if app_doc_data.activeDrawing is not None:                    
214
                    app_doc_data.activeDrawing = None
214 215

  
215 216
                if self.graphicsView.hasImage():
216 217
                    self.graphicsView.clearImage()
217 218
                    self.graphicsView.scene.clear()
218 219

  
219
                appDocData.deleteDrawingByUID(uid)
220
                app_doc_data.deleteDrawingByUID(drawing)
220 221

  
221 222
                self.load_drawing_list()                
222 223
                self.initTableWidgetHMB()
......
229 230
        self.clear_HMB()
230 231
        
231 232
    def eventFilter(self, source, event):
232
        
233
        """
234
        display mouse position of graphics view
235
        """
233
        """ display mouse position of graphics view """
236 234
        if (event.type() == QEvent.MouseMove):
237 235
            pos = self.graphicsView.mapToScene(event.pos())
238 236
            self._label_mouse.setText('mouse pos : ({},{})'.format(round(pos.x()), round(pos.y())))
......
385 383
        """
386 384

  
387 385
        try:
388
            appDocData = AppDocData.instance()
389
            drawings = appDocData.getDrawings()
386
            app_doc_data = AppDocData.instance()
387
            drawings = app_doc_data.getDrawings()
390 388

  
391 389
            self.treeWidgetDrawingList.clear()
392 390
            self.treeWidgetDrawingList.root = QTreeWidgetItem(self.treeWidgetDrawingList, [self.tr('Drawings'), ''])
393 391
                      
394
            for drawing in drawings:               
395
                if drawing[1] == 'Template':
396
                    continue
397
                QTreeWidgetItem(self.treeWidgetDrawingList.root, [drawing[1], drawing[2], drawing[0] if drawing and drawing[0] else ''])
392
            for drawing in drawings:
393
                item = QTreeWidgetItem(self.treeWidgetDrawingList.root, [drawing.name, drawing.date_time])
394
                item.setData(0, Qt.UserRole, drawing)
398 395
                            
399 396
            self.treeWidgetDrawingList.root.setText(0, self.tr('Drawings')+'({})'.format(self.treeWidgetDrawingList.root.childCount()))
400 397
            self.treeWidgetDrawingList.expandItem(self.treeWidgetDrawingList.root)
......
406 403
            self.addMessage.emit(MessageType.Error, message)
407 404

  
408 405
    def open_selected_drawing(self, item, column):
409
        """
410
        @brief      open selected p&id drawing
411
        @author     humkyung
412
        @date       18.11.02
413
        """
414
        if item.parent() is not None:
406
        """ open selected drawing """
407
        drawing = item.data(0, Qt.UserRole)
408
        if drawing:
415 409
            self.open_border_file()
416
            self.load_data(item.text(0))
410
            self.load_data(drawing)
417 411

  
418 412
    def dbUpdate(self):
419 413
        '''
......
463 457
        from SaveWorkCommand import SaveWorkCommand 
464 458

  
465 459
        try:
466
            appDocData = AppDocData.instance()
467
            if appDocData.imgName is None or appDocData.activeDrawing is None:
460
            app_doc_data = AppDocData.instance()
461
            if app_doc_data.activeDrawing is None:
468 462
                self.showImageSelectionMessageBox()
469 463
                return
470 464

  
471
            appDocData.activeDrawing.clearItemList()
465
            app_doc_data.activeDrawing.clearItemList()
472 466

  
473 467
            items = self.graphicsView.scene.items()
474 468
            for item in items:
475 469
                if issubclass(type(item), QEngineeringAbstractItem):
476
                    appDocData.activeDrawing.allItems.append(item)
470
                    app_doc_data.activeDrawing.allItems.append(item)
477 471
                    if issubclass(type(item), QEngineeringTextItem):
478
                        appDocData.texts.append(item)
472
                        app_doc_data.texts.append(item)
479 473
            
480
            count = len(appDocData.activeDrawing.allItems)
474
            count = len(app_doc_data.activeDrawing.allItems)
481 475
            if count > 0:
482 476
                try:
483 477
                    self.progress = QProgressDialog(self.tr("Please wait for a while"), self.tr("Cancel"), 0, 100, self) if not hasattr(self, 'progress') else self.progress
......
500 494
            self.addMessage.emit(MessageType.Error, message)
501 495

  
502 496
    def save_drawing_data(self):
497
        """ save drawing data """
503 498
        from datetime import datetime
504 499
        from AppDocData import AppDocData
505 500
        from SymbolSvgItem import SymbolSvgItem 
506 501
        from EngineeringStreamlineItem import QEngineeringStreamlineItem
507 502

  
508 503
        try:            
509
            appDocData = AppDocData.instance()
510
            items = appDocData.activeDrawing.allItems
504
            app_doc_data = AppDocData.instance()
505
            items = app_doc_data.activeDrawing.allItems
511 506

  
512 507
            maxValue = len(items)
513 508
            self.progress.setMaximum(maxValue)
......
515 510
            index = 0
516 511
            for item in items:                
517 512
                if type(item) is SymbolSvgItem or type(item) is QEngineeringStreamlineItem:                    
518
                    appDocData.saveToDatabase(item, index)         
513
                    app_doc_data.saveToDatabase(item, index)         
519 514
                    self.progress.setValue(index)
520 515
                    index += 1
521 516

  
......
526 521
                activeDrawing.hmbTable.saveData()
527 522

  
528 523
            """ update drawing's modified time """
529
            drawings = appDocData.getDrawings()
530
            drawing = [drawing for drawing in drawings if appDocData.imgName == os.path.splitext(drawing[1])[0]]
531
            if drawing[0]:
532
                drawing[0][2] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
524
            drawings = app_doc_data.getDrawings()
525
            drawing = [drawing for drawing in drawings if app_doc_data.activeDrawing == drawing]
526
            if drawing:
527
                drawing.date_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
533 528
                appDocData.updateDrawing(drawing)
534 529
                
535 530
        except Exception as ex:
......
752 747
        @date       2019.07.10
753 748
    '''
754 749
    def open_border_file(self):   
755
        project = AppDocData.instance().getCurrentProject()
756
        borderDir = project.getBorderFilePath()    
757
        borderFile = os.path.join(borderDir, 'Border.png')
750
        app_doc_data = AppDocData.instance()
751
        borderFile = app_doc_data.border_file_path
758 752
        if not os.path.exists(borderFile):
759
            if not os.path.exists(borderDir):
760
                os.makedirs(borderDir)
761 753
            self.create_border_file(borderFile)
762 754

  
763 755
        self.graphicsView.loadImageFromFile(fileName=borderFile)
......
781 773
        img.save(border)
782 774

  
783 775
    def load_data(self, drawing):
776
        """ load data from drawing """
784 777
        from Drawing import Drawing
785
        from xml.etree.ElementTree import Element, SubElement, dump, ElementTree, parse
786 778

  
787 779
        try:
788
            appDocData = AppDocData.instance()
789
            project = appDocData.getCurrentProject()
780
            app_doc_data = AppDocData.instance()
790 781
                    
791 782
            ## Set appDocData
792
            appDocData.clear()
783
            app_doc_data.clear()
793 784
            self.onCommandRejected()
794 785

  
795
            self.path = os.path.join(project.getDrawingFilePath(), drawing + '.png')
796
            appDocData.setImgFilePath(self.path)
797
            appDocData.activeDrawing = Drawing(appDocData.imgName)            
786
            app_doc_data.activeDrawing = drawing
798 787

  
799 788
            self.initTableWidgetHMB()
800 789
            ## Load data on database     
801 790

  
802
            components = appDocData.getComponentListByDrawingUID(appDocData.activeDrawing.UID)
791
            components = app_doc_data.getComponentListByDrawingUID(drawing)
803 792
            count = len(components)
804 793

  
805 794
            if count > 0:                
......
831 820
        @brief      create new drawing
832 821
        @author     yeonjin
833 822
        @date       2019.07.03
834

  
835 823
    '''
836 824
    def new_drawing(self):
837
        from DrawingDialog import QDrawingDialog
825
        import uuid
826
        from datetime import datetime 
827
        from Drawing import Drawing
828

  
829
        options = QFileDialog.Options()
830
        options |= QFileDialog.DontUseNativeDialog
831
        name , _ = QFileDialog.getSaveFileName(self, self.tr('New Drawing'), '', 'HYTOS Files (*.hytos)', options=options)
832
        if name:
833
            if not os.path.splitext(name)[1]: name += '.hytos'
834

  
835
            app_doc_data = AppDocData.instance()
836
            matches = [drawing for drawing in app_doc_data.getDrawings() if drawing.path == name]
837
            if not matches:
838
                drawing = Drawing(str(uuid.uuid4()), name, str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
839
                app_doc_data.saveDrawing(drawing)
840
            else:
841
                drawing = Drawing(str(matches[0].UID), name, str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
842
                app_doc_data.updateDrawing(drawing)
838 843

  
839
        dlg = QDrawingDialog(self)
840
        drawingName = dlg.showDialog()
841
        if drawingName:
842 844
            self.load_drawing_list()
843 845
            self.open_border_file()
844
            self.load_data(drawingName)
846
            self.load_data(name)
845 847
    
848
    def open_drawing(self):
849
        """ open selected drawing by user """
850
        import uuid
851

  
852
        options = QFileDialog.Options()
853
        options |= QFileDialog.DontUseNativeDialog
854
        name, _ = QFileDialog.getOpenFileName(self, 'open drawing', '', 'HYTOS File(*.hytos)', options=options)
855
        if name:
856
            app_doc_data = AppDocData.instance()
857
            drawings = app_doc_data.getDrawings()
858
            matches = [drawing for drawing in drawings if drawing.path == name]
859
            if not matches:
860
                drawing = Drawing(str(uuid.uuid4()), name, str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
861
                app_doc_data.saveDrawing(drawing)
862

  
863
                self.load_drawing_list()
864
            else:
865
                drawing = matches[0]
866

  
867
            self.open_border_file()
868
            self.load_data(drawing)
869

  
846 870
    def changeViewCheckedState(self, checked, clear=True):
847 871
        '''
848 872
            @brief      change view checked state
......
1061 1085
        from EngineeringConnectorItem import QEngineeringConnectorItem 
1062 1086

  
1063 1087
        try:
1064
            appDocData = AppDocData.instance()
1088
            app_doc_data = AppDocData.instance()
1065 1089

  
1066 1090
            maxValue = len(componentsUID)
1067 1091
            self.progress.setMaximum(maxValue)
1068 1092

  
1069 1093
            for componentUID in componentsUID:
1070
                componentInfos = appDocData.getComponentByComponentUID(componentUID)
1094
                componentInfos = app_doc_data.getComponentByComponentUID(componentUID)
1071 1095
                if (len(componentInfos)) > 0:                    
1072 1096
                    category = componentInfos[0][3] # Category@SymbolType
1073 1097

  
......
1080 1104
                        item = SymbolSvgItem.fromDatabase(componentInfos)
1081 1105
                        if item is not None:
1082 1106
                            item.transfer.onRemoved.connect(self.itemRemoved)
1083
                            #symbols.append(item)
1084
                            appDocData.symbols.append(item)
1107
                            app_doc_data.symbols.append(item)
1085 1108
                            self.addSvgItemToScene(item)
1086 1109

  
1087 1110
                    self.progress.setValue(self.progress.value() + 1)
HYTOS/HYTOS/MainWindow_UI.py
1 1
# -*- coding: utf-8 -*-
2 2

  
3
# Form implementation generated from reading ui file '.\UI\MainWindow.ui'
3
# Form implementation generated from reading ui file '.\ui\MainWindow.ui'
4 4
#
5 5
# Created by: PyQt5 UI code generator 5.13.0
6 6
#
......
395 395
        self.actionCalculation.setFont(font)
396 396
        self.actionCalculation.setObjectName("actionCalculation")
397 397
        self.menu.addAction(self.actionNew)
398
        self.menu.addAction(self.actionOpen)
398 399
        self.menu.addAction(self.actionSave)
399 400
        self.menu.addSeparator()
400 401
        self.menu.addAction(self.actionConfiguration)
HYTOS/HYTOS/Project.py
89 89
        return self.getPath() + '/Temp'
90 90

  
91 91
    '''
92
        @brief  return training path
93
        @author euisung
94
        @date   2018.09.28
95
    '''
96
    def getTrainingFilePath(self):
97
        return self.getPath() + '/Training'
98

  
99
    '''
100 92
        @brief  return border file path
101 93
        @author yeonjin
102 94
        @date   2019.07.11
HYTOS/HYTOS/QtImageViewer.py
555 555
        from AppDocData import AppDocData
556 556
        import symbol
557 557
        
558
        symbol = AppDocData.instance().getSymbolByQuery('uid', uid)
558
        app_doc_data = AppDocData.instance()
559
        symbol = app_doc_data.getSymbolByQuery('uid', uid)
559 560
        svgFileName = symbol.sName
560 561
        svgType = symbol.sType
561 562
        svgAngle = 0
562 563
        svgScale = 1
563 564
        svgOrigin = symbol.originalPoint
564
        svgFilePath = os.path.join(AppDocData.instance().getCurrentProject().getSvgFilePath(), symbol.getCategory(), symbol.getType(), svgFileName+'.svg')
565
        svgFilePath = os.path.join(app_doc_data.symbol_file_path, symbol.getCategory(), symbol.getType(), svgFileName + '.svg')
565 566
        svg = SymbolSvgItem.createItem(symbol.getType(), svgFilePath)
566 567
        connPts = None
567 568
        strConnPts = symbol.connectionPoint
HYTOS/HYTOS/Scripts/App.sql
1
CREATE TABLE IF NOT EXISTS Configuration (
2
	Section VARCHAR(37) NOT NULL,
3
	[Key] 	VARCHAR(37) NOT NULL,
4
	Value 	TEXT,
5
	CONSTRAINT PK_Configuration PRIMARY KEY (
6
        Section,
7
		[Key]
8
    )
9
);
10

  
11
CREATE TABLE IF NOT EXISTS Styles (
12
    UID   VARCHAR(37),
13
    Value TEXT,
14
    CONSTRAINT Styles_PK PRIMARY KEY (
15
        UID
16
    ),
17
    UNIQUE (
18
        Value
19
    )
20
);
21

  
22
CREATE TABLE IF NOT EXISTS Drawings (
23
    UID      VARCHAR(37) NOT NULL,
24
    NAME     VARCHAR(1024) NOT NULL,
25
    DATETIME TEXT NOT NULL,
26
	Owner	 VARCHAR(64) NULL,
27
    CONSTRAINT PK_Drawings PRIMARY KEY (
28
        UID
29
    ),
30
    CONSTRAINT UQ_Drawings UNIQUE (
31
        NAME
32
    )
33
);
HYTOS/HYTOS/Shapes/SymbolSvgItem.py
860 860
                pointsUid = componentInfo[11]       # uid@Points
861 861
                pointsUids.append(pointsUid)
862 862

  
863
            appDocData = AppDocData.instance()
864
            project = appDocData.getCurrentProject()
865
            svgFilePath = os.path.join(project.getSvgFilePath(), category, _type, name + '.svg')
863
            app_doc_data = AppDocData.instance()
864
            svgFilePath = os.path.join(app_doc_data.symbol_file_path, category, _type, name + '.svg')
866 865
            if os.path.isfile(svgFilePath):
867 866
                item = SymbolSvgItem.createItem(_type, svgFilePath, uid)
868 867
                item.setVisible(False)
869 868
                item.buildItem(name, _type, float(angle), float(scale), pt, origin, connPts, dbUid, pointsUids)
870

  
871
                for area in appDocData.getAreaList():
872
                    if area.contains(pt):
873
                        item.area = area.name
874
                        break
875
                
876 869
        except Exception as ex:
877 870
            from App import App 
878 871
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
HYTOS/HYTOS/SymbolTreeWidget.py
65 65
        project = AppDocData.instance().getCurrentProject()
66 66
        if project is not None:
67 67
            self.clear()
68
            self.makeChildDir()
69 68
            self.loadSymbolInfo()
70 69
            self.expandAll()
71 70

  
......
122 121
            App.mainWnd().addMessage.emit(MessageType.Error, message)
123 122

  
124 123
    '''
125
        @brief      Make Directory
126
        @author     Jeongwoo
127
        @date       18.04.??
128
        @history    18.04.12    Jeongwoo    Add output, temp Directory
129
    '''
130
    def makeChildDir(self):
131
        project = AppDocData.instance().getCurrentProject()
132
        dbDir = project.getDbFilePath()
133
        if not os.path.exists(dbDir):
134
            os.makedirs(dbDir)
135
        imgDir = project.getImageFilePath()
136
        if not os.path.exists(imgDir):
137
            os.makedirs(imgDir)
138
        svgDir = project.getSvgFilePath()
139
        if not os.path.exists(svgDir):
140
            os.makedirs(svgDir)
141
        outputDir = project.getOutputPath()
142
        if not os.path.exists(outputDir):
143
            os.makedirs(outputDir)
144
        tempDir = project.getTempPath()
145
        if not os.path.exists(tempDir):
146
            os.makedirs(tempDir)
147

  
148
    '''
149 124
        @brief  start drag
150 125
        @author humkyung
151 126
        @date   2018.04.17
HYTOS/HYTOS/UI/MainWindow.ui
59 59
     </property>
60 60
    </widget>
61 61
    <addaction name="actionNew"/>
62
    <addaction name="actionOpen"/>
62 63
    <addaction name="actionSave"/>
63 64
    <addaction name="separator"/>
64 65
    <addaction name="actionConfiguration"/>
HYTOS/HYTOS/XmlGenerator.py
1
# coding: utf-8
2
""" This is xml generator module """
3

  
4
from xml.etree.ElementTree import Element, SubElement, dump, ElementTree, parse
5
import symbol
6
import SymbolBase
7
import TextInfo as ti
8
import math
9
import os
10
import sys
11
from AppDocData import AppDocData
12

  
13
ROOT_NODE_NAME = "DWG"
14
ROOT_DWGNAME_NODE_NAME = "DWGNAME"
15
ROOT_SIZE_NODE_NAME = "SIZE"
16

  
17
SYMBOL_LIST_NODE_NAME = "SYMBOLS"
18
TEXT_INFO_LIST_NODE_NAME = "TEXTINFOS"
19
IMG_LINE_LIST_NODE_NAME = "IMGLINES"
20
NOTE_TEXT_INFO_LIST_NOTE_NAME = "NOTES"
21

  
22
SCATEGORY_NODE_NAME = "SYMBOL"
23

  
24
SNAME_NODE_NAME = "NAME"
25

  
26
STYPE_NOTE_NAME = "TYPE"
27

  
28
SCLASS_NODE_NAME = "CLASS"
29

  
30
SITEM_NODE_NAME = "ITEM"
31

  
32
SSUB_TEXT = "TEXT"
33
SSUB_ORIGINAL_POINT = "ORIGINALPOINT"
34
SSUB_CONNECTION_POINT = "CONNECTIONPOINT"
35
SSUB_PARENT = "PARENT"
36
SSUB_CHILD = "CHILD"
37
SSUB_ANGLE = "ANGLE"
38
SSUB_START_POINT = "STARTPOINT"
39
SSUB_SIZE = "SIZE"
40

  
41
LINE_NO_LIST_NODE_NAME = "LINE_NOS"
42

  
43
TEXT_INFO_NODE_NAME = "TEXTINFO"
44
TTEXT_NODE_NAME = "TEXT"
45
TTEXT_X_NODE_NAME = "X"
46
TTEXT_Y_NODE_NAME = "Y"
47
TTEXT_WIDTH_NODE_NAME = "WIDTH"
48
TTEXT_HEIGHT_NODE_NAME = "HEIGHT"
49
TTEXT_ANGLE_NODE_NAME = "ANGLE"
50

  
51

  
52
IMG_LINE_NODE_NAME = "IMGLINE"
53
ISP_NODE_NAME = "START"
54
IEP_NODE_NAME = "END"
55

  
56
NOTE_TEXT_INFO_NOTE_NAME = "NOTE"
57
TNOTE_TEXT_NODE_NAME = "TEXT"
58
TNOTE_TEXT_X_NODE_NAME = "X"
59
TNOTE_TEXT_Y_NODE_NAME = "Y"
60
TNOTE_TEXT_WIDTH_NODE_NAME = "WIDTH"
61
TNOTE_TEXT_HEIGHT_NODE_NAME = "HEIGHT"
62
TNOTE_TEXT_ANGLE_NODE_NAME = "ANGLE"
63

  
64
LINE_INFOS_NODE_NAME = "LINEINFOS"
65
LLINE_INFO_NODE_NAME = "LINEINFO"
66
LLINE_UUID = "UUID"
67
LLINE_START_POINT_NODE_NAME = "STARTPOINT"
68
LLINE_END_POINT_NODE_NAME = "ENDPOINT"
69

  
70
LINE_NOS_NODE_NAME = "LINENOS"
71
TRIM_LINE_NOS_NODE_NAME = "TRIMLINENOS"
72

  
73
UNKNOWNS_NODE_NAME = "UNKNOWNS"
74
VENDOR_NODE_NAME = "VENDORS"
75
#END_BREAK = "END_BREAKS"
76

  
77
'''
78
    @brief  
79
    @author 
80
    @date   
81
    @history    2018.05.25  Jeongwoo    Remove parameter 'imgLineList'
82
'''
83
def writeXml(pidName, pidWidth, pidHeight, searchedSymbolList, textInfoList, noteTextInfoList):
84
    path = os.path.join(AppDocData.instance().getCurrentProject().getTempPath(), pidName + '.xml')
85
    try:
86
        xmlData = generateXml(pidName, pidWidth, pidHeight, searchedSymbolList, textInfoList, noteTextInfoList)
87
        ElementTree(xmlData).write(path)
88
    except Exception as ex:
89
        from App import App
90
        from AppDocData import MessageType
91

  
92
        message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
93
        print(message)
94
        App.mainWnd().addMessage.emit(MessageType.Error, message)
95

  
96
    return path
97

  
98
'''
99
    @brief  write output xml
100
    @author humkyung
101
    @date   2018.04.23
102
'''
103
def writeOutputXml(pidName, pidWidth, pidHeight):
104
    try:
105
        path = os.path.join(AppDocData.instance().getCurrentProject().getOutputPath(), pidName + '.xml')
106

  
107
        xmlData = generateOutputXml(pidName, pidWidth, pidHeight)
108
        ElementTree(xmlData).write(path)
109
    except Exception as ex:
110
        from App import App 
111
        from AppDocData import MessageType
112

  
113
        message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
114
        print(message)
115
        App.mainWnd().addMessage.emit(MessageType.Error, message)
116

  
117
    return path
118

  
119
'''
120
    @brief      generate output xml for converter
121
    @author     humkyung
122
    @date       2018.04.23
123
    @history    humkyung 2018.05.02 write equipment node
124
                humkyung 2018.05.10 write orphan lines
125
                humkyung 2018.05.16 remove code to write orphan lines and symbols
126
                humkyung 2018.09.06 write text to xml
127
'''
128
def generateOutputXml(pidName, pidWidth, pidHeight):
129
    appDocData = AppDocData.instance()
130

  
131
    try:
132
        xml = Element(ROOT_NODE_NAME) # Root Node
133
        SubElement(xml, ROOT_DWGNAME_NODE_NAME).text = pidName
134
        SubElement(xml, ROOT_SIZE_NODE_NAME).text = str(pidWidth) + "," + str(pidHeight)
135
        SubElement(xml, 'UNIT').text = appDocData.getCurrentProject().unit()
136

  
137
        for equipment in appDocData.equipments:
138
            equipmentNode = Element('EQUIPMENT')
139
            equipmentNode.append(equipment.toXml())
140
            xml.append(equipmentNode)
141

  
142
        sortedList = sorted(appDocData.lineNos, key=lambda param:param.text())
143
        for lineno in sortedList:
144
            xml.append(lineno.toXml())
145

  
146
        for text in appDocData.texts:
147
            xml.append(text.toXml())
148
    except Exception as ex:
149
        from App import App
150
        from AppDocData import MessageType
151

  
152
        message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
153
        print(message)
154
        App.mainWnd().addMessage.emit(MessageType.Error, message)
155
    return xml
156

  
157
'''
158
    @history    2018.04.30  Jeongwoo    noteTextInfoList None Check
159
                2018.05.25  Jeongwoo    Remove parameter 'imgLineList' and Check if variable is None or not
160
'''
161
def generateXml(pidName, pidWidth, pidHeight, searchedSymbolList, textInfoList, noteTextInfoList):
162
    xml = Element(ROOT_NODE_NAME) # Root Node
163
    SubElement(xml, ROOT_DWGNAME_NODE_NAME).text = pidName
164
    SubElement(xml, ROOT_SIZE_NODE_NAME).text = str(pidWidth) + "," + str(pidHeight)
165
    try:
166
        if searchedSymbolList is not None:
167
            symbolListNode = Element(SYMBOL_LIST_NODE_NAME) # Symbol List Node
168
            sortedList = sorted(searchedSymbolList, key=lambda sym:sym.getName())
169
            for symbol in sortedList:
170
                node = getSymbolInfoNode(symbol)
171
                symbolListNode.append(node)
172

  
173
            xml.append(symbolListNode)
174

  
175
        if textInfoList is not None:
176
            textInfoListNode = Element(TEXT_INFO_LIST_NODE_NAME) # Text Info List Node
177
            for textInfo in textInfoList:
178
                node = getTextInfoNode(textInfo)
179
                textInfoListNode.append(node)
180

  
181
            xml.append(textInfoListNode)
182

  
183
        noteTextInfoListNode = Element(NOTE_TEXT_INFO_LIST_NOTE_NAME)
184
        if noteTextInfoList is not None:
185
            for noteTextInfo in noteTextInfoList:
186
                node = getNoteTextInfoNode(noteTextInfo)
187
                noteTextInfoListNode.append(node)
188

  
189
        xml.append(noteTextInfoListNode)
190
    except Exception as ex:
191
        from App import App
192
        from AppDocData import MessageType
193

  
194
        message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
195
        print(message)
196
        App.mainWnd().addMessage.emit(MessageType.Error, message)
197

  
198
    return xml
199

  
200
def getSymbolInfoNode(symbol):
201
    sName = symbol.getName()
202
    sSp = symbol.getSp()
203
    sAngle = symbol.getRotatedAngle()
204
    sType = symbol.getType()
205
    sText = symbol.getText()
206
    sOriginalPoint = symbol.getOriginalPoint()
207
    sConnectionPoint = symbol.getConnectionPoint()
208
    sWidth = symbol.getWidth()
209
    sHeight = symbol.getHeight()
210
    sBaseSymbol = symbol.getBaseSymbol()
211
    sAdditionalSymbol = symbol.getAdditionalSymbol()
212

  
213
    sCategoryNode = Element(SCATEGORY_NODE_NAME)
214

  
215
    sNameNode = Element(SNAME_NODE_NAME)
216
    sNameNode.text = sName
217

  
218
    sTypeNode = Element(STYPE_NOTE_NAME)
219
    sTypeNode.text = sType
220
    
221
    sOriginalPointNode = Element(SSUB_ORIGINAL_POINT)
222
    sOpX = sSp[0] + int(sOriginalPoint.split(',')[0])
223
    sOpY = sSp[1] + int(sOriginalPoint.split(',')[1])
224
    sOriginalPointNode.text = str(sOpX) + "," + str(sOpY)
225

  
226
    sConnectionPointNode = Element(SSUB_CONNECTION_POINT)
... 이 차이점은 표시할 수 있는 최대 줄수를 초과해서 이 차이점은 잘렸습니다.

내보내기 Unified diff

클립보드 이미지 추가 (최대 크기: 500 MB)