chiark / gitweb /
Fix temp graph size being too small
[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 from wx.lib.intctrl import IntCtrl
5 import power
6 import time
7 import sys
8 import os
9 import ctypes
10 import subprocess
11 from Cura.util import resources
12
13 #TODO: This does not belong here!
14 if sys.platform.startswith('win'):
15         def preventComputerFromSleeping(frame, prevent):
16                 """
17                 Function used to prevent the computer from going into sleep mode.
18                 :param prevent: True = Prevent the system from going to sleep from this point on.
19                 :param prevent: False = No longer prevent the system from going to sleep.
20                 """
21                 ES_CONTINUOUS = 0x80000000
22                 ES_SYSTEM_REQUIRED = 0x00000001
23                 ES_AWAYMODE_REQUIRED = 0x00000040
24                 #SetThreadExecutionState returns 0 when failed, which is ignored. The function should be supported from windows XP and up.
25                 if prevent:
26                         # For Vista and up we use ES_AWAYMODE_REQUIRED to prevent a print from failing if the PC does go to sleep
27                         # As it's not supported on XP, we catch the error and fallback to using ES_SYSTEM_REQUIRED only
28                         if ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED) == 0:
29                                 ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED)
30                 else:
31                         ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS)
32
33 elif sys.platform.startswith('darwin'):
34         import objc
35         bundle = objc.initFrameworkWrapper("IOKit",
36         frameworkIdentifier="com.apple.iokit",
37         frameworkPath=objc.pathForFramework("/System/Library/Frameworks/IOKit.framework"),
38         globals=globals())
39         objc.loadBundleFunctions(bundle, globals(), [("IOPMAssertionCreateWithName", b"i@I@o^I")])
40         def preventComputerFromSleeping(frame, prevent):
41                 if prevent:
42                         success, preventComputerFromSleeping.assertionID = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, "Cura is printing", None)
43                         if success != kIOReturnSuccess:
44                                 preventComputerFromSleeping.assertionID = None
45                 else:
46                         if preventComputerFromSleeping.assertionID is not None:
47                                 IOPMAssertionRelease(preventComputerFromSleeping.assertionID)
48                                 preventComputerFromSleeping.assertionID = None
49 else:
50         def preventComputerFromSleeping(frame, prevent):
51                 if os.path.isfile("/usr/bin/xdg-screensaver"):
52                         try:
53                                 cmd = ['xdg-screensaver', 'suspend' if prevent else 'resume', str(frame.GetHandle())]
54                                 subprocess.call(cmd)
55                         except:
56                                 pass
57
58 class printWindowPlugin(wx.Frame):
59         def __init__(self, parent, printerConnection, filename):
60                 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()))
61                 self._printerConnection = printerConnection
62                 self._basePath = os.path.dirname(filename)
63                 self._backgroundImage = None
64                 self._colorCommandMap = {}
65                 self._buttonList = []
66                 self._termLog = None
67                 self._termInput = None
68                 self._termHistory = []
69                 self._termHistoryIdx = 0
70                 self._progressBar = None
71                 self._tempGraph = None
72                 self._infoText = None
73                 self._lastUpdateTime = time.time()
74                 self._isPrinting = False
75
76                 variables = {
77                         'setImage': self.script_setImage,
78                         'addColorCommand': self.script_addColorCommand,
79                         'addTerminal': self.script_addTerminal,
80                         'addTemperatureGraph': self.script_addTemperatureGraph,
81                         'addProgressbar': self.script_addProgressbar,
82                         'addButton': self.script_addButton,
83                         'addSpinner': self.script_addSpinner,
84                         'addTextButton': self.script_addTextButton,
85
86                         'sendGCode': self.script_sendGCode,
87                         'sendMovementGCode': self.script_sendMovementGCode,
88                         'connect': self.script_connect,
89                         'startPrint': self.script_startPrint,
90                         'pausePrint': self.script_pausePrint,
91                         'cancelPrint': self.script_cancelPrint,
92                         'showErrorLog': self.script_showErrorLog,
93                 }
94                 execfile(filename, variables, variables)
95
96                 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
97                 self.Bind(wx.EVT_PAINT, self.OnDraw)
98                 self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftClick)
99                 self.Bind(wx.EVT_CLOSE, self.OnClose)
100
101                 self._updateButtonStates()
102
103                 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
104
105                 if self._printerConnection.hasActiveConnection() and not self._printerConnection.isActiveConnectionOpen():
106                         self._printerConnection.openActiveConnection()
107
108         def script_setImage(self, guiImage, mapImage):
109                 self._backgroundImage = wx.BitmapFromImage(wx.Image(os.path.join(self._basePath, guiImage)))
110                 self._mapImage = wx.Image(os.path.join(self._basePath, mapImage))
111                 self.SetClientSize(self._mapImage.GetSize())
112
113         def script_addColorCommand(self, r, g, b, command, data = None):
114                 self._colorCommandMap[(r, g, b)] = (command, data)
115
116         def script_addTerminal(self, r, g, b):
117                 x, y, w, h = self._getColoredRect(r, g, b)
118                 if x < 0 or self._termLog is not None:
119                         return
120                 f = wx.Font(8, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
121                 self._termLog = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.TE_DONTWRAP)
122                 self._termLog.SetFont(f)
123                 self._termLog.SetEditable(0)
124                 self._termInput = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER)
125                 self._termInput.SetFont(f)
126
127                 self._termLog.SetPosition((x, y))
128                 self._termLog.SetSize((w, h - self._termInput.GetSize().GetHeight()))
129                 self._termInput.SetPosition((x, y + h - self._termInput.GetSize().GetHeight()))
130                 self._termInput.SetSize((w, self._termInput.GetSize().GetHeight()))
131                 self.Bind(wx.EVT_TEXT_ENTER, self.OnTermEnterLine, self._termInput)
132                 self._termInput.Bind(wx.EVT_CHAR, self.OnTermKey)
133
134         def script_addTemperatureGraph(self, r, g, b):
135                 x, y, w, h = self._getColoredRect(r, g, b)
136                 if x < 0 or self._tempGraph is not None:
137                         return
138                 self._tempGraph = TemperatureGraph(self)
139
140                 self._tempGraph.SetPosition((x, y))
141                 self._tempGraph.SetSize((w, h))
142
143         def script_addProgressbar(self, r, g, b):
144                 x, y, w, h = self._getColoredRect(r, g, b)
145                 if x < 0:
146                         return
147                 self._progressBar = wx.Gauge(self, -1, range=1000)
148
149                 self._progressBar.SetPosition((x, y))
150                 self._progressBar.SetSize((w, h))
151
152         def script_addButton(self, r, g, b, text, command, data = None):
153                 x, y, w, h = self._getColoredRect(r, g, b)
154                 if x < 0:
155                         return
156                 button = wx.Button(self, -1, _(text))
157                 button.SetPosition((x, y))
158                 button.SetSize((w, h))
159                 button.command = command
160                 button.data = data
161                 self._buttonList.append(button)
162                 self.Bind(wx.EVT_BUTTON, lambda e: command(data), button)
163
164         def script_addSpinner(self, r, g, b, command, data):
165                 x, y, w, h = self._getColoredRect(r, g, b)
166                 if x < 0:
167                         return
168
169                 def run_command(spinner):
170                         value = spinner.GetValue()
171                         print "Value (%s) and (%s)" % (spinner.last_value, value)
172                         if spinner.last_value != '' and value != 0:
173                                 spinner.command(spinner.data % value)
174                                 spinner.last_value = value
175
176                 spinner = wx.SpinCtrl(self, -1, style=wx.TE_PROCESS_ENTER)
177                 spinner.SetRange(0, 300)
178                 spinner.SetPosition((x, y))
179                 spinner.SetSize((w, h))
180                 spinner.SetValue(0)
181                 spinner.command = command
182                 spinner.data = data
183                 spinner.last_value = ''
184                 self._buttonList.append(spinner)
185                 self.Bind(wx.EVT_SPINCTRL, lambda e: run_command(spinner), spinner)
186
187         def script_addTextButton(self, r_text, g_text, b_text, r_button, g_button, b_button, button_text, command, data):
188                 x_text, y_text, w_text, h_text = self._getColoredRect(r_text, g_text, b_text)
189                 if x_text < 0:
190                         return
191                 x_button, y_button, w_button, h_button = self._getColoredRect(r_button, g_button, b_button)
192                 if x_button < 0:
193                         return
194                 from wx.lib.intctrl import IntCtrl
195                 text = IntCtrl(self, -1)
196                 text.SetBounds(0, 300)
197                 text.SetPosition((x_text, y_text))
198                 text.SetSize((w_text, h_text))
199                 
200                 button = wx.Button(self, -1, _(button_text))
201                 button.SetPosition((x_button, y_button))
202                 button.SetSize((w_button, h_button))
203                 button.command = command
204                 button.data = data
205                 self._buttonList.append(button)
206                 self.Bind(wx.EVT_BUTTON, lambda e: command(data % text.GetValue()), button)
207
208         def _getColoredRect(self, r, g, b):
209                 for x in xrange(0, self._mapImage.GetWidth()):
210                         for y in xrange(0, self._mapImage.GetHeight()):
211                                 if self._mapImage.GetRed(x, y) == r and self._mapImage.GetGreen(x, y) == g and self._mapImage.GetBlue(x, y) == b:
212                                         w = 0
213                                         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:
214                                                 w += 1
215                                         h = 0
216                                         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:
217                                                 h += 1
218                                         return x, y, w, h
219                 print "Failed to find color: ", r, g, b
220                 return -1, -1, 1, 1
221
222         def script_sendGCode(self, data = None):
223                 for line in data.split(';'):
224                         line = line.strip()
225                         if len(line) > 0:
226                                 self._printerConnection.sendCommand(line)
227
228         def script_sendMovementGCode(self, data = None):
229                 if not self._printerConnection.isPaused() and not self._printerConnection.isPrinting():
230                         self.script_sendGCode(data)
231
232         def script_connect(self, data = None):
233                 self._printerConnection.openActiveConnection()
234
235         def script_startPrint(self, data = None):
236                 if self._printerConnection.isPrinting() or self._printerConnection.isPaused():
237                         self._printerConnection.pause(not self._printerConnection.isPaused())
238                 else:
239                         self._printerConnection.startPrint()
240
241         def script_cancelPrint(self, e):
242                 self._printerConnection.cancelPrint()
243
244         def script_pausePrint(self, e):
245                 self._printerConnection.pause(not self._printerConnection.isPaused())
246
247         def script_showErrorLog(self, e):
248                 LogWindow(self._printerConnection.getErrorLog())
249
250         def OnEraseBackground(self, e):
251                 pass
252
253         def OnDraw(self, e):
254                 dc = wx.BufferedPaintDC(self, self._backgroundImage)
255
256         def OnLeftClick(self, e):
257                 r = self._mapImage.GetRed(e.GetX(), e.GetY())
258                 g = self._mapImage.GetGreen(e.GetX(), e.GetY())
259                 b = self._mapImage.GetBlue(e.GetX(), e.GetY())
260                 if (r, g, b) in self._colorCommandMap:
261                         command = self._colorCommandMap[(r, g, b)]
262                         command[0](command[1])
263
264         def OnClose(self, e):
265                 if self._printerConnection.hasActiveConnection():
266                         if self._printerConnection.isPrinting() or self._printerConnection.isPaused():
267                                 pass #TODO: Give warning that the close will kill the print.
268                         self._printerConnection.closeActiveConnection()
269                 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
270                 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
271                 preventComputerFromSleeping(self, False)
272                 self._printerConnection.cancelPrint()
273                 self.Destroy()
274
275         def OnTermEnterLine(self, e):
276                 if not self._printerConnection.isAbleToSendDirectCommand():
277                         return
278                 line = self._termInput.GetValue()
279                 if line == '':
280                         return
281                 self._addTermLog('> %s\n' % (line))
282                 self._printerConnection.sendCommand(line)
283                 self._termHistory.append(line)
284                 self._termHistoryIdx = len(self._termHistory)
285                 self._termInput.SetValue('')
286
287         def OnTermKey(self, e):
288                 if len(self._termHistory) > 0:
289                         if e.GetKeyCode() == wx.WXK_UP:
290                                 self._termHistoryIdx -= 1
291                                 if self._termHistoryIdx < 0:
292                                         self._termHistoryIdx = len(self._termHistory) - 1
293                                 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
294                         if e.GetKeyCode() == wx.WXK_DOWN:
295                                 self._termHistoryIdx -= 1
296                                 if self._termHistoryIdx >= len(self._termHistory):
297                                         self._termHistoryIdx = 0
298                                 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
299                 e.Skip()
300
301         def _addTermLog(self, line):
302                 if self._termLog is not None:
303                         if len(self._termLog.GetValue()) > 10000:
304                                 self._termLog.SetValue(self._termLog.GetValue()[-10000:])
305                         self._termLog.SetInsertionPointEnd()
306                         if type(line) != unicode:
307                                 line = unicode(line, 'utf-8', 'replace')
308                         self._termLog.AppendText(line.encode('utf-8', 'replace'))
309
310         def _updateButtonStates(self):
311                 hasPauseButton = False
312                 for button in self._buttonList:
313                         if button.command == self.script_pausePrint:
314                                 hasPauseButton = True
315                                 break
316
317                 for button in self._buttonList:
318                         if button.command == self.script_connect:
319                                 button.Show(self._printerConnection.hasActiveConnection())
320                                 button.Enable(not self._printerConnection.isActiveConnectionOpen() and \
321                                                           not self._printerConnection.isActiveConnectionOpening())
322                         elif button.command == self.script_pausePrint:
323                                 button.Show(self._printerConnection.hasPause())
324                                 if not self._printerConnection.hasActiveConnection() or \
325                                    self._printerConnection.isActiveConnectionOpen():
326                                         button.Enable(self._printerConnection.isPrinting() or \
327                                                                   self._printerConnection.isPaused())
328                                         if self._printerConnection.isPaused():
329                                                 button.SetLabel(_("Resume"))
330                                         else:
331                                                 button.SetLabel(_("Pause"))
332                                 else:
333                                         button.Enable(False)
334                         elif button.command == self.script_startPrint:
335                                 if hasPauseButton or not self._printerConnection.hasPause():
336                                         if not self._printerConnection.hasActiveConnection() or \
337                                            self._printerConnection.isActiveConnectionOpen():
338                                                         button.Enable(not self._printerConnection.isPrinting() and \
339                                                                                   not self._printerConnection.isPaused())
340                                         else:
341                                                 button.Enable(False)
342                                 else:
343                                         if not self._printerConnection.hasActiveConnection() or \
344                                            self._printerConnection.isActiveConnectionOpen():
345                                                 if self._printerConnection.isPrinting():
346                                                         button.SetLabel(_("Pause"))
347                                                 else:
348                                                         if self._printerConnection.isPaused():
349                                                                 button.SetLabel(_("Resume"))
350                                                         else:
351                                                                 button.SetLabel(_("Print"))
352                                                 button.Enable(True)
353                                         else:
354                                                 button.Enable(False)
355                         elif button.command == self.script_cancelPrint:
356                                 if not self._printerConnection.hasActiveConnection() or \
357                                    self._printerConnection.isActiveConnectionOpen():
358                                         button.Enable(self._printerConnection.isPrinting() or \
359                                                                   self._printerConnection.isPaused())
360                                 else:
361                                         button.Enable(False)
362                         elif button.command == self.script_showErrorLog:
363                                 button.Show(self._printerConnection.isInErrorState())
364                 if self._termInput is not None:
365                         self._termInput.Enable(self._printerConnection.isAbleToSendDirectCommand())
366
367         def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
368                 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
369                 if self._tempGraph is not None:
370                         temp = []
371                         for n in xrange(0, 4):
372                                 t = connection.getTemperature(0)
373                                 if t is not None:
374                                         temp.append(t)
375                                 else:
376                                         break
377                         self._tempGraph.addPoint(temp, [0] * len(temp), connection.getBedTemperature(), 0)
378
379         def __doPrinterConnectionUpdate(self, connection, extraInfo):
380                 t = time.time()
381                 if self._lastUpdateTime + 0.5 > t and extraInfo is None:
382                         return
383                 self._lastUpdateTime = t
384
385                 if extraInfo is not None and len(extraInfo) > 0:
386                         self._addTermLog('< %s\n' % (extraInfo))
387
388                 self._updateButtonStates()
389                 isPrinting = connection.isPrinting() or connection.isPaused()
390                 if self._progressBar is not None:
391                         if isPrinting:
392                                 self._progressBar.SetValue(connection.getPrintProgress() * 1000)
393                         else:
394                                 self._progressBar.SetValue(0)
395                 info = connection.getStatusString()
396                 info += '\n'
397                 if self._printerConnection.getTemperature(0) is not None:
398                         info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
399                 if self._printerConnection.getBedTemperature() > 0:
400                         info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
401                 if self._infoText is not None:
402                         self._infoText.SetLabel(info)
403                 else:
404                         self.SetTitle(info.replace('\n', ', '))
405                 if isPrinting != self._isPrinting:
406                         self._isPrinting = isPrinting
407                         preventComputerFromSleeping(self, self._isPrinting)
408
409 class printWindowBasic(wx.Frame):
410         """
411         Printing window for USB printing, network printing, and any other type of printer connection we can think off.
412         This is only a basic window with minimal information.
413         """
414         def __init__(self, parent, printerConnection):
415                 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()))
416                 self._printerConnection = printerConnection
417                 self._lastUpdateTime = 0
418                 self._isPrinting = False
419
420                 self.SetSizer(wx.BoxSizer())
421                 self.panel = wx.Panel(self)
422                 self.GetSizer().Add(self.panel, 1, flag=wx.EXPAND)
423                 self.sizer = wx.GridBagSizer(2, 2)
424                 self.panel.SetSizer(self.sizer)
425
426                 self.powerWarningText = wx.StaticText(parent=self.panel,
427                         id=-1,
428                         label=_("Your computer is running on battery power.\nConnect your computer to AC power or your print might not finish."),
429                         style=wx.ALIGN_CENTER)
430                 self.powerWarningText.SetBackgroundColour('red')
431                 self.powerWarningText.SetForegroundColour('white')
432                 self.powerManagement = power.PowerManagement()
433                 self.powerWarningTimer = wx.Timer(self)
434                 self.Bind(wx.EVT_TIMER, self.OnPowerWarningChange, self.powerWarningTimer)
435                 self.OnPowerWarningChange(None)
436                 self.powerWarningTimer.Start(10000)
437
438                 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"))
439
440                 self.connectButton = wx.Button(self.panel, -1, _("Connect"))
441                 #self.loadButton = wx.Button(self.panel, -1, 'Load')
442                 self.printButton = wx.Button(self.panel, -1, _("Print"))
443                 self.pauseButton = wx.Button(self.panel, -1, _("Pause"))
444                 self.cancelButton = wx.Button(self.panel, -1, _("Cancel print"))
445                 self.errorLogButton = wx.Button(self.panel, -1, _("Error log"))
446                 self.progress = wx.Gauge(self.panel, -1, range=1000)
447
448                 self.sizer.Add(self.powerWarningText, pos=(0, 0), span=(1, 5), flag=wx.EXPAND|wx.BOTTOM, border=5)
449                 self.sizer.Add(self.statsText, pos=(1, 0), span=(1, 5), flag=wx.LEFT, border=5)
450                 self.sizer.Add(self.connectButton, pos=(2, 0))
451                 #self.sizer.Add(self.loadButton, pos=(2,1))
452                 self.sizer.Add(self.printButton, pos=(2, 1))
453                 self.sizer.Add(self.pauseButton, pos=(2, 2))
454                 self.sizer.Add(self.cancelButton, pos=(2, 3))
455                 self.sizer.Add(self.errorLogButton, pos=(2, 4))
456                 self.sizer.Add(self.progress, pos=(3, 0), span=(1, 5), flag=wx.EXPAND)
457
458                 self.Bind(wx.EVT_CLOSE, self.OnClose)
459                 self.connectButton.Bind(wx.EVT_BUTTON, self.OnConnect)
460                 #self.loadButton.Bind(wx.EVT_BUTTON, self.OnLoad)
461                 self.printButton.Bind(wx.EVT_BUTTON, self.OnPrint)
462                 self.pauseButton.Bind(wx.EVT_BUTTON, self.OnPause)
463                 self.cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel)
464                 self.errorLogButton.Bind(wx.EVT_BUTTON, self.OnErrorLog)
465
466                 self.Layout()
467                 self.Fit()
468                 self.Centre()
469
470                 self.progress.SetMinSize(self.progress.GetSize())
471                 self.statsText.SetLabel('\n\n\n\n\n\n')
472                 self._updateButtonStates()
473
474                 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
475
476                 if self._printerConnection.hasActiveConnection() and not self._printerConnection.isActiveConnectionOpen():
477                         self._printerConnection.openActiveConnection()
478
479         def OnPowerWarningChange(self, e):
480                 type = self.powerManagement.get_providing_power_source_type()
481                 if type == power.POWER_TYPE_AC and self.powerWarningText.IsShown():
482                         self.powerWarningText.Hide()
483                         self.panel.Layout()
484                         self.Layout()
485                         self.Fit()
486                         self.Refresh()
487                 elif type != power.POWER_TYPE_AC and not self.powerWarningText.IsShown():
488                         self.powerWarningText.Show()
489                         self.panel.Layout()
490                         self.Layout()
491                         self.Fit()
492                         self.Refresh()
493
494         def OnClose(self, e):
495                 if self._printerConnection.hasActiveConnection():
496                         if self._printerConnection.isPrinting() or self._printerConnection.isPaused():
497                                 pass #TODO: Give warning that the close will kill the print.
498                         self._printerConnection.closeActiveConnection()
499                 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
500                 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
501                 preventComputerFromSleeping(self, False)
502                 self.Destroy()
503
504         def OnConnect(self, e):
505                 self._printerConnection.openActiveConnection()
506
507         def OnLoad(self, e):
508                 pass
509
510         def OnPrint(self, e):
511                 self._printerConnection.startPrint()
512
513         def OnCancel(self, e):
514                 self._printerConnection.cancelPrint()
515
516         def OnPause(self, e):
517                 self._printerConnection.pause(not self._printerConnection.isPaused())
518
519         def OnErrorLog(self, e):
520                 LogWindow(self._printerConnection.getErrorLog())
521
522         def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
523                 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
524                 #temp = [connection.getTemperature(0)]
525                 #self.temperatureGraph.addPoint(temp, [0], connection.getBedTemperature(), 0)
526
527         def __doPrinterConnectionUpdate(self, connection, extraInfo):
528                 now = time.time()
529                 if self._lastUpdateTime + 0.5 > now and extraInfo is None:
530                         return
531                 self._lastUpdateTime = now
532
533                 if extraInfo is not None and len(extraInfo) > 0:
534                         self._addTermLog('< %s\n' % (extraInfo))
535
536                 self._updateButtonStates()
537                 onGoingPrint = connection.isPrinting() or connection.isPaused()
538                 if onGoingPrint:
539                         self.progress.SetValue(connection.getPrintProgress() * 1000)
540                 else:
541                         self.progress.SetValue(0)
542                 info = connection.getStatusString()
543                 info += '\n'
544                 if self._printerConnection.getTemperature(0) is not None:
545                         info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
546                 if self._printerConnection.getBedTemperature() > 0:
547                         info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
548                 info += '\n\n'
549                 self.statsText.SetLabel(info)
550                 if onGoingPrint != self._isPrinting:
551                         self._isPrinting = onGoingPrint
552                         preventComputerFromSleeping(self, self._isPrinting)
553
554         def _addTermLog(self, msg):
555                 pass
556
557         def _updateButtonStates(self):
558                 self.connectButton.Show(self._printerConnection.hasActiveConnection())
559                 self.connectButton.Enable(not self._printerConnection.isActiveConnectionOpen() and not self._printerConnection.isActiveConnectionOpening())
560                 self.pauseButton.Show(self._printerConnection.hasPause())
561                 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
562                         self.printButton.Enable(not self._printerConnection.isPrinting() and \
563                                                                         not self._printerConnection.isPaused())
564                         self.pauseButton.Enable(self._printerConnection.isPrinting())
565                         self.cancelButton.Enable(self._printerConnection.isPrinting())
566                 else:
567                         self.printButton.Enable(False)
568                         self.pauseButton.Enable(False)
569                         self.cancelButton.Enable(False)
570                 self.errorLogButton.Show(self._printerConnection.isInErrorState())
571
572 class printWindowAdvanced(wx.Frame):
573         def __init__(self, parent, printerConnection):
574                 super(printWindowAdvanced, 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()))
575                 self._printerConnection = printerConnection
576                 self._lastUpdateTime = time.time()
577                 self._isPrinting = False
578
579                 self.SetSizer(wx.BoxSizer(wx.VERTICAL))
580                 self.toppanel = wx.Panel(self)
581                 self.topsizer = wx.GridBagSizer(2, 2)
582                 self.toppanel.SetSizer(self.topsizer)
583                 self.toppanel.SetBackgroundColour(wx.WHITE)
584                 self.topsizer.SetEmptyCellSize((125, 1))
585                 self.panel = wx.Panel(self)
586                 self.sizer = wx.GridBagSizer(2, 2)
587                 self.sizer.SetEmptyCellSize((125, 1))
588                 self.panel.SetSizer(self.sizer)
589                 self.panel.SetBackgroundColour(wx.WHITE)
590                 self.GetSizer().Add(self.toppanel, 0, flag=wx.EXPAND)
591                 self.GetSizer().Add(self.panel, 1, flag=wx.EXPAND)
592
593                 self._fullscreenTemperature = None
594                 self._termHistory = []
595                 self._termHistoryIdx = 0
596
597                 self._mapImage = wx.Image(resources.getPathForImage('print-window-map.png'))
598                 self._colorCommandMap = {}
599
600                 # Move X
601                 self._addMovementCommand(0, 0, 255, self._moveX, 100)
602                 self._addMovementCommand(0, 0, 240, self._moveX, 10)
603                 self._addMovementCommand(0, 0, 220, self._moveX, 1)
604                 self._addMovementCommand(0, 0, 200, self._moveX, 0.1)
605                 self._addMovementCommand(0, 0, 180, self._moveX, -0.1)
606                 self._addMovementCommand(0, 0, 160, self._moveX, -1)
607                 self._addMovementCommand(0, 0, 140, self._moveX, -10)
608                 self._addMovementCommand(0, 0, 120, self._moveX, -100)
609
610                 # Move Y
611                 self._addMovementCommand(0, 255, 0, self._moveY, -100)
612                 self._addMovementCommand(0, 240, 0, self._moveY, -10)
613                 self._addMovementCommand(0, 220, 0, self._moveY, -1)
614                 self._addMovementCommand(0, 200, 0, self._moveY, -0.1)
615                 self._addMovementCommand(0, 180, 0, self._moveY, 0.1)
616                 self._addMovementCommand(0, 160, 0, self._moveY, 1)
617                 self._addMovementCommand(0, 140, 0, self._moveY, 10)
618                 self._addMovementCommand(0, 120, 0, self._moveY, 100)
619
620                 # Move Z
621                 self._addMovementCommand(255, 0, 0, self._moveZ, 10)
622                 self._addMovementCommand(220, 0, 0, self._moveZ, 1)
623                 self._addMovementCommand(200, 0, 0, self._moveZ, 0.1)
624                 self._addMovementCommand(180, 0, 0, self._moveZ, -0.1)
625                 self._addMovementCommand(160, 0, 0, self._moveZ, -1)
626                 self._addMovementCommand(140, 0, 0, self._moveZ, -10)
627
628                 # Extrude/Retract
629                 self._addMovementCommand(255, 80, 0, self._moveE, 10)
630                 self._addMovementCommand(255, 180, 0, self._moveE, -10)
631
632                 # Home
633                 self._addMovementCommand(255, 255, 0, self._homeXYZ, None)
634                 self._addMovementCommand(240, 255, 0, self._homeXYZ, "X")
635                 self._addMovementCommand(220, 255, 0, self._homeXYZ, "Y")
636                 self._addMovementCommand(200, 255, 0, self._homeXYZ, "Z")
637
638                 self.powerWarningText = wx.StaticText(parent=self.toppanel,
639                         id=-1,
640                         label=_("Your computer is running on battery power.\nConnect your computer to AC power or your print might not finish."),
641                         style=wx.ALIGN_CENTER)
642                 self.powerWarningText.SetBackgroundColour('red')
643                 self.powerWarningText.SetForegroundColour('white')
644                 self.powerManagement = power.PowerManagement()
645                 self.powerWarningTimer = wx.Timer(self)
646                 self.Bind(wx.EVT_TIMER, self.OnPowerWarningChange, self.powerWarningTimer)
647                 self.OnPowerWarningChange(None)
648                 self.powerWarningTimer.Start(10000)
649
650                 self.connectButton = wx.Button(self.toppanel, -1, _("Connect"), size=(125, 30))
651                 self.printButton = wx.Button(self.toppanel, -1, _("Print"), size=(125, 30))
652                 self.cancelButton = wx.Button(self.toppanel, -1, _("Cancel"), size=(125, 30))
653                 self.errorLogButton = wx.Button(self.toppanel, -1, _("Error log"), size=(125, 30))
654                 self.motorsOffButton = wx.Button(self.toppanel, -1, _("Motors off"), size=(125, 30))
655                 self.movementBitmap = wx.StaticBitmap(self.panel, -1, wx.BitmapFromImage(wx.Image(
656                                 resources.getPathForImage('print-window.png'))), (0, 0))
657                 self.temperatureBitmap = wx.StaticBitmap(self.panel, -1, wx.BitmapFromImage(wx.Image(
658                                 resources.getPathForImage('print-window-temperature.png'))), (0, 0))
659                 self.temperatureField = TemperatureField(self.panel, self._setHotendTemperature)
660                 self.temperatureBedBitmap = wx.StaticBitmap(self.panel, -1, wx.BitmapFromImage(wx.Image(
661                                 resources.getPathForImage('print-window-temperature-bed.png'))), (0, 0))
662                 self.temperatureBedField = TemperatureField(self.panel, self._setBedTemperature)
663                 self.temperatureGraph = TemperatureGraph(self.panel)
664                 self.temperatureGraph.SetMinSize((250, 100))
665                 self.progress = wx.Gauge(self.panel, -1, range=1000)
666
667                 f = wx.Font(8, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
668                 self._termLog = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE | wx.TE_DONTWRAP)
669                 self._termLog.SetFont(f)
670                 self._termLog.SetEditable(0)
671                 self._termLog.SetMinSize((385, -1))
672                 self._termInput = wx.TextCtrl(self.panel, style=wx.TE_PROCESS_ENTER)
673                 self._termInput.SetFont(f)
674
675                 self.Bind(wx.EVT_TEXT_ENTER, self.OnTermEnterLine, self._termInput)
676                 self._termInput.Bind(wx.EVT_CHAR, self.OnTermKey)
677
678                 self.topsizer.Add(self.powerWarningText, pos=(0, 0), span=(1, 6), flag=wx.EXPAND|wx.BOTTOM, border=5)
679                 self.topsizer.Add(self.connectButton, pos=(1, 0), flag=wx.LEFT, border=2)
680                 self.topsizer.Add(self.printButton, pos=(1, 1), flag=wx.LEFT, border=2)
681                 self.topsizer.Add(self.cancelButton, pos=(1, 2), flag=wx.LEFT, border=2)
682                 self.topsizer.Add(self.errorLogButton, pos=(1, 4), flag=wx.LEFT, border=2)
683                 self.topsizer.Add(self.motorsOffButton, pos=(1, 5), flag=wx.LEFT|wx.RIGHT, border=2)
684                 self.sizer.Add(self.movementBitmap, pos=(0, 0), span=(2, 3))
685                 self.sizer.Add(self.temperatureGraph, pos=(2, 0), span=(4, 2), flag=wx.EXPAND)
686                 self.sizer.Add(self.temperatureBitmap, pos=(2, 2))
687                 self.sizer.Add(self.temperatureField, pos=(3, 2))
688                 self.sizer.Add(self.temperatureBedBitmap, pos=(4, 2))
689                 self.sizer.Add(self.temperatureBedField, pos=(5, 2))
690                 self.sizer.Add(self._termLog, pos=(0, 3), span=(5, 3), flag=wx.EXPAND|wx.RIGHT, border=5)
691                 self.sizer.Add(self._termInput, pos=(5, 3), span=(1, 3), flag=wx.EXPAND|wx.RIGHT, border=5)
692                 self.sizer.Add(self.progress, pos=(6, 0), span=(1, 6), flag=wx.EXPAND|wx.BOTTOM)
693
694                 self.Bind(wx.EVT_SIZE, self.OnSize)
695                 self.Bind(wx.EVT_CLOSE, self.OnClose)
696                 self.movementBitmap.Bind(wx.EVT_LEFT_DOWN, self.OnMovementClick)
697                 self.temperatureGraph.Bind(wx.EVT_LEFT_UP, self.OnTemperatureClick)
698                 self.connectButton.Bind(wx.EVT_BUTTON, self.OnConnect)
699                 self.printButton.Bind(wx.EVT_BUTTON, self.OnPrint)
700                 self.cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel)
701                 self.errorLogButton.Bind(wx.EVT_BUTTON, self.OnErrorLog)
702                 self.motorsOffButton.Bind(wx.EVT_BUTTON, self.OnMotorsOff)
703
704                 self.Layout()
705                 self.Fit()
706                 self.Refresh()
707                 self.progress.SetMinSize(self.progress.GetSize())
708                 self._updateButtonStates()
709
710                 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
711
712                 if self._printerConnection.hasActiveConnection() and \
713                    not self._printerConnection.isActiveConnectionOpen():
714                         self._printerConnection.openActiveConnection()
715
716         def OnSize(self, e):
717                 # HACK ALERT: This is needed for some reason otherwise the window
718                 # will be bigger than it should be until a power warning change
719                 self.Layout()
720                 self.Fit()
721                 e.Skip()
722
723         def OnClose(self, e):
724                 if self._printerConnection.hasActiveConnection():
725                         if self._printerConnection.isPrinting() or self._printerConnection.isPaused():
726                                 pass #TODO: Give warning that the close will kill the print.
727                         self._printerConnection.closeActiveConnection()
728                 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
729                 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
730                 preventComputerFromSleeping(self, False)
731                 self._printerConnection.cancelPrint()
732                 self.Destroy()
733
734         def OnPowerWarningChange(self, e):
735                 type = self.powerManagement.get_providing_power_source_type()
736                 if type == power.POWER_TYPE_AC and self.powerWarningText.IsShown():
737                         self.powerWarningText.Hide()
738                         self.toppanel.Layout()
739                         self.Layout()
740                         self.Fit()
741                         self.Refresh()
742                 elif type != power.POWER_TYPE_AC and not self.powerWarningText.IsShown():
743                         self.powerWarningText.Show()
744                         self.toppanel.Layout()
745                         self.Layout()
746                         self.Fit()
747                         self.Refresh()
748
749         def OnConnect(self, e):
750                 self._printerConnection.openActiveConnection()
751
752         def OnPrint(self, e):
753                 if self._printerConnection.isPrinting() or self._printerConnection.isPaused():
754                         self._printerConnection.pause(not self._printerConnection.isPaused())
755                 else:
756                         self._printerConnection.startPrint()
757
758         def OnCancel(self, e):
759                 self._printerConnection.cancelPrint()
760
761         def OnErrorLog(self, e):
762                 LogWindow(self._printerConnection.getErrorLog())
763
764         def OnMotorsOff(self, e):
765                 self._printerConnection.sendCommand("M18")
766
767         def GetMapRGB(self, x, y):
768                 r = self._mapImage.GetRed(x, y)
769                 g = self._mapImage.GetGreen(x, y)
770                 b = self._mapImage.GetBlue(x, y)
771                 return (r, g, b)
772
773         def OnMovementClick(self, e):
774                 (r, g, b) = self.GetMapRGB(e.GetX(), e.GetY())
775                 if (r, g, b) in self._colorCommandMap:
776                         command = self._colorCommandMap[(r, g, b)]
777                         command[0](command[1])
778
779         def _addMovementCommand(self, r, g, b, command, step):
780                 self._colorCommandMap[(r, g, b)] = (command, step)
781
782         def _moveXYZE(self, motor, step, feedrate):
783                 if (not self._printerConnection.hasActiveConnection() or \
784                         self._printerConnection.isActiveConnectionOpen()) and \
785                         (not self._printerConnection.isPaused() and \
786                          not self._printerConnection.isPrinting()):
787                         self._printerConnection.sendCommand("G91")
788                         self._printerConnection.sendCommand("G1 %s%.1f F%d" % (motor, step, feedrate))
789                         self._printerConnection.sendCommand("G90")
790
791         def _moveX(self, step):
792                 self._moveXYZE("X", step, 2000)
793
794         def _moveY(self, step):
795                 self._moveXYZE("Y", step, 2000)
796
797         def _moveZ(self, step):
798                 self._moveXYZE("Z", step, 200)
799
800         def _moveE(self, step):
801                 self._moveXYZE("E", step, 120)
802
803         def _homeXYZ(self, direction):
804                 if not self._printerConnection.isPaused() and not self._printerConnection.isPrinting():
805                         if direction is None:
806                                 self._printerConnection.sendCommand("G28")
807                         else:
808                                 self._printerConnection.sendCommand("G28 %s0" % direction)
809
810         def _setHotendTemperature(self, value):
811                 self._printerConnection.sendCommand("M104 S%d" % value)
812
813         def _setBedTemperature(self, value):
814                 self._printerConnection.sendCommand("M140 S%d" % value)
815
816         def OnTemperatureClick(self, e):
817                 wx.CallAfter(self.ToggleFullScreenTemperature)
818
819         def ToggleFullScreenTemperature(self):
820                 sizer = self.GetSizer()
821                 if self._fullscreenTemperature:
822                         self._fullscreenTemperature.Show(False)
823                         sizer.Detach(self._fullscreenTemperature)
824                         self._fullscreenTemperature.Destroy()
825                         self._fullscreenTemperature = None
826                         self.panel.Show(True)
827                 else:
828                         self._fullscreenTemperature = self.temperatureGraph.Clone(self)
829                         self._fullscreenTemperature.Bind(wx.EVT_LEFT_UP, self.OnTemperatureClick)
830                         self._fullscreenTemperature.SetMinSize(self.panel.GetSize())
831                         sizer.Add(self._fullscreenTemperature, 1, flag=wx.EXPAND)
832                         self.panel.Show(False)
833                 self.Layout()
834                 self.Refresh()
835
836         def OnTermEnterLine(self, e):
837                 if not self._printerConnection.isAbleToSendDirectCommand():
838                         return
839                 line = self._termInput.GetValue()
840                 if line == '':
841                         return
842                 self._addTermLog('> %s\n' % (line))
843                 self._printerConnection.sendCommand(line)
844                 self._termHistory.append(line)
845                 self._termHistoryIdx = len(self._termHistory)
846                 self._termInput.SetValue('')
847
848         def OnTermKey(self, e):
849                 if len(self._termHistory) > 0:
850                         if e.GetKeyCode() == wx.WXK_UP:
851                                 self._termHistoryIdx -= 1
852                                 if self._termHistoryIdx < 0:
853                                         self._termHistoryIdx = len(self._termHistory) - 1
854                                 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
855                         if e.GetKeyCode() == wx.WXK_DOWN:
856                                 self._termHistoryIdx -= 1
857                                 if self._termHistoryIdx >= len(self._termHistory):
858                                         self._termHistoryIdx = 0
859                                 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
860                 e.Skip()
861
862         def _addTermLog(self, line):
863                 if self._termLog is not None:
864                         if len(self._termLog.GetValue()) > 10000:
865                                 self._termLog.SetValue(self._termLog.GetValue()[-10000:])
866                         self._termLog.SetInsertionPointEnd()
867                         if type(line) != unicode:
868                                 line = unicode(line, 'utf-8', 'replace')
869                         self._termLog.AppendText(line.encode('utf-8', 'replace'))
870
871         def _updateButtonStates(self):
872                 self.connectButton.Show(self._printerConnection.hasActiveConnection())
873                 self.connectButton.Enable(not self._printerConnection.isActiveConnectionOpen() and \
874                                                                   not self._printerConnection.isActiveConnectionOpening())
875                 if not self._printerConnection.hasPause():
876                         if not self._printerConnection.hasActiveConnection() or \
877                            self._printerConnection.isActiveConnectionOpen():
878                                 self.printButton.Enable(not self._printerConnection.isPrinting() and \
879                                                                                 not self._printerConnection.isPaused())
880                         else:
881                                 self.printButton.Enable(False)
882                 else:
883                         if not self._printerConnection.hasActiveConnection() or \
884                            self._printerConnection.isActiveConnectionOpen():
885                                 if self._printerConnection.isPrinting():
886                                         self.printButton.SetLabel(_("Pause"))
887                                 else:
888                                         if self._printerConnection.isPaused():
889                                                 self.printButton.SetLabel(_("Resume"))
890                                         else:
891                                                 self.printButton.SetLabel(_("Print"))
892                                 self.printButton.Enable(True)
893                         else:
894                                 self.printButton.Enable(False)
895                 if not self._printerConnection.hasActiveConnection() or \
896                    self._printerConnection.isActiveConnectionOpen():
897                         self.cancelButton.Enable(self._printerConnection.isPrinting() or \
898                                                                          self._printerConnection.isPaused())
899                 else:
900                         self.cancelButton.Enable(False)
901                 self.errorLogButton.Show(self._printerConnection.isInErrorState())
902                 self._termInput.Enable(self._printerConnection.isAbleToSendDirectCommand())
903                 self.Layout()
904
905         def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
906                 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
907                 temp = []
908                 for n in xrange(0, 4):
909                         t = connection.getTemperature(0)
910                         if t is not None:
911                                 temp.append(t)
912                         else:
913                                 break
914                 self.temperatureGraph.addPoint(temp, [0] * len(temp), connection.getBedTemperature(), 0)
915                 if self._fullscreenTemperature is not None:
916                         self._fullscreenTemperature.addPoint(temp, [0] * len(temp), connection.getBedTemperature(), 0)
917
918         def __doPrinterConnectionUpdate(self, connection, extraInfo):
919                 t = time.time()
920                 if self._lastUpdateTime + 0.5 > t and extraInfo is None:
921                         return
922                 self._lastUpdateTime = t
923
924                 if extraInfo is not None and len(extraInfo) > 0:
925                         self._addTermLog('< %s\n' % (extraInfo))
926
927                 self._updateButtonStates()
928                 isPrinting = connection.isPrinting() or connection.isPaused()
929                 if isPrinting:
930                         self.progress.SetValue(connection.getPrintProgress() * 1000)
931                 else:
932                         self.progress.SetValue(0)
933                 info = connection.getStatusString()
934                 info += '\n'
935                 if self._printerConnection.getTemperature(0) is not None:
936                         info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
937                 if self._printerConnection.getBedTemperature() > 0:
938                         info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
939                 self.SetTitle(info.replace('\n', ', '))
940                 if isPrinting != self._isPrinting:
941                         self._isPrinting = isPrinting
942                         preventComputerFromSleeping(self, self._isPrinting)
943
944 class TemperatureField(wx.Panel):
945         def __init__(self, parent, callback):
946                 super(TemperatureField, self).__init__(parent)
947                 self.callback = callback
948
949                 self.SetBackgroundColour(wx.WHITE)
950
951                 self.text = IntCtrl(self, -1)
952                 self.text.SetBounds(0, 300)
953                 self.text.SetSize((60, 25))
954
955                 self.unit = wx.StaticBitmap(self, -1, wx.BitmapFromImage(wx.Image(
956                                 resources.getPathForImage('print-window-temperature-unit.png'))), (0, 0))
957
958                 self.button = wx.Button(self, -1, _("Set"))
959                 self.button.SetSize((35, 25))
960                 self.Bind(wx.EVT_BUTTON, lambda e: self.callback(self.text.GetValue()), self.button)
961
962                 self.text.SetPosition((0, 0))
963                 self.unit.SetPosition((60, 0))
964                 self.button.SetPosition((90, 0))
965
966
967 class TemperatureGraph(wx.Panel):
968         def __init__(self, parent):
969                 super(TemperatureGraph, self).__init__(parent)
970
971                 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
972                 self.Bind(wx.EVT_SIZE, self.OnSize)
973                 self.Bind(wx.EVT_PAINT, self.OnDraw)
974
975                 self._lastDraw = time.time() - 1.0
976                 self._points = []
977                 self._backBuffer = None
978                 self.addPoint([0]*16, [0]*16, 0, 0)
979
980         def Clone(self, parent):
981                 clone = TemperatureGraph(parent)
982                 clone._points = list(self._points)
983                 return clone
984
985         def OnEraseBackground(self, e):
986                 pass
987
988         def OnSize(self, e):
989                 if self._backBuffer is None or self.GetSize() != self._backBuffer.GetSize():
990                         self._backBuffer = wx.EmptyBitmap(*self.GetSizeTuple())
991                         self.UpdateDrawing(True)
992
993         def OnDraw(self, e):
994                 dc = wx.BufferedPaintDC(self, self._backBuffer)
995
996         def UpdateDrawing(self, force=False):
997                 now = time.time()
998                 if (not force and now - self._lastDraw < 1.0) or self._backBuffer is None:
999                         return
1000                 self._lastDraw = now
1001                 dc = wx.MemoryDC()
1002                 dc.SelectObject(self._backBuffer)
1003                 dc.Clear()
1004                 dc.SetFont(wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT))
1005                 w, h = self.GetSizeTuple()
1006                 bgLinePen = wx.Pen('#A0A0A0')
1007                 tempPen = wx.Pen('#FF4040')
1008                 tempSPPen = wx.Pen('#FFA0A0')
1009                 tempPenBG = wx.Pen('#FFD0D0')
1010                 bedTempPen = wx.Pen('#4040FF')
1011                 bedTempSPPen = wx.Pen('#A0A0FF')
1012                 bedTempPenBG = wx.Pen('#D0D0FF')
1013
1014                 #Draw the background up to the current temperatures.
1015                 x0 = 0
1016                 t0 = []
1017                 bt0 = 0
1018                 tSP0 = 0
1019                 btSP0 = 0
1020                 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
1021                         x1 = int(w - (now - t))
1022                         for x in xrange(x0, x1 + 1):
1023                                 for n in xrange(0, min(len(t0), len(temp))):
1024                                         t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
1025                                         dc.SetPen(tempPenBG)
1026                                         dc.DrawLine(x, h, x, h - (t * h / 350))
1027                                 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
1028                                 dc.SetPen(bedTempPenBG)
1029                                 dc.DrawLine(x, h, x, h - (bt * h / 350))
1030                         t0 = temp
1031                         bt0 = bedTemp
1032                         tSP0 = tempSP
1033                         btSP0 = bedTempSP
1034                         x0 = x1 + 1
1035
1036                 #Draw the grid
1037                 for x in xrange(w, 0, -30):
1038                         dc.SetPen(bgLinePen)
1039                         dc.DrawLine(x, 0, x, h)
1040                 tmpNr = 0
1041                 for y in xrange(h - 1, 0, -h * 50 / 350):
1042                         dc.SetPen(bgLinePen)
1043                         dc.DrawLine(0, y, w, y)
1044                         dc.DrawText(str(tmpNr), 0, y - dc.GetFont().GetPixelSize().GetHeight())
1045                         tmpNr += 50
1046                 dc.DrawLine(0, 0, w, 0)
1047                 dc.DrawLine(0, 0, 0, h)
1048
1049                 #Draw the main lines
1050                 x0 = 0
1051                 t0 = []
1052                 bt0 = 0
1053                 tSP0 = []
1054                 btSP0 = 0
1055                 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
1056                         x1 = int(w - (now - t))
1057                         for x in xrange(x0, x1 + 1):
1058                                 for n in xrange(0, min(len(t0), len(temp))):
1059                                         t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
1060                                         tSP = float(x - x0) / float(x1 - x0 + 1) * (tempSP[n] - tSP0[n]) + tSP0[n]
1061                                         dc.SetPen(tempSPPen)
1062                                         dc.DrawPoint(x, h - (tSP * h / 350))
1063                                         dc.SetPen(tempPen)
1064                                         dc.DrawPoint(x, h - (t * h / 350))
1065                                 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
1066                                 btSP = float(x - x0) / float(x1 - x0 + 1) * (bedTempSP - btSP0) + btSP0
1067                                 dc.SetPen(bedTempSPPen)
1068                                 dc.DrawPoint(x, h - (btSP * h / 350))
1069                                 dc.SetPen(bedTempPen)
1070                                 dc.DrawPoint(x, h - (bt * h / 350))
1071                         t0 = temp
1072                         bt0 = bedTemp
1073                         tSP0 = tempSP
1074                         btSP0 = bedTempSP
1075                         x0 = x1 + 1
1076
1077                 del dc
1078                 self.Refresh(eraseBackground=False)
1079                 self.Update()
1080
1081                 if len(self._points) > 0 and (time.time() - self._points[0][4]) > w + 20:
1082                         self._points.pop(0)
1083
1084         def addPoint(self, temp, tempSP, bedTemp, bedTempSP):
1085                 if len(self._points) > 0 and time.time() - self._points[-1][4] < 0.5:
1086                         return
1087                 for n in xrange(0, len(temp)):
1088                         if temp[n] is None:
1089                                 temp[n] = 0
1090                 for n in xrange(0, len(tempSP)):
1091                         if tempSP[n] is None:
1092                                 tempSP[n] = 0
1093                 if bedTemp is None:
1094                         bedTemp = 0
1095                 if bedTempSP is None:
1096                         bedTempSP = 0
1097                 self._points.append((temp[:], tempSP[:], bedTemp, bedTempSP, time.time()))
1098                 wx.CallAfter(self.UpdateDrawing)
1099
1100 class LogWindow(wx.Frame):
1101         def __init__(self, logText):
1102                 super(LogWindow, self).__init__(None, title=_("Error log"))
1103                 self.textBox = wx.TextCtrl(self, -1, logText, style=wx.TE_MULTILINE | wx.TE_DONTWRAP | wx.TE_READONLY)
1104                 self.SetSize((500, 400))
1105                 self.Show(True)