프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

hytos / DTI_PID / DTI_PID / Drawing.py @ 7fb00532

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

1
# coding: utf-8
2
""" This is Drawing module """
3

    
4
import os
5
import sys
6
import uuid
7
from PIL import PngImagePlugin, JpegImagePlugin
8
from PIL import Image
9
from PIL.ImageQt import ImageQt
10
import numpy as np
11
from AppDocData import AppDocData
12

    
13
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)) + '\\Shapes')
14
from SymbolSvgItem import SymbolSvgItem
15
from EngineeringTextItem import QEngineeringTextItem
16
from EngineeringLineItem import QEngineeringLineItem
17
from EngineeringLineNoTextItem import QEngineeringLineNoTextItem
18
from EngineeringRunItem import QEngineeringRunItem
19
from EngineeringVendorItem import QEngineeringVendorItem
20
from EngineeringUnknownItem import QEngineeringUnknownItem
21
from QEngineeringTrimLineNoTextItem import QEngineeringTrimLineNoTextItem
22

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

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

    
48
class Drawing:
49
    '''
50
        @brief  construction
51
        @author humkyung
52
        @date   2018.07.07
53
    '''
54
    def __init__(self, uid, name, datetime):
55
        import uuid
56
        app_doc_data = AppDocData.instance()
57

    
58
        self.name = name
59
        self._datetime = datetime
60
        ''' set drawing uid '''
61
        if not uid:
62
            drawings = app_doc_data.getDrawings()
63
            drawing = [drawing for drawing in drawings if self.name == os.path.splitext(drawing.name)[0]]
64
            self.UID = drawing[0].UID if drawing else uuid.uuid4()
65
            self._datetime = drawing[0].datetime if drawing else None
66
        else:
67
            self.UID = uid
68

    
69
        self.width = 0
70
        self.height = 0
71
        self._attrs = [['Drawing No', ''], ['Rev No', ''], ['Unit', '']] # attributes
72

    
73
    @property
74
    def datetime(self):
75
        """ return datetime """
76
        return self._datetime
77

    
78
    @datetime.setter
79
    def datetime(self, value):
80
        """ set date time of drawing """
81
        self._datetime = value
82

    
83
    '''
84
        @brief  getter of attrs
85
        @author humkyung
86
        @date   2018.07.07
87
    '''
88
    @property
89
    def attrs(self):
90
        return self._attrs
91

    
92
    '''
93
        @brief  setter of attrs
94
        @author humkyung
95
        @date   2018.07.07
96
    '''
97
    @attrs.setter
98
    def attrs(self, value):
99
        self._attrs = value
100

    
101
    def set_pid_source(self, image):
102
        """ set image source for drawing """
103
        self.width, self.height = image.size
104
        self.currentPidSource = Source(image)
105

    
106
    '''
107
        @brief  set attribute
108
        @author humkyung
109
        @date   2018.07.07
110
    '''
111
    def setAttr(self, name, value):
112
        attrs = [attr for attr in self._attrs if attr[0] == name]
113
        if attrs:
114
            attrs[0][1] = value
115
        else:
116
            self._attrs.append([name, value])
117

    
118
        print('attribute({},{})'.format(name, value))
119

    
120
    def from_database(self):
121
        """ load all components of drawing """
122
        
123
        items = []
124
        tracer_line_nos = []
125
        app_doc_data = AppDocData.instance()
126
        try:
127
            components = app_doc_data.get_components(self.UID)
128

    
129
            """ parsing all symbols """
130
            for symbol in [component for component in components if component['SymbolType_UID'] != -1]:
131
                item = SymbolSvgItem.from_database(symbol)
132
                if item: items.append(item)
133

    
134
            # parse texts
135
            for text in [component for component in components if component['Name'] == 'Text' and component['SymbolType_UID'] == -1]:
136
                item = QEngineeringTextItem.from_database(text)
137
                if item:
138
                    item.uid = text['UID']
139
                    item.attribute = text['Value']
140
                    items.append(item)
141

    
142
            # note
143
            for note in [component for component in components if component['Name'] == 'Note' and component['SymbolType_UID'] == -1]:
144
                item = QEngineeringTextItem.from_database(note)
145
                if item is not None:
146
                    item.uid = note['UID']
147
                    items.append(item)
148

    
149
            for line in [component for component in components if component['Name'] == 'Line' and component['SymbolType_UID'] == -1]:
150
                item = QEngineeringLineItem.from_database(line)
151
                if item: items.append(item)
152

    
153
            for unknown in [component for component in components if component['Name'] == 'Unknown' and component['SymbolType_UID'] == -1]:
154
                item = QEngineeringUnknownItem.from_database(unknown)
155
                if item: items.append(item)
156

    
157
            for component in [component for component in components if component['Name'] == 'Line NO' and component['SymbolType_UID'] == -1]:
158
                line_no = QEngineeringLineNoTextItem.from_database(component)
159
                if type(line_no) is QEngineeringLineNoTextItem:
160
                    runs = app_doc_data.get_pipe_runs(str(line_no.uid))
161
                    if not runs: continue
162
                    for run in runs:
163
                        line_run = QEngineeringRunItem()
164
                        run_items = app_doc_data.get_pipe_run_items(run['UID'])
165
                        for record in run_items:
166
                            uid = record['Components_UID']
167
                            matches = [item for item in items if str(item) == str(uid)]
168
                            if matches:
169
                                matches[0]._owner = line_no
170
                                line_run.items.append(matches[0])
171
                        line_run.owner = line_no
172
                        line_no.runs.append(line_run)
173

    
174
            for component in [component for component in components if component['Name'] == 'Trim Line NO' and component['SymbolType_UID'] == -1]:
175
                tracer_line_no = QEngineeringTrimLineNoTextItem()
176
                tracer_line_no.uid = uuid.UUID(component['UID'], version=4)
177

    
178
                runs = app_doc_data.get_pipe_runs(str(tracer_line_no.uid))
179
                if not runs: continue
180
                for run in runs:
181
                    line_run = QEngineeringRunItem()
182
                    run_items = app_doc_data.get_pipe_run_items(run['UID'])
183
                    for record in run_items:
184
                        uid = record['Components_UID']
185
                        matches = [item for item in items if str(item) == str(uid)]
186
                        if matches:
187
                            matches[0].owner = tracer_line_no
188
                            line_run.items.append(matches[0])
189
                tracer_line_no.runs.append(line_run)
190
                
191
                tracer_line_nos.append(tracer_line_no)
192

    
193
            for component in [component for component in components if component['Name'] == 'VendorPackage' and component['SymbolType_UID'] == -1]:
194
                item = QEngineeringVendorItem.from_database(component)
195
                if item: items.append(item)
196
        except Exception as ex:
197
            from App import App
198
            from AppDocData import MessageType
199

    
200
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
201
            App.mainWnd().addMessage.emit(MessageType.Error, message)
202
        finally:
203
            return items,tracer_line_nos
204

    
205
    def export(self, path):
206
        """ save items of drawing to given xml file """
207
        import XmlGenerator as xg
208

    
209
        items,tracer_line_nos = self.from_database()
210
        xg.writeXmlOnScene(path, self.width, self.height, items, tracer_line_nos)
211

    
212
    def transfer(self, database):
213
        """ data transfer to given database """
214
        from AppDocData import AppDocData, MessageType
215

    
216
        app_doc_data = AppDocData.instance()
217
        conn = database.connect()
218
        with conn:
219
            try:
220
                cursor = conn.cursor()
221
                sql = database.to_sql('delete from LINE_DATA_LIST where PNID_NO=?')
222
                cursor.execute(sql, (self.name,))
223
                sql = database.to_sql('delete from EQUIPMENT_DATA_LIST where PNID_NO=?')
224
                cursor.execute(sql,(self.name,))
225
                sql = database.to_sql('delete from VALVE_DATA_LIST where PNID_NO=?')
226
                cursor.execute(sql, (self.name,))
227
                sql = database.to_sql('delete from INSTRUMENT_DATA_LIST where PNID_NO=?')
228
                cursor.execute(sql, (self.name,))
229
                sql = database.to_sql('delete from NOTE_DATA_LIST where PNID_NO=?') 
230
                cursor.execute(sql, (self.name,))
231
                sql = database.to_sql('delete from TitleBlockValues where Drawings_UID=(select UID from Drawings where [Name]=?)')
232
                cursor.execute(sql, (self.name,))
233
                sql = database.to_sql('delete from LineNoAttributes where Components_UID in (select UID from Components where Drawings_UID=(select UID from Drawings where Name=?))')
234
                cursor.execute(sql, (self.name,))
235
                sql = database.to_sql('delete from Attributes where Components_UID in (select UID from Components where Drawings_UID=(select UID from Drawings where Name=?))')
236
                cursor.execute(sql, (self.name,))
