aboutsummaryrefslogtreecommitdiffstats
path: root/awlsim/gui/fup/fupwidget.py
blob: 87e0320b05751be5054e7199bd724042081f8137 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# -*- coding: utf-8 -*-
#
# AWL simulator - FUP widget
#
# Copyright 2016-2017 Michael Buesch <m@bues.ch>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#

from __future__ import division, absolute_import, print_function, unicode_literals
from awlsim.common.compat import *

from awlsim.gui.fup.fupdrawwidget import *
from awlsim.gui.fup.fupelemcontainerwidget import *
from awlsim.gui.interfedit.interfwidget import *
from awlsim.gui.editwidget import *
from awlsim.gui.optimizerconfig import *
from awlsim.gui.util import *

from awlsim.fupcompiler import *
from awlsim.awloptimizer.awloptimizer import *


FUP_DEBUG = 0


class FupFactory(XmlFactory):
	FUP_VERSION = 0

	def parser_open(self, tag=None):
		self.inFup = False
		self.inGrids = False
		XmlFactory.parser_open(self, tag)

	def parser_beginTag(self, tag):
		blockTypeEdit = self.fupWidget.interf.blockTypeEdit
		interfModel = self.fupWidget.interf.interfView.model()
		drawWidget = self.fupWidget.edit.draw
		grid = drawWidget.grid
		if self.inFup:
			if self.inGrids:
				if tag.name == "grid":
					self.parser_switchTo(grid.factory(grid=grid))
					return
			else:
				if tag.name == "blockdecl":
					self.parser_switchTo(blockTypeEdit.factory(
						blockTypeWidget=blockTypeEdit))
					return
				if tag.name == "interface":
					self.parser_switchTo(interfModel.factory(
						model=interfModel))
					return
				if tag.name == "grids":
					self.inGrids = True
					return
		else:
			if tag.name == "FUP":
				version = tag.getAttrInt("version")
				zoom = tag.getAttrFloat("zoom", 1.0)
				if version != self.FUP_VERSION:
					raise self.Error("Unsupported FUP version. "
						"Got %d, but expected %d." % (
						version, self.FUP_VERSION))
				drawWidget.zoom = zoom
				self.inFup = True
				return
		XmlFactory.parser_beginTag(self, tag)

	def parser_endTag(self, tag):
		if self.inFup:
			if self.inGrids:
				if tag.name == "grids":
					self.inGrids = False
					return
			else:
				if tag.name == "FUP":
					self.inFup = False
					self.parser_finish()
					return
		XmlFactory.parser_endTag(self, tag)

	def composer_getTags(self):
		childTags = []

		drawWidget = self.fupWidget.edit.draw
		grid = drawWidget.grid

		blockTypeEdit = self.fupWidget.interf.blockTypeEdit
		childTags.extend(blockTypeEdit.factory(
			blockTypeWidget=blockTypeEdit).composer_getTags())

		interfModel = self.fupWidget.interf.interfView.model()
		childTags.extend(interfModel.factory(
			model=interfModel).composer_getTags())

		childTags.append(self.Tag(name="grids",
					  tags=grid.factory(grid=grid).composer_getTags()))

		tags = [
			self.Tag(name="FUP",
				comment="Awlsim FUP/FBD source generated by awlsim-%s" % VERSION_STRING,
				attrs={
					"version"	: str(self.FUP_VERSION),
					"zoom"		: "%.1f" % float(drawWidget.zoom),
				},
				tags=childTags),
		]
		return tags

class FupEditWidgetMenu(QMenu):
	configOpt = Signal()
	showAwlOpt = Signal()
	showAwl = Signal()
	showStlOpt = Signal()
	showStl = Signal()
	genCall = Signal()

	def __init__(self, parent=None):
		QMenu.__init__(self, parent)
		self.addAction("Configure &optimizer...",
			       lambda: self.configOpt.emit())
		self.addAction("Show AWL code (DE, optimized)...",
			       lambda: self.showAwlOpt.emit())
		self.addAction("Show AWL code (DE)...",
			       lambda: self.showAwl.emit())
		self.addAction("Show STL code (EN, optimized)...",
			       lambda: self.showStlOpt.emit())
		self.addAction("Show STL code (EN)...",
			       lambda: self.showStl.emit())
		self.addAction("Generate CALL template...",
			       lambda: self.genCall.emit())

class FupEditWidget(QWidget):
	def __init__(self, parent, interfWidget):
		QWidget.__init__(self, parent)
		self.setLayout(QGridLayout())
		self.layout().setContentsMargins(QMargins())

		self.__splitter = QSplitter(self)

		self.__leftWidget = QWidget(self)
		self.__leftWidget.setLayout(QVBoxLayout())
		self.__leftWidget.layout().setContentsMargins(QMargins())

		self.container = FupElemContainerWidget(self)
		self.__leftWidget.layout().addWidget(self.container)

		self.menu = FupEditWidgetMenu(self)

		self.menuButton = QPushButton("FUP/FBD compiler...", self)
		self.menuButton.setMenu(self.menu)
		self.__leftWidget.layout().addWidget(self.menuButton)

		self.__splitter.addWidget(self.__leftWidget)

		self.draw = FupDrawWidget(self, interfWidget)

		self.__drawScroll = QScrollArea(self)
		self.__drawScroll.setWidget(self.draw)
		self.__splitter.addWidget(self.__drawScroll)

		self.layout().addWidget(self.__splitter, 0, 0)

		self.draw.selectTipChanged.connect(self.__handleMouseTipChange)
		self.draw.moveTipChanged.connect(self.__handleMouseTipChange)

	def __handleMouseTipChange(self, x, y):
		# Scroll the draw area so that the
		# selection or element move is visible.
		self.__drawScroll.ensureVisible(x, y)

