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