chiark / gitweb /
Fix for new temperature button name
[cura.git] / Cura / gui / printWindow.py
1 __copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
2
3 import wx
4 import power
5 import time
6 import sys
7 import os
8 import ctypes
9
10 #TODO: This does not belong here!
11 if sys.platform.startswith('win'):
12         def preventComputerFromSleeping(prevent):
13                 """
14                 Function used to prevent the computer from going into sleep mode.
15                 :param prevent: True = Prevent the system from going to sleep from this point on.
16                 :param prevent: False = No longer prevent the system from going to sleep.
17                 """
18                 ES_CONTINUOUS = 0x80000000
19                 ES_SYSTEM_REQUIRED = 0x00000001
20                 #SetThreadExecutionState returns 0 when failed, which is ignored. The function should be supported from windows XP and up.
21                 if prevent:
22                         ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED)
23                 else:
24                         ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS)
25
26 else:
27         def preventComputerFromSleeping(prevent):
28                 #No preventComputerFromSleeping for MacOS and Linux yet.
29                 pass
30
31 class printWindowPlugin(wx.Frame):
32         def __init__(self, parent, printerConnection, filename):
33                 super(printWindowPlugin, self).__init__(parent, -1, style=wx.CLOSE_BOX|wx.CLIP_CHILDREN|wx.CAPTION|wx.SYSTEM_MENU|wx.FRAME_FLOAT_ON_PARENT|wx.MINIMIZE_BOX, title=_("Printing on %s") % (printerConnection.getName()))
34                 self._printerConnection = printerConnection
35                 self._basePath = os.path.dirname(filename)
36                 self._backgroundImage = None
37                 self._colorCommandMap = {}
38                 self._buttonList = []
39                 self._termLog = None
40                 self._termInput = None
41                 self._termHistory = []
42                 self._termHistoryIdx = 0
43                 self._progressBar = None
44                 self._tempGraph = None
45                 self._infoText = None
46                 self._lastUpdateTime = time.time()
47
48                 variables = {
49                         'setImage': self.script_setImage,
50                         'addColorCommand': self.script_addColorCommand,
51                         'addTerminal': self.script_addTerminal,
52                         'addTemperatureGraph': self.script_addTemperatureGraph,
53                         'addProgressbar': self.script_addProgressbar,
54                         'addButton': self.script_addButton,
55                         'addSpinner': self.script_addSpinner,
56                         'addTextButton': self.script_addTextButton,
57
58                         'sendGCode': self.script_sendGCode,
59                         'connect': self.script_connect,
60                         'startPrint': self.script_startPrint,
61                         'pausePrint': self.script_pausePrint,
62                         'cancelPrint': self.script_cancelPrint,
63                         'showErrorLog': self.script_showErrorLog,
64                 }
65                 execfile(filename, variables, variables)
66
67                 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
68                 self.Bind(wx.EVT_PAINT, self.OnDraw)
69                 self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftClick)
70                 self.Bind(wx.EVT_CLOSE, self.OnClose)
71
72                 self._updateButtonStates()
73
74                 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
75
76                 if self._printerConnection.hasActiveConnection() and not self._printerConnection.isActiveConnectionOpen():
77                         self._printerConnection.openActiveConnection()
78                 preventComputerFromSleeping(True)
79
80         def script_setImage(self, guiImage, mapImage):
81                 self._backgroundImage = wx.BitmapFromImage(wx.Image(os.path.join(self._basePath, guiImage)))
82                 self._mapImage = wx.Image(os.path.join(self._basePath, mapImage))
83                 self.SetClientSize(self._mapImage.GetSize())
84
85         def script_addColorCommand(self, r, g, b, command, data = None):
86                 self._colorCommandMap[(r, g, b)] = (command, data)
87
88         def script_addTerminal(self, r, g, b):
89                 x, y, w, h = self._getColoredRect(r, g, b)
90                 if x < 0 or self._termLog is not None:
91                         return
92                 f = wx.Font(8, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
93                 self._termLog = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.TE_DONTWRAP)
94                 self._termLog.SetFont(f)
95                 self._termLog.SetEditable(0)
96                 self._termInput = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER)
97                 self._termInput.SetFont(f)
98
99                 self._termLog.SetPosition((x, y))
100                 self._termLog.SetSize((w, h - self._termInput.GetSize().GetHeight()))
101                 self._termInput.SetPosition((x, y + h - self._termInput.GetSize().GetHeight()))
102                 self._termInput.SetSize((w, self._termInput.GetSize().GetHeight()))
103                 self.Bind(wx.EVT_TEXT_ENTER, self.OnTermEnterLine, self._termInput)
104                 self._termInput.Bind(wx.EVT_CHAR, self.OnTermKey)
105
106         def script_addTemperatureGraph(self, r, g, b):
107                 x, y, w, h = self._getColoredRect(r, g, b)
108                 if x < 0 or self._tempGraph is not None:
109                         return
110                 self._tempGraph = TemperatureGraph(self)
111
112                 self._tempGraph.SetPosition((x, y))
113                 self._tempGraph.SetSize((w, h))
114
115         def script_addProgressbar(self, r, g, b):
116                 x, y, w, h = self._getColoredRect(r, g, b)
117                 if x < 0:
118                         return
119                 self._progressBar = wx.Gauge(self, -1, range=1000)
120
121                 self._progressBar.SetPosition((x, y))
122                 self._progressBar.SetSize((w, h))
123
124         def script_addButton(self, r, g, b, text, command, data = None):
125                 x, y, w, h = self._getColoredRect(r, g, b)
126                 if x < 0:
127                         return
128                 button = wx.Button(self, -1, _(text))
129                 button.SetPosition((x, y))
130                 button.SetSize((w, h))
131                 button.command = command
132                 button.data = data
133                 self._buttonList.append(button)
134                 self.Bind(wx.EVT_BUTTON, lambda e: command(data), button)
135
136         def script_addSpinner(self, r, g, b, command, data):
137                 x, y, w, h = self._getColoredRect(r, g, b)
138                 if x < 0:
139                         return
140
141                 def run_command(spinner):
142                         value = spinner.GetValue()
143                         print "Value (%s) and (%s)" % (spinner.last_value, value)
144                         if spinner.last_value != '' and value != 0:
145                                 spinner.command(spinner.data % value)
146                                 spinner.last_value = value
147
148                 spinner = wx.SpinCtrl(self, -1, style=wx.TE_PROCESS_ENTER)
149                 spinner.SetRange(0, 300)
150                 spinner.SetPosition((x, y))
151                 spinner.SetSize((w, h))
152                 spinner.SetValue(0)
153                 spinner.command = command
154                 spinner.data = data
155                 spinner.last_value = ''
156                 self._buttonList.append(spinner)
157                 self.Bind(wx.EVT_SPINCTRL, lambda e: run_command(spinner), spinner)
158
159         def script_addTextButton(self, r_text, g_text, b_text, r_button, g_button, b_button, button_text, command, data):
160                 x_text, y_text, w_text, h_text = self._getColoredRect(r_text, g_text, b_text)
161                 if x_text < 0:
162                         return
163                 x_button, y_button, w_button, h_button = self._getColoredRect(r_button, g_button, b_button)
164                 if x_button < 0:
165                         return
166                 from wx.lib.intctrl import IntCtrl
167                 text = IntCtrl(self, -1)
168                 text.SetBounds(0, 300)
169                 text.SetPosition((x_text, y_text))
170                 text.SetSize((w_text, h_text))
171                 
172                 button = wx.Button(self, -1, _(button_text))
173                 button.SetPosition((x_button, y_button))
174                 button.SetSize((w_button, h_button))
175                 button.command = command
176                 button.data = data
177                 self._buttonList.append(button)
178                 self.Bind(wx.EVT_BUTTON, lambda e: command(data % text.GetValue()), button)
179
180         def _getColoredRect(self, r, g, b):
181                 for x in xrange(0, self._mapImage.GetWidth()):
182                         for y in xrange(0, self._mapImage.GetHeight()):
183                                 if self._mapImage.GetRed(x, y) == r and self._mapImage.GetGreen(x, y) == g and self._mapImage.GetBlue(x, y) == b:
184                                         w = 0
185                                         while x+w < self._mapImage.GetWidth() and self._mapImage.GetRed(x + w, y) == r and self._mapImage.GetGreen(x + w, y) == g and self._mapImage.GetBlue(x + w, y) == b:
186                                                 w += 1
187                                         h = 0
188                                         while y+h < self._mapImage.GetHeight() and self._mapImage.GetRed(x, y + h) == r and self._mapImage.GetGreen(x, y + h) == g and self._mapImage.GetBlue(x, y + h) == b:
189                                                 h += 1
190                                         return x, y, w, h
191                 print "Failed to find color: ", r, g, b
192                 return -1, -1, 1, 1
193
194         def script_sendGCode(self, data = None):
195                 for line in data.split(';'):
196                         line = line.strip()
197                         if len(line) > 0:
198                                 self._printerConnection.sendCommand(line)
199
200         def script_connect(self, data = None):
201                 self._printerConnection.openActiveConnection()
202
203         def script_startPrint(self, data = None):
204                 self._printerConnection.startPrint()
205
206         def script_cancelPrint(self, e):
207                 self._printerConnection.cancelPrint()
208
209         def script_pausePrint(self, e):
210                 self._printerConnection.pause(not self._printerConnection.isPaused())
211
212         def script_showErrorLog(self, e):
213                 LogWindow(self._printerConnection.getErrorLog())
214
215         def OnEraseBackground(self, e):
216                 pass
217
218         def OnDraw(self, e):
219                 dc = wx.BufferedPaintDC(self, self._backgroundImage)
220
221         def OnLeftClick(self, e):
222                 r = self._mapImage.GetRed(e.GetX(), e.GetY())
223                 g = self._mapImage.GetGreen(e.GetX(), e.GetY())
224                 b = self._mapImage.GetBlue(e.GetX(), e.GetY())
225                 if (r, g, b) in self._colorCommandMap:
226                         command = self._colorCommandMap[(r, g, b)]
227                         command[0](command[1])
228
229         def OnClose(self, e):
230                 if self._printerConnection.hasActiveConnection():
231                         if self._printerConnection.isPrinting():
232                                 pass #TODO: Give warning that the close will kill the print.
233                         self._printerConnection.closeActiveConnection()
234                 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
235                 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
236                 preventComputerFromSleeping(False)
237                 self.Destroy()
238
239         def OnTermEnterLine(self, e):
240                 if not self._printerConnection.isAbleToSendDirectCommand():
241                         return
242                 line = self._termInput.GetValue()
243                 if line == '':
244                         return
245                 self._addTermLog('> %s\n' % (line))
246                 self._printerConnection.sendCommand(line)
247                 self._termHistory.append(line)
248                 self._termHistoryIdx = len(self._termHistory)
249                 self._termInput.SetValue('')
250
251         def OnTermKey(self, e):
252                 if len(self._termHistory) > 0:
253                         if e.GetKeyCode() == wx.WXK_UP:
254                                 self._termHistoryIdx -= 1
255                                 if self._termHistoryIdx < 0:
256                                         self._termHistoryIdx = len(self._termHistory) - 1
257                                 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
258                         if e.GetKeyCode() == wx.WXK_DOWN:
259                                 self._termHistoryIdx -= 1
260                                 if self._termHistoryIdx >= len(self._termHistory):
261                                         self._termHistoryIdx = 0
262                                 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
263                 e.Skip()
264
265         def _addTermLog(self, line):
266                 if self._termLog is not None:
267                         if len(self._termLog.GetValue()) > 10000:
268                                 self._termLog.SetValue(self._termLog.GetValue()[-10000:])
269                         self._termLog.SetInsertionPointEnd()
270                         if type(line) != unicode:
271                                 line = unicode(line, 'utf-8', 'replace')
272                         self._termLog.AppendText(line.encode('utf-8', 'replace'))
273
274         def _updateButtonStates(self):
275                 for button in self._buttonList:
276                         if button.command == self.script_connect:
277                                 button.Show(self._printerConnection.hasActiveConnection())
278                                 button.Enable(not self._printerConnection.isActiveConnectionOpen() and not self._printerConnection.isActiveConnectionOpening())
279                         elif button.command == self.script_pausePrint:
280                                 button.Show(self._printerConnection.hasPause())
281                                 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
282                                         button.Enable(self._printerConnection.isPrinting() or self._printerConnection.isPaused())
283                                 else:
284                                         button.Enable(False)
285                         elif button.command == self.script_startPrint:
286                                 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
287                                         button.Enable(not self._printerConnection.isPrinting())
288                                 else:
289                                         button.Enable(False)
290                         elif button.command == self.script_cancelPrint:
291                                 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
292                                         button.Enable(self._printerConnection.isPrinting())
293                                 else:
294                                         button.Enable(False)
295                         elif button.command == self.script_showErrorLog:
296                                 button.Show(self._printerConnection.isInErrorState())
297                 if self._termInput is not None:
298                         self._termInput.Enable(self._printerConnection.isAbleToSendDirectCommand())
299
300         def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
301                 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
302                 if self._tempGraph is not None:
303                         temp = []
304                         for n in xrange(0, 4):
305                                 t = connection.getTemperature(0)
306                                 if t is not None:
307                                         temp.append(t)
308                                 else:
309                                         break
310                         self._tempGraph.addPoint(temp, [0] * len(temp), connection.getBedTemperature(), 0)
311
312         def __doPrinterConnectionUpdate(self, connection, extraInfo):
313                 t = time.time()
314                 if self._lastUpdateTime + 0.5 > t and extraInfo is None:
315                         return
316                 self._lastUpdateTime = t
317
318                 if extraInfo is not None:
319                         self._addTermLog('< %s\n' % (extraInfo))
320
321                 self._updateButtonStates()
322                 if self._progressBar is not None:
323                         if connection.isPrinting():
324                                 self._progressBar.SetValue(connection.getPrintProgress() * 1000)
325                         else:
326                                 self._progressBar.SetValue(0)
327                 info = connection.getStatusString()
328                 info += '\n'
329                 if self._printerConnection.getTemperature(0) is not None:
330                         info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
331                 if self._printerConnection.getBedTemperature() > 0:
332                         info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
333                 if self._infoText is not None:
334                         self._infoText.SetLabel(info)
335                 else:
336                         self.SetTitle(info.replace('\n', ', '))
337
338 class printWindowBasic(wx.Frame):
339         """
340         Printing window for USB printing, network printing, and any other type of printer connection we can think off.
341         This is only a basic window with minimal information.
342         """
343         def __init__(self, parent, printerConnection):
344                 super(printWindowBasic, self).__init__(parent, -1, style=wx.CLOSE_BOX|wx.CLIP_CHILDREN|wx.CAPTION|wx.SYSTEM_MENU|wx.FRAME_TOOL_WINDOW|wx.FRAME_FLOAT_ON_PARENT, title=_("Printing on %s") % (printerConnection.getName()))
345                 self._printerConnection = printerConnection
346                 self._lastUpdateTime = 0
347
348                 self.SetSizer(wx.BoxSizer())
349                 self.panel = wx.Panel(self)
350                 self.GetSizer().Add(self.panel, 1, flag=wx.EXPAND)
351                 self.sizer = wx.GridBagSizer(2, 2)
352                 self.panel.SetSizer(self.sizer)
353
354                 self.powerWarningText = wx.StaticText(parent=self.panel,
355                         id=-1,
356                         label=_("Your computer is running on battery power.\nConnect your computer to AC power or your print might not finish."),
357                         style=wx.ALIGN_CENTER)
358                 self.powerWarningText.SetBackgroundColour('red')
359                 self.powerWarningText.SetForegroundColour('white')
360                 self.powerManagement = power.PowerManagement()
361                 self.powerWarningTimer = wx.Timer(self)
362                 self.Bind(wx.EVT_TIMER, self.OnPowerWarningChange, self.powerWarningTimer)
363                 self.OnPowerWarningChange(None)
364                 self.powerWarningTimer.Start(10000)
365
366                 self.statsText = wx.StaticText(self.panel, -1, _("InfoLine from printer connection\nInfoLine from dialog\nExtra line\nMore lines for layout\nMore lines for layout\nMore lines for layout"))
367
368                 self.connectButton = wx.Button(self.panel, -1, _("Connect"))
369                 #self.loadButton = wx.Button(self.panel, -1, 'Load')
370                 self.printButton = wx.Button(self.panel, -1, _("Print"))
371                 self.pauseButton = wx.Button(self.panel, -1, _("Pause"))
372                 self.cancelButton = wx.Button(self.panel, -1, _("Cancel print"))
373                 self.errorLogButton = wx.Button(self.panel, -1, _("Error log"))
374                 self.progress = wx.Gauge(self.panel, -1, range=1000)
375
376                 self.sizer.Add(self.powerWarningText, pos=(0, 0), span=(1, 5), flag=wx.EXPAND|wx.BOTTOM, border=5)
377                 self.sizer.Add(self.statsText, pos=(1, 0), span=(1, 5), flag=wx.LEFT, border=5)
378                 self.sizer.Add(self.connectButton, pos=(2, 0))
379                 #self.sizer.Add(self.loadButton, pos=(2,1))
380                 self.sizer.Add(self.printButton, pos=(2, 1))
381                 self.sizer.Add(self.pauseButton, pos=(2, 2))
382                 self.sizer.Add(self.cancelButton, pos=(2, 3))
383                 self.sizer.Add(self.errorLogButton, pos=(2, 4))
384                 self.sizer.Add(self.progress, pos=(3, 0), span=(1, 5), flag=wx.EXPAND)
385
386                 self.Bind(wx.EVT_CLOSE, self.OnClose)
387                 self.connectButton.Bind(wx.EVT_BUTTON, self.OnConnect)
388                 #self.loadButton.Bind(wx.EVT_BUTTON, self.OnLoad)
389                 self.printButton.Bind(wx.EVT_BUTTON, self.OnPrint)
390                 self.pauseButton.Bind(wx.EVT_BUTTON, self.OnPause)
391                 self.cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel)
392                 self.errorLogButton.Bind(wx.EVT_BUTTON, self.OnErrorLog)
393
394                 self.Layout()
395                 self.Fit()
396                 self.Centre()
397
398                 self.progress.SetMinSize(self.progress.GetSize())
399                 self.statsText.SetLabel('\n\n\n\n\n\n')
400                 self._updateButtonStates()
401
402                 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
403
404                 if self._printerConnection.hasActiveConnection() and not self._printerConnection.isActiveConnectionOpen():
405                         self._printerConnection.openActiveConnection()
406                 preventComputerFromSleeping(True)
407
408         def OnPowerWarningChange(self, e):
409                 type = self.powerManagement.get_providing_power_source_type()
410                 if type == power.POWER_TYPE_AC and self.powerWarningText.IsShown():
411                         self.powerWarningText.Hide()
412                         self.panel.Layout()
413                         self.Layout()
414                         self.Fit()
415                         self.Refresh()
416                 elif type != power.POWER_TYPE_AC and not self.powerWarningText.IsShown():
417                         self.powerWarningText.Show()
418                         self.panel.Layout()
419                         self.Layout()
420                         self.Fit()
421                         self.Refresh()
422
423         def OnClose(self, e):
424                 if self._printerConnection.hasActiveConnection():
425                         if self._printerConnection.isPrinting():
426                                 pass #TODO: Give warning that the close will kill the print.
427                         self._printerConnection.closeActiveConnection()
428                 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
429                 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
430                 preventComputerFromSleeping(False)
431                 self.Destroy()
432
433         def OnConnect(self, e):
434                 self._printerConnection.openActiveConnection()
435
436         def OnLoad(self, e):
437                 pass
438
439         def OnPrint(self, e):
440                 self._printerConnection.startPrint()
441
442         def OnCancel(self, e):
443                 self._printerConnection.cancelPrint()
444
445         def OnPause(self, e):
446                 self._printerConnection.pause(not self._printerConnection.isPaused())
447
448         def OnErrorLog(self, e):
449                 LogWindow(self._printerConnection.getErrorLog())
450
451         def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
452                 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
453                 #temp = [connection.getTemperature(0)]
454                 #self.temperatureGraph.addPoint(temp, [0], connection.getBedTemperature(), 0)
455
456         def __doPrinterConnectionUpdate(self, connection, extraInfo):
457                 t = time.time()
458                 if self._lastUpdateTime + 0.5 > t and extraInfo is None:
459                         return
460                 self._lastUpdateTime = t
461
462                 if extraInfo is not None:
463                         self._addTermLog('< %s\n' % (extraInfo))
464
465                 self._updateButtonStates()
466                 if connection.isPrinting():
467                         self.progress.SetValue(connection.getPrintProgress() * 1000)
468                 else:
469                         self.progress.SetValue(0)
470                 info = connection.getStatusString()
471                 info += '\n'
472                 if self._printerConnection.getTemperature(0) is not None:
473                         info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
474                 if self._printerConnection.getBedTemperature() > 0:
475                         info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
476                 info += '\n\n'
477                 self.statsText.SetLabel(info)
478
479         def _updateButtonStates(self):
480                 self.connectButton.Show(self._printerConnection.hasActiveConnection())
481                 self.connectButton.Enable(not self._printerConnection.isActiveConnectionOpen() and not self._printerConnection.isActiveConnectionOpening())
482                 self.pauseButton.Show(self._printerConnection.hasPause())
483                 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
484                         self.printButton.Enable(not self._printerConnection.isPrinting())
485                         self.pauseButton.Enable(self._printerConnection.isPrinting())
486                         self.cancelButton.Enable(self._printerConnection.isPrinting())
487                 else:
488                         self.printButton.Enable(False)
489                         self.pauseButton.Enable(False)
490                         self.cancelButton.Enable(False)
491                 self.errorLogButton.Show(self._printerConnection.isInErrorState())
492
493 class TemperatureGraph(wx.Panel):
494         def __init__(self, parent):
495                 super(TemperatureGraph, self).__init__(parent)
496
497                 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
498                 self.Bind(wx.EVT_SIZE, self.OnSize)
499                 self.Bind(wx.EVT_PAINT, self.OnDraw)
500
501                 self._lastDraw = time.time() - 1.0
502                 self._points = []
503                 self._backBuffer = None
504                 self.addPoint([0]*16, [0]*16, 0, 0)
505
506         def OnEraseBackground(self, e):
507                 pass
508
509         def OnSize(self, e):
510                 if self._backBuffer is None or self.GetSize() != self._backBuffer.GetSize():
511                         self._backBuffer = wx.EmptyBitmap(*self.GetSizeTuple())
512                         self.UpdateDrawing(True)
513
514         def OnDraw(self, e):
515                 dc = wx.BufferedPaintDC(self, self._backBuffer)
516
517         def UpdateDrawing(self, force=False):
518                 now = time.time()
519                 if (not force and now - self._lastDraw < 1.0) or self._backBuffer is None:
520                         return
521                 self._lastDraw = now
522                 dc = wx.MemoryDC()
523                 dc.SelectObject(self._backBuffer)
524                 dc.Clear()
525                 dc.SetFont(wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT))
526                 w, h = self.GetSizeTuple()
527                 bgLinePen = wx.Pen('#A0A0A0')
528                 tempPen = wx.Pen('#FF4040')
529                 tempSPPen = wx.Pen('#FFA0A0')
530                 tempPenBG = wx.Pen('#FFD0D0')
531                 bedTempPen = wx.Pen('#4040FF')
532                 bedTempSPPen = wx.Pen('#A0A0FF')
533                 bedTempPenBG = wx.Pen('#D0D0FF')
534
535                 #Draw the background up to the current temperatures.
536                 x0 = 0
537                 t0 = []
538                 bt0 = 0
539                 tSP0 = 0
540                 btSP0 = 0
541                 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
542                         x1 = int(w - (now - t))
543                         for x in xrange(x0, x1 + 1):
544                                 for n in xrange(0, min(len(t0), len(temp))):
545                                         t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
546                                         dc.SetPen(tempPenBG)
547                                         dc.DrawLine(x, h, x, h - (t * h / 350))
548                                 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
549                                 dc.SetPen(bedTempPenBG)
550                                 dc.DrawLine(x, h, x, h - (bt * h / 350))
551                         t0 = temp
552                         bt0 = bedTemp
553                         tSP0 = tempSP
554                         btSP0 = bedTempSP
555                         x0 = x1 + 1
556
557                 #Draw the grid
558                 for x in xrange(w, 0, -30):
559                         dc.SetPen(bgLinePen)
560                         dc.DrawLine(x, 0, x, h)
561                 tmpNr = 0
562                 for y in xrange(h - 1, 0, -h * 50 / 350):
563                         dc.SetPen(bgLinePen)
564                         dc.DrawLine(0, y, w, y)
565                         dc.DrawText(str(tmpNr), 0, y - dc.GetFont().GetPixelSize().GetHeight())
566                         tmpNr += 50
567                 dc.DrawLine(0, 0, w, 0)
568                 dc.DrawLine(0, 0, 0, h)
569
570                 #Draw the main lines
571                 x0 = 0
572                 t0 = []
573                 bt0 = 0
574                 tSP0 = []
575                 btSP0 = 0
576                 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
577                         x1 = int(w - (now - t))
578                         for x in xrange(x0, x1 + 1):
579                                 for n in xrange(0, min(len(t0), len(temp))):
580                                         t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
581                                         tSP = float(x - x0) / float(x1 - x0 + 1) * (tempSP[n] - tSP0[n]) + tSP0[n]
582                                         dc.SetPen(tempSPPen)
583                                         dc.DrawPoint(x, h - (tSP * h / 350))
584                                         dc.SetPen(tempPen)
585                                         dc.DrawPoint(x, h - (t * h / 350))
586                                 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
587                                 btSP = float(x - x0) / float(x1 - x0 + 1) * (bedTempSP - btSP0) + btSP0
588                                 dc.SetPen(bedTempSPPen)
589                                 dc.DrawPoint(x, h - (btSP * h / 350))
590                                 dc.SetPen(bedTempPen)
591                                 dc.DrawPoint(x, h - (bt * h / 350))
592                         t0 = temp
593                         bt0 = bedTemp
594                         tSP0 = tempSP
595                         btSP0 = bedTempSP
596                         x0 = x1 + 1
597
598                 del dc
599                 self.Refresh(eraseBackground=False)
600                 self.Update()
601
602                 if len(self._points) > 0 and (time.time() - self._points[0][4]) > w + 20:
603                         self._points.pop(0)
604
605         def addPoint(self, temp, tempSP, bedTemp, bedTempSP):
606                 if len(self._points) > 0 and time.time() - self._points[-1][4] < 0.5:
607                         return
608                 for n in xrange(0, len(temp)):
609                         if temp[n] is None:
610                                 temp[n] = 0
611                 for n in xrange(0, len(tempSP)):
612                         if tempSP[n] is None:
613                                 tempSP[n] = 0
614                 if bedTemp is None:
615                         bedTemp = 0
616                 if bedTempSP is None:
617                         bedTempSP = 0
618                 self._points.append((temp[:], tempSP[:], bedTemp, bedTempSP, time.time()))
619                 wx.CallAfter(self.UpdateDrawing)
620
621
622 class LogWindow(wx.Frame):
623         def __init__(self, logText):
624                 super(LogWindow, self).__init__(None, title="Error log")
625                 self.textBox = wx.TextCtrl(self, -1, logText, style=wx.TE_MULTILINE | wx.TE_DONTWRAP | wx.TE_READONLY)
626                 self.SetSize((500, 400))
627                 self.Show(True)