class FupWidget(QWidget):
	"""Main FUP/FBD widget."""

	diagramChanged = Signal()

	def __init__(self, parent, getSymTabSourcesFunc):
		QWidget.__init__(self, parent)
		self.setLayout(QGridLayout())

		self.__getSymTabSourcesFunc = getSymTabSourcesFunc
		self.__source = FupSource(name = "Diagram 1")
		self.__needSourceUpdate = True

		self.splitter = QSplitter(Qt.Vertical)

		self.interf = AwlInterfWidget(self)
		self.splitter.addWidget(self.interf)

		self.edit = FupEditWidget(self, self.interf)
		self.splitter.addWidget(self.edit)

		self.layout().addWidget(self.splitter, 0, 0)

		self.interf.contentChanged.connect(self.diagramChanged)
		self.edit.draw.diagramChanged.connect(self.diagramChanged)
		self.edit.menu.configOpt.connect(self.__configureOptimizer)
		self.edit.menu.showAwlOpt.connect(self.__compileAndShowAwlOpt)
		self.edit.menu.showAwl.connect(self.__compileAndShowAwl)
		self.edit.menu.showStlOpt.connect(self.__compileAndShowStlOpt)
		self.edit.menu.showStl.connect(self.__compileAndShowStl)
		self.edit.menu.genCall.connect(self.__generateCallTemplate)
		self.diagramChanged.connect(self.__handleDiagramChange)

	def __handleDiagramChange(self):
		self.__needSourceUpdate = True

	def __updateSource(self):
		# Generate XML
		try:
			xmlBytes = FupFactory(fupWidget=self).compose()
		except FupFactory.Error as e:
			raise AwlSimError("Failed to create FUP source: "
				"%s" % str(e))
		if FUP_DEBUG:
			print("Composed FUP XML:")
			print(xmlBytes.decode(FupFactory.XML_ENCODING))
		self.__source.sourceBytes = xmlBytes
		self.__needSourceUpdate = False

	def getSource(self):
		if self.__needSourceUpdate:
			self.__updateSource()
		return self.__source

	def setSource(self, source):
		self.__source = source.dup()
		self.__source.sourceBytes = b""
		# Parse XML
		if FUP_DEBUG:
			print("Parsing FUP XML:")
			print(source.sourceBytes.decode(FupFactory.XML_ENCODING))
		try:
			factory = FupFactory(fupWidget=self)
			factory.parse(source.sourceBytes)
		except FupFactory.Error as e:
			raise AwlSimError("Failed to parse FUP source: "
				"%s" % str(e))
		self.__needSourceUpdate = True

	def __configureOptimizer(self):
		grid = self.edit.draw.grid
		dlg = OptimizerConfigDialog(
				settingsContainer=grid.optSettingsCont.dup(),
				parent=self)
		if dlg.exec_() == QDialog.Accepted:
			grid.optSettingsCont = dlg.getSettingsContainer()
			self.diagramChanged.emit()

	def __compileAndShow(self, mnemonics, showCall, optimize=False):
		fupSource = self.getSource()
		try:
			symTabSources = self.__getSymTabSourcesFunc()
			optSettCont = None
			if not optimize:
				optSettCont = AwlOptimizerSettingsContainer(globalEnable=False)
			compiler = FupCompiler()
			blockAwlSource = compiler.compile(fupSource=fupSource,
							  symTabSources=symTabSources,
							  mnemonics=mnemonics,
							  optimizerSettingsContainer=optSettCont)
			if showCall:
				callAwlSource = compiler.generateCallTemplate()
		except AwlSimError as e:
			MessageBox.handleAwlSimError(self, "FUP compiler error", e)
			return
		dlg = EditDialog(self, readOnly=True, withHeader=False, withCpuStats=False)
		if showCall:
			title = "FUP/FBD CALL template - %s"
			awlSource = callAwlSource
		else:
			title = "Compiled FUP/FBD diagram - %s"
			awlSource = blockAwlSource
		dlg.setWindowTitle(title % self.__source.name)
		dlg.edit.setSource(awlSource)
		dlg.show()

	def __compileAndShowAwlOpt(self):
		self.__compileAndShow(S7CPUConfig.MNEMONICS_DE, showCall=False, optimize=True)

	def __compileAndShowAwl(self):
		self.__compileAndShow(S7CPUConfig.MNEMONICS_DE, showCall=False, optimize=False)

	def __compileAndShowStlOpt(self):
		self.__compileAndShow(S7CPUConfig.MNEMONICS_EN, showCall=False, optimize=True)

	def __compileAndShowStl(self):
		self.__compileAndShow(S7CPUConfig.MNEMONICS_EN, showCall=False, optimize=False)

	def __generateCallTemplate(self):
		self.__compileAndShow(S7CPUConfig.MNEMONICS_AUTO, showCall=True)
bues.ch cgit interface