237
                sql = database.to_sql('delete from Associations where Components_UID in (select UID from Components where Drawings_UID=(select UID from Drawings where Name=?))')
238
                cursor.execute(sql, (self.name,))
239
                sql = database.to_sql('delete from Points where Components_UID in (select UID from Components where Drawings_UID=(select UID from Drawings where Name=?))')
240
                cursor.execute(sql, (self.name,))
241
                sql = database.to_sql('delete from PipeRunItems where PipeRuns_UID in (select UID from PipeRuns where Drawings_UID=(select UID from Drawings where Name=?))')
242
                cursor.execute(sql, (self.name,))
243
                sql = database.to_sql('delete from PipeRuns where Drawings_UID=(select UID from Drawings where Name=?)')
244
                cursor.execute(sql, (self.name,))
245
                sql = database.to_sql('delete from Components where Drawings_UID=(select UID from Drawings where Name=?)')
246
                cursor.execute(sql, (self.name,))
247
                sql = database.to_sql('delete from Drawings where Name=?')
248
                cursor.execute(sql, (self.name,))
249

    
250
                sql = database.to_sql('insert into Drawings(UID,Name,DATETIME) values(?,?,?)')
251
                cursor.execute(sql, (self.UID, self.name, self.datetime))
252

    
253
                components = app_doc_data.get_components(str(self.UID))
254
                for component in components:
255
                    sql = database.to_sql('insert into Components(UID,Drawings_UID,Symbol_UID,X,Y,Width,Height,Rotation,Area,Value,Owner,[From],[To],Connected,[Supplied By],SpecialItemTypes_UID, OriginIndex) \
256
                        values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)')
257
                    cursor.execute(sql, (component['UID'], component['Drawings_UID'], component['Symbol_UID'], 
258
                        component['X'], component['Y'], component['Width'], component['Height'], component['Rotation'], component['Area'],
259
                        component['Value'], component['Owner'], component['From'], component['To'], component['Connected'], 
260
                        component['Supplied By'], component['SpecialItemTypes_UID'], component['OriginIndex']))
261

    
262
                for component in components:
263
                    pipe_runs = app_doc_data.get_pipe_runs(component['UID'])
264
                    for pipe_run in pipe_runs:
265
                        sql = database.to_sql('insert into PipeRuns(UID,Drawings_UID,Type,Owner,[Index]) values(?,?,?,?,?)')
266
                        cursor.execute(sql, (pipe_run[0], pipe_run[1], pipe_run[2], pipe_run[3], pipe_run[4]))
267
                        pipe_run_items = app_doc_data.get_pipe_run_items(pipe_run[0])
268
                        for pipe_run_item in pipe_run_items:
269
                            sql = database.to_sql('insert into PipeRunItems(UID,PipeRuns_UID,[Index],Components_UID) values(?,?,?,?)')
270
                            cursor.execute(sql, (pipe_run_item[0], pipe_run_item[1], pipe_run_item[2], pipe_run_item[3]))
271

    
272
                    connectors = app_doc_data.get_component_connectors(component['UID'])
273
                    for connector in connectors:
274
                        sql = database.to_sql('insert into Points(Components_UID,[Index],X,Y,Connected,Connected_At) values(?,?,?,?,?,?)')
275
                        cursor.execute(sql, (connector['Components_UID'], connector['Index'], connector['X'], connector['Y'], connector['Connected'], connector['Connected_At']))
276

    
277
                    associations = app_doc_data.get_component_associations(component['UID'])
278
                    for assoc in associations:
279
                        sql = database.to_sql('insert into Associations(UID,[Type],Components_UID,Association) values(?,?,?,?)')
280
                        cursor.execute(sql, (assoc['UID'], assoc['Type'], assoc['Components_UID'], assoc['Association']))
281

    
282
                    attributes = app_doc_data.get_component_attributes(component['UID'])
283
                    for attr in attributes:
284
                        sql = database.to_sql('insert into Attributes(UID,Components_UID,SymbolAttribute_UID,Value) values(?,?,?,?)')
285
                        cursor.execute(sql, (attr['UID'], attr['Components_UID'], attr['SymbolAttribute_UID'], attr['Value']))
286

    
287
                    conn.commit()
288
                # Catch the exception
289
            except Exception as ex:
290
                # Roll back any change if something goes wrong
291
                conn.rollback()
292

    
293
                print(sql)
294
                from App import App
295
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
296
                App.mainWnd().addMessage.emit(MessageType.Error, message)
클립보드 이미지 추가 (최대 크기: 500 MB)