프로젝트

일반

사용자정보

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

hytos / HYTOS / HYTOS / TextItemFactory.py @ 5ddf3ffe

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

1
"""
2
This is TextItemFactor module
3
"""
4

    
5
from SingletonInstance import SingletonInstane
6
import re
7
try:
8
    from PyQt5.QtCore import *
9
    from PyQt5.QtGui import *
10
    from PyQt5.QtWidgets import *
11
except ImportError:
12
    try:
13
        from PyQt4.QtCore import *
14
        from PyQt4.QtGui import *
15
    except ImportError:
16
        raise ImportError("ImageViewerQt: Requires PyQt5 or PyQt4.")
17
from AppDocData import *
18
import sys, os
19
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)) + '\\Shapes')
20
from EngineeringTextItem import QEngineeringTextItem
21
from EngineeringLineNoTextItem import QEngineeringLineNoTextItem
22
from QEngineeringSizeTextItem import QEngineeringSizeTextItem
23
from QEngineeringTagNoTextItem import QEngineeringTagNoTextItem
24
from EngineeringReservedWordTextItem import QEngineeringReservedWordTextItem
25

    
26
class TextItemFactory(SingletonInstane):
27
    """ This is TextItemFactor class """
28
    def __init__(self):
29
        self.delimiter = '"'
30
        self.lineNoDelimiter = '!-!'
31

    
32
    '''
33
        @history    2018.04.27  Jeongwoo    Add condition on elif-statement (delimiter != '' and lineNoConfig != '')
34
                    humkyung 2018.05.02 create engineering size text item if condition matches
35
                    humkyung 2018.06.19 set line no's color
36
                    kyouho 2018.07.04 edit for isLineNo method (add parameter)
37
                    humkyung 2018.08.08 fill linePropertyData and tagSeqNoPattern if given data is None
38
                    euisung 2018.11.19  now textitemfactory set plain text in createTextItem() for allowables
39
    '''             
40
    def createTextItem(self, textInfo):
41
        from Configs import LineNoConfig
42

    
43
        item = None
44

    
45
        try:
46
            text = textInfo.getText()
47
            docData = AppDocData.instance()
48

    
49
            """ create normal text item if it is not in drawing area """
50
            area = docData.getArea('Drawing')
51
            if not area.contains([textInfo.getX(), textInfo.getY()]):
52
                item = QEngineeringTextItem()
53
                item.setToolTip(text)
54
                item.setPlainText(text)
55

    
56
            configs = docData.getConfigs('Size', 'Delimiter')
57
            sizeDelimiter = configs[0].value.upper() if 1 == len(configs) else None
58

    
59
            line_no_configs = LineNoConfig.instance()
60
            if line_no_configs:
61
                for line_no_config in line_no_configs:
62
                    result = line_no_config.parse(text)
63
                    if result[0]:
64
                        sizeUnit = line_no_config.unit
65
                        break
66
            else:
67
                result = (False,)
68

    
69
            if result[0]:
70
                item = QEngineeringLineNoTextItem()
71
                text = ''.join(result[1])
72
                item.setToolTip('<b>{}</b><br>LINE NO={}'.format(str(item.uid), text))
73
                item.setPlainText(text)
74

    
75
                # get color option
76
                configs = docData.getConfigs('Line Color', 'Visible Option')
77
                if configs:
78
                    visibleOption = configs[0].value
79
                else:
80
                    visibleOption = 'Random'
81

    
82
                configs = docData.getConfigs('Color Property', 'State')
83
                if configs:
84
                    color_property = configs[0].value
85

    
86
                # set line no color
87
                if visibleOption == 'Random':
88
                    rgb = docData.colors
89
                    item.change_color(QColor(rgb.red, rgb.green, rgb.blue).name())
90
                    #item.setColor(QColor(rgb.red, rgb.green, rgb.blue).name())
91
                else:
92
                    configs = docData.getConfigs('Line No', 'Configuration')
93
                    configs = configs[0].value.split(self.delimiter)
94

    
95
                    values = result[1]
96
                    index = configs.index(color_property)
97
                    if index >= 0:
98
                        value = values[index]
99
                        line_properties = docData.getLinePropertiesByUID(color_property)
100
                        if line_properties[0].Attribute.replace(' ','') == 'NominalDiameter':
101
                            if sizeUnit == "Inch":
102
                                value = docData.convertInchToMetric(value)
103

    
104
                        configs = docData.getConfigs(color_property, value)
105
                        if configs:
106
                            data = configs[0].value
107
                            rgb = data.split(',')
108
                            item.change_color(QColor(int(rgb[0]), int(rgb[1]), int(rgb[2])).name())
109
                    # up to here
110
                docData.tracerLineNos.append(item)
111
            else:
112
                item = self.create_note_no_text(textInfo)
113
                if item:
114
                    pass
115
                elif self.isSizeText(text, sizeDelimiter):
116
                    item = QEngineeringSizeTextItem()
117
                    text = text.replace(' ', '')
118
                    item.setToolTip('SIZE = {}'.format(text))
119
                    item.setPlainText(text)
120
                elif self.isTagNoText(text):
121
                    item = QEngineeringTagNoTextItem()
122
                    item.setToolTip('TAG NO = {}'.format(text))
123
                    item.setPlainText(text)
124
                elif self.is_valve_operation_code(text):
125
                    item = QEngineeringValveOperCodeTextItem()
126
                    item.setToolTip('Valve Operation Code = {}'.format(text))
127
                    item.setPlainText(text)
128
                elif self.is_reserved_word(text):
129
                    item = QEngineeringReservedWordTextItem()
130
                    item.setToolTip('Reserved Word = {}'.format(text))
131
                    item.setPlainText(text)
132
                else:
133
                    item = QEngineeringTextItem()
134
                    item.setToolTip(text)
135
                    item.setPlainText(text)
136
                docData.texts.append(item)
137
        except Exception as ex:
138
            from App import App
139

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

    
143
        return item
144
    
145
    '''
146
        @brief      Check Text startwith word
147
        @author     kyouho
148
        @date       2018.07.04
149
    '''
150
    def isStartWithWord(self, text, word):
151
        sliceText = text[0:len(word[0])]
152
        if sliceText == word[0]:
153
            return (True, text[len(sliceText):len(text)], word[1])
154
        else:
155
            return (False,)
156

    
157

    
158
    '''
159
        @brief      Check Text startwith number
160
        @author     kyouho
161
        @date       2018.07.05
162
    '''
163
    def isStartWithNumber(self, text):
164
        sliceText = text[0:1]
165
        num = ''
166
        if self.isNumber(sliceText):
167
            text = text[1:len(text)]
168
            num += text 
169
            while len(text) > 0:
170
                sliceText = text[0:1]
171
                
172
                if self.isNumber(sliceText):
173
                    text = text[1:len(text)]
174
                    num += text
175
                else:
176
                    break
177
            
178
            return (True, text, num)
179
        else:
180
            return (False,)
181

    
182
    '''
183
        @brief      Check Number
184
        @author     kyouho
185
        @date       2018.07.05
186
        @history    kyouho 2018.07.09   add Refular Expression
187
    '''
188
    def isNumber(self, num):
189
        p = re.compile('(^[0-9]+$)')
190
        result = p.match(num)
191

    
192
        if result:
193
            return True
194
        else:
195
            return False
196

    
197
    '''
198
        @brief      Check Number
199
        @author     kyouho
200
        @date       2018.07.05
201
    '''
202
    def isTagSeqNo(self, text, pattern):
203
        try:
204
            if pattern is not None:
205
                attr = text
206
                result = eval(pattern)
207
                if self.isNumber(result):
208
                    sliceText = text[0:len(result)]
209
                    return (True, text[len(sliceText):len(text)], sliceText)
210
                else:
211
                    return (False,)
212
            else:
213
                return (False,)
214
        except Exception as ex:
215
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))       
216
            
217
    '''
218
        @brief      Check Number
219
        @author     kyouho
220
        @date       2018.07.05
221
    '''
222
    def isLimitWord(self, text, pattern):
223
        try:
224
            if pattern is not None:
225
                attr = text
226
                length = pattern[0]
227
                isNumber = pattern[1]
228

    
229
                if length:  # Length가 있으면 Length만큼 문자열을 가져와 길이를 검사한다.
230
                    result = eval('attr[:' + str(length) + ']')
231
                    if int(length) != len(result):
232
                        return(False,)
233
                elif isNumber:
234
                    match = re.search(re.compile('^[0-9]+'), attr)
235
                    if match:
236
                        result = match.group(match.start()) 
237
                    else:
238
                        return (False,)
239
                else:
240
                    result = attr
241

    
242
                if isNumber:
243
                    if self.isNumber(result):
244
                        sliceText = text[0:len(result)]
245
                        return (True, text[len(sliceText):len(text)], sliceText)
246
                    else:
247
                        return (False,)
248
                else:
249
                    sliceText = text[0:len(result)]
250
                    return (True, text[len(sliceText):len(text)], sliceText)
251
            else:
252
                return (False,)
253
        except Exception as ex:
254
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))       
255

    
256
    '''
257
        @brief      Check if given text is Note No Text (ex : NOTE 1, NOTE 2, ...)
258
        @author     Jeongwoo
259
        @date       2018.04.26
260
        @history    2018.05.16  Jeongwoo    Modify Validator flag
261
    '''
262
    def create_note_no_text(self, textInfo):
263
        item = None
264

    
265
        appDocData = AppDocData.instance()
266
        configs = appDocData.getConfigs('Note No Tag Rule', 'Note No Expression')
267
        if 1 == len(configs) and configs[0].value:
268
            expression = configs[0].value
269
            match = re.search(re.compile(expression), textInfo.getText())
270

    
271
            if match:
272
                configs = appDocData.getConfigs('Note No Tag Rule', 'Note No Symbol Name')
273
                if 1 == len(configs) and configs[0].value:
274
                    symbol_names = configs[0].value.split(',')
275
                    for symbol in appDocData.symbols:
276
                        if symbol.name in symbol_names and symbol.includes(textInfo.center):
277
                            item = QEngineeringNoteItem(symbol=symbol)
278
                            break
279
                else:
280
                    item = QEngineeringNoteItem()
281

    
282
                if item:
283
                    item.setToolTip(textInfo.getText())
284
                    item.setPlainText(textInfo.getText())
285

    
286
        return item
287

    
288
    '''
289
        @brief  check if given text is size text
290
        @author humkyung
291
        @date   2018.05.02
292
    '''
293
    def isSizeText(self, text, delimiter=None):
294
        from NominalPipeSize import NominalPipeSizeTable
295

    
296
        pipe_sizes = NominalPipeSizeTable.instance().pipe_sizes
297

    
298
        tokens = text.upper().split(delimiter) if delimiter is not None else [text]
299
        for token in tokens:
300
            matches = [sizeData for sizeData in pipe_sizes if sizeData.find(token.strip())]
301
            if not matches: return False
302
        
303
        return True
304
    
305
    '''
306
        @brief  check if given text is tag no
307
        @author humkyung
308
        @date   2018.05.03
309
    '''
310
    def isTagNoText(self, text):
311
        from CodeTables import CodeTable
312

    
313
        found = CodeTable.instance('EqpTagNames').find_starts_with(text)
314

    
315
        return True if found else False
316

    
317
    def is_valve_operation_code(self, text):
318
        """
319
        check if given text is valve operation code
320
        """
321
        from CodeTables import CodeTable
322

    
323
        found = CodeTable.instance('ValveOperCodes').find_starts_with(text)
324

    
325
        return True if found else False
326

    
327
    def is_reserved_word(self, text):
328
        """ check if given text is reserved words """
329
        from CodeTables import CodeTable
330

    
331
        found = CodeTable.instance('ReservedWords').find_starts_with(text)
332

    
333
        return True if found else False
클립보드 이미지 추가 (최대 크기: 500 MB)