chiark / gitweb /
Enable full screen temp graph only on button up, not down
[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.panel.SetSizer(self.sizer)
588                 self.panel.SetBackgroundColour(wx.WHITE)
589                 self.GetSizer().Add(self.toppanel, 0, flag=wx.EXPAND)
590                 self.GetSizer().Add(self.panel, 1, flag=wx.EXPAND)
591
592                 self._fullscreenTemperature = None
593                 self._termHistory = []
594                 self._termHistoryIdx = 0
595
596                 self._mapImage = wx.Image(resources.getPathForImage('print-window-map.png'))
597                 self._colorCommandMap = {}
598
599                 # Move X
600                 self._addMovementCommand(0, 0, 255, self._moveX, 100)
601                 self._addMovementCommand(0, 0, 240, self._moveX, 10)
602                 self._addMovementCommand(0, 0, 220, self._moveX, 1)
603                 self._addMovementCommand(0, 0, 200, self._moveX, 0.1)
604                 self._addMovementCommand(0, 0, 180, self._moveX, -0.1)
605                 self._addMovementCommand(0, 0, 160, self._moveX, -1)
606                 self._addMovementCommand(0, 0, 140, self._moveX, -10)
607                 self._addMovementCommand(0, 0, 120, self._moveX, -100)
608
609                 # Move Y
610                 self._addMovementCommand(0, 255, 0, self._moveY, -100)
611                 self._addMovementCommand(0, 240, 0, self._moveY, -10)
612                 self._addMovementCommand(0, 220, 0, self._moveY, -1)
613                 self._addMovementCommand(0, 200, 0, self._moveY, -0.1)
614                 self._addMovementCommand(0, 180, 0, self._moveY, 0.1)
615                 self._addMovementCommand(0, 160, 0, self._moveY, 1)
616                 self._addMovementCommand(0, 140, 0, self._moveY, 10)
617                 self._addMovementCommand(0, 120, 0, self._moveY, 100)
618
619                 # Move Z
620                 self._addMovementCommand(255, 0, 0, self._moveZ, 10)
621                 self._addMovementCommand(220, 0, 0, self._moveZ, 1)
622                 self._addMovementCommand(200, 0, 0, self._moveZ, 0.1)
623                 self._addMovementCommand(180, 0, 0, self._moveZ, -0.1)
624                 self._addMovementCommand(160, 0, 0, self._moveZ, -1)
625                 self._addMovementCommand(140, 0, 0, self._moveZ, -10)
626
627                 # Extrude/Retract
628                 self._addMovementCommand(255, 80, 0, self._moveE, 10)
629                 self._addMovementCommand(255, 180, 0, self._moveE, -10)
630
631                 # Home
632                 self._addMovementCommand(255, 255, 0, self._homeXYZ, None)
633                 self._addMovementCommand(240, 255, 0, self._homeXYZ, "X")
634                 self._addMovementCommand(220, 255, 0, self._homeXYZ, "Y")
635                 self._addMovementCommand(200, 255, 0, self._homeXYZ, "Z")
636
637                 self.powerWarningText = wx.StaticText(parent=self.toppanel,
638                         id=-1,
639                         label=_("Your computer is running on battery power.\nConnect your computer to AC power or your print might not finish."),
640                         style=wx.ALIGN_CENTER)
641                 self.powerWarningText.SetBackgroundColour('red')
642                 self.powerWarningText.SetForegroundColour('white')
643                 self.powerManagement = power.PowerManagement()
644                 self.powerWarningTimer = wx.Timer(self)
645                 self.Bind(wx.EVT_TIMER, self.OnPowerWarningChange, self.powerWarningTimer)
646                 self.OnPowerWarningChange(None)
647                 self.powerWarningTimer.Start(10000)
648
649                 self.connectButton = wx.Button(self.toppanel, -1, _("Connect"), size=(125, 30))
650                 self.printButton = wx.Button(self.toppanel, -1, _("Print"), size=(125, 30))
651                 self.cancelButton = wx.Button(self.toppanel, -1, _("Cancel"), size=(125, 30))
652                 self.errorLogButton = wx.Button(self.toppanel, -1, _("Error log"), size=(125, 30))
653                 self.motorsOffButton = wx.Button(self.toppanel, -1, _("Motors off"), size=(125, 30))
654                 self.movementBitmap = wx.StaticBitmap(self.panel, -1, wx.BitmapFromImage(wx.Image(
655                                 resources.getPathForImage('print-window.png'))), (0, 0))
656                 self.temperatureBitmap = wx.StaticBitmap(self.panel, -1, wx.BitmapFromImage(wx.Image(
657                                 resources.getPathForImage('print-window-temperature.png'))), (0, 0))
658                 self.temperatureField = TemperatureField(self.panel, self._setHotendTemperature)
659                 self.temperatureBedBitmap = wx.StaticBitmap(self.panel, -1, wx.BitmapFromImage(wx.Image(
660                                 resources.getPathForImage('print-window-temperature-bed.png'))), (0, 0))
661                 self.temperatureBedField = TemperatureField(self.panel, self._setBedTemperature)
662                 self.temperatureGraph = TemperatureGraph(self.panel)
663                 self.progress = wx.Gauge(self.panel, -1, range=1000)
664
665                 f = wx.Font(8, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
666                 self._termLog = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE | wx.TE_DONTWRAP)
667                 self._termLog.SetFont(f)
668                 self._termLog.SetEditable(0)
669                 self._termLog.SetMinSize((385, -1))
670                 self._termInput = wx.TextCtrl(self.panel, style=wx.TE_PROCESS_ENTER)
671                 self._termInput.SetFont(f)
672
673                 self.Bind(wx.EVT_TEXT_ENTER, self.OnTermEnterLine, self._termInput)
674                 self._termInput.Bind(wx.EVT_CHAR, self.OnTermKey)
675
676                 self.topsizer.Add(self.powerWarningText, pos=(0, 0), span=(1, 6), flag=wx.EXPAND|wx.BOTTOM, border=5)
677                 self.topsizer.Add(self.connectButton, pos=(1, 0), flag=wx.LEFT, border=2)
678                 self.topsizer.Add(self.printButton, pos=(1, 1), flag=wx.LEFT, border=2)
679                 self.topsizer.Add(self.cancelButton, pos=(1, 2), flag=wx.LEFT, border=2)
680                 self.topsizer.Add(self.errorLogButton, pos=(1, 4), flag=wx.LEFT, border=2)
681                 self.topsizer.Add(self.motorsOffButton, pos=(1, 5), flag=wx.LEFT|wx.RIGHT, border=2)
682                 self.sizer.Add(self.movementBitmap, pos=(0, 0), span=(2, 3))
683                 self.sizer.Add(self.temperatureGraph, pos=(2, 0), span=(4, 2), flag=wx.EXPAND)
684                 self.sizer.Add(self.temperatureBitmap, pos=(2, 2))
685                 self.sizer.Add(self.temperatureField, pos=(3, 2))
686                 self.sizer.Add(self.temperatureBedBitmap, pos=(4, 2))
687                 self.sizer.Add(self.temperatureBedField, pos=(5, 2))
688                 self.sizer.Add(self._termLog, pos=(0, 3), span=(5, 3), flag=wx.EXPAND|wx.RIGHT, border=5)
689                 self.sizer.Add(self._termInput, pos=(5, 3), span=(1, 3), flag=wx.EXPAND|wx.RIGHT, border=5)
690                 self.sizer.Add(self.progress, pos=(6, 0), span=(1, 6), flag=wx.EXPAND|wx.BOTTOM)
691
692                 self.Bind(wx.EVT_SIZE, self.OnSize)
693                 self.Bind(wx.EVT_CLOSE, self.OnClose)
694                 self.movementBitmap.Bind(wx.EVT_LEFT_DOWN, self.OnMovementClick)
695                 self.temperatureGraph.Bind(wx.EVT_LEFT_UP, self.OnTemperatureClick)
696                 self.connectButton.Bind(wx.EVT_BUTTON, self.OnConnect)
697                 self.printButton.Bind(wx.EVT_BUTTON, self.OnPrint)
698                 self.cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel)
699                 self.errorLogButton.Bind(wx.EVT_BUTTON, self.OnErrorLog)
700                 self.motorsOffButton.Bind(wx.EVT_BUTTON, self.OnMotorsOff)
701
702                 self.Layout()
703                 self.Fit()
704                 self.Refresh()
705                 self.progress.SetMinSize(self.progress.GetSize())
706                 self._updateButtonStates()
707
708                 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
709
710                 if self._printerConnection.hasActiveConnection() and \
711                    not self._printerConnection.isActiveConnectionOpen():
712                         self._printerConnection.openActiveConnection()
713
714         def OnSize(self, e):
715                 # HACK ALERT: This is needed for some reason otherwise the window
716                 # will be bigger than it should be until a power warning change
717                 self.Layout()
718                 self.Fit()
719                 e.Skip()
720
721         def OnClose(self, e):
722                 if self._printerConnection.hasActiveConnection():
723                         if self._printerConnection.isPrinting() or self._printerConnection.isPaused():
724                                 pass #TODO: Give warning that the close will kill the print.
725                         self._printerConnection.closeActiveConnection()
726                 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
727                 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
728                 preventComputerFromSleeping(self, False)
729                 self._printerConnection.cancelPrint()
730                 self.Destroy()
731
732         def OnPowerWarningChange(self, e):
733                 type = self.powerManagement.get_providing_power_source_type()
734                 if type == power.POWER_TYPE_AC and self.powerWarningText.IsShown():
735                         self.powerWarningText.Hide()
736                         self.toppanel.Layout()
737                         self.Layout()
738                         self.Fit()
739                         self.Refresh()
740                 elif type != power.POWER_TYPE_AC and not self.powerWarningText.IsShown():
741                         self.powerWarningText.Show()
742                         self.toppanel.Layout()
743                         self.Layout()
744                         self.Fit()
745                         self.Refresh()
746
747         def OnConnect(self, e):
748                 self._printerConnection.openActiveConnection()
749
750         def OnPrint(self, e):
751                 if self._printerConnection.isPrinting() or self._printerConnection.isPaused():
752                         self._printerConnection.pause(not self._printerConnection.isPaused())
753                 else:
754                         self._printerConnection.startPrint()
755
756         def OnCancel(self, e):
757                 self._printerConnection.cancelPrint()
758
759         def OnErrorLog(self, e):
760                 LogWindow(self._printerConnection.getErrorLog())
761
762         def OnMotorsOff(self, e):
763                 self._printerConnection.sendCommand("M18")
764
765         def GetMapRGB(self, x, y):
766                 r = self._mapImage.GetRed(x, y)
767                 g = self._mapImage.GetGreen(x, y)
768                 b = self._mapImage.GetBlue(x, y)
769                 return (r, g, b)
770
771         def OnMovementClick(self, e):
772                 (r, g, b) = self.GetMapRGB(e.GetX(), e.GetY())
773                 if (r, g, b) in self._colorCommandMap:
774                         command = self._colorCommandMap[(r, g, b)]
775                         command[0](command[1])
776
777         def _addMovementCommand(self, r, g, b, command, step):
778                 self._colorCommandMap[(r, g, b)] = (command, step)
779
780         def _moveXYZE(self, motor, step, feedrate):
781                 if (not self._printerConnection.hasActiveConnection() or \
782                         self._printerConnection.isActiveConnectionOpen()) and \
783                         (not self._printerConnection.isPaused() and \
784                          not self._printerConnection.isPrinting()):
785                         self._printerConnection.sendCommand("G91")
786                         self._printerConnection.sendCommand("G1 %s%.1f F%d" % (motor, step, feedrate))
787                         self._printerConnection.sendCommand("G90")
788
789         def _moveX(self, step):
790                 self._moveXYZE("X", step, 2000)
791
792         def _moveY(self, step):
793                 self._moveXYZE("Y", step, 2000)
794
795         def _moveZ(self, step):
796                 self._moveXYZE("Z", step, 200)
797
798         def _moveE(self, step):
799                 self._moveXYZE("E", step, 120)
800
801         def _homeXYZ(self, direction):
802                 if not self._printerConnection.isPaused() and not self._printerConnection.isPrinting():
803                         if direction is None:
804                                 self._printerConnection.sendCommand("G28")
805                         else:
806                                 self._printerConnection.sendCommand("G28 %s0" % direction)
807
808         def _setHotendTemperature(self, value):
809                 self._printerConnection.sendCommand("M104 S%d" % value)
810
811         def _setBedTemperature(self, value):
812                 self._printerConnection.sendCommand("M140 S%d" % value)
813
814         def OnTemperatureClick(self, e):
815                 wx.CallAfter(self.ToggleFullScreenTemperature)
816
817         def ToggleFullScreenTemperature(self):
818                 sizer = self.GetSizer()
819                 if self._fullscreenTemperature:
820                         self._fullscreenTemperature.Show(False)
821                         sizer.Detach(self._fullscreenTemperature)
822                         self._fullscreenTemperature.Destroy()
823                         self._fullscreenTemperature = None
824                         self.panel.Show(True)
825                 else:
826                         self._fullscreenTemperature = self.temperatureGraph.Clone(self)
827                         self._fullscreenTemperature.Bind(wx.EVT_LEFT_UP, self.OnTemperatureClick)
828                         sizer.Add(self._fullscreenTemperature, 1, flag=wx.EXPAND)
829                         self.panel.Show(False)
830                 self.Layout()
831                 self.Refresh()
832
833         def OnTermEnterLine(self, e):
834                 if not self._printerConnection.isAbleToSendDirectCommand():
835                         return
836                 line = self._termInput.GetValue()
837                 if line == '':
838                         return
839                 self._addTermLog('> %s\n' % (line))
840                 self._printerConnection.sendCommand(line)
841                 self._termHistory.append(line)
842                 self._termHistoryIdx = len(self._termHistory)
843                 self._termInput.SetValue('')
844
845         def OnTermKey(self, e):
846                 if len(self._termHistory) > 0:
847                         if e.GetKeyCode() == wx.WXK_UP:
848                                 self._termHistoryIdx -= 1
849                                 if self._termHistoryIdx < 0:
850                                         self._termHistoryIdx = len(self._termHistory) - 1
851                                 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
852                         if e.GetKeyCode() == wx.WXK_DOWN:
853                                 self._termHistoryIdx -= 1
854                                 if self._termHistoryIdx >= len(self._termHistory):
855                                         self._termHistoryIdx = 0
856                                 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
857                 e.Skip()
858
859         def _addTermLog(self, line):
860                 if self._termLog is not None:
861                         if len(self._termLog.GetValue()) > 10000:
862                                 self._termLog.SetValue(self._termLog.GetValue()[-10000:])
863                         self._termLog.SetInsertionPointEnd()
864                         if type(line) != unicode:
865                                 line = unicode(line, 'utf-8', 'replace')
866                         self._termLog.AppendText(line.encode('utf-8', 'replace'))
867
868         def _updateButtonStates(self):
869                 self.connectButton.Show(self._printerConnection.hasActiveConnection())
870                 self.connectButton.Enable(not self._printerConnection.isActiveConnectionOpen() and \
871                                                                   not self._printerConnection.isActiveConnectionOpening())
872                 if not self._printerConnection.hasPause():
873                         if not self._printerConnection.hasActiveConnection() or \
874                            self._printerConnection.isActiveConnectionOpen():
875                                 self.printButton.Enable(not self._printerConnection.isPrinting() and \
876                                                                                 not self._printerConnection.isPaused())
877                         else:
878                                 self.printButton.Enable(False)
879                 else:
880                         if not self._printerConnection.hasActiveConnection() or \
881                            self._printerConnection.isActiveConnectionOpen():
882                                 if self._printerConnection.isPrinting():
883                                         self.printButton.SetLabel(_("Pause"))
884                                 else:
885                                         if self._printerConnection.isPaused():
886                                                 self.printButton.SetLabel(_("Resume"))
887                                         else:
888                                                 self.printButton.SetLabel(_("Print"))
889                                 self.printButton.Enable(True)
890                         else:
891                                 self.printButton.Enable(False)
892                 if not self._printerConnection.hasActiveConnection() or \
893                    self._printerConnection.isActiveConnectionOpen():
894                         self.cancelButton.Enable(self._printerConnection.isPrinting() or \
895                                                                          self._printerConnection.isPaused())
896                 else:
897                         self.cancelButton.Enable(False)
898                 self.errorLogButton.Show(self._printerConnection.isInErrorState())
899                 self._termInput.Enable(self._printerConnection.isAbleToSendDirectCommand())
900
901         def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
902                 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
903                 temp = []
904                 for n in xrange(0, 4):
905                         t = connection.getTemperature(0)
906                         if t is not None:
907                                 temp.append(t)
908                         else:
909                                 break
910                 self.temperatureGraph.addPoint(temp, [0] * len(temp), connection.getBedTemperature(), 0)
911                 if self._fullscreenTemperature is not None:
912                         self._fullscreenTemperature.addPoint(temp, [0] * len(temp), connection.getBedTemperature(), 0)
913
914         def __doPrinterConnectionUpdate(self, connection, extraInfo):
915                 t = time.time()
916                 if self._lastUpdateTime + 0.5 > t and extraInfo is None:
917                         return
918                 self._lastUpdateTime = t
919
920                 if extraInfo is not None and len(extraInfo) > 0:
921                         self._addTermLog('< %s\n' % (extraInfo))
922
923                 self._updateButtonStates()
924                 isPrinting = connection.isPrinting() or connection.isPaused()
925                 if isPrinting:
926                         self.progress.SetValue(connection.getPrintProgress() * 1000)
927                 else:
928                         self.progress.SetValue(0)
929                 info = connection.getStatusString()
930                 info += '\n'
931                 if self._printerConnection.getTemperature(0) is not None:
932                         info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
933                 if self._printerConnection.getBedTemperature() > 0:
934                         info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
935                 self.SetTitle(info.replace('\n', ', '))
936                 if isPrinting != self._isPrinting:
937                         self._isPrinting = isPrinting
938                         preventComputerFromSleeping(self, self._isPrinting)
939
940 class TemperatureField(wx.Panel):
941         def __init__(self, parent, callback):
942                 super(TemperatureField, self).__init__(parent)
943                 self.callback = callback
944
945                 self.SetBackgroundColour(wx.WHITE)
946
947                 self.text = IntCtrl(self, -1)
948                 self.text.SetBounds(0, 300)
949                 self.text.SetSize((60, 25))
950
951                 self.unit = wx.StaticBitmap(self, -1, wx.BitmapFromImage(wx.Image(
952                                 resources.getPathForImage('print-window-temperature-unit.png'))), (0, 0))
953
954                 self.button = wx.Button(self, -1, _("Set"))
955                 self.button.SetSize((35, 25))
956                 self.Bind(wx.EVT_BUTTON, lambda e: self.callback(self.text.GetValue()), self.button)
957
958                 self.text.SetPosition((0, 0))
959                 self.unit.SetPosition((60, 0))
960                 self.button.SetPosition((90, 0))
961
962
963 class TemperatureGraph(wx.Panel):
964         def __init__(self, parent):
965                 super(TemperatureGraph, self).__init__(parent)
966
967                 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
968                 self.Bind(wx.EVT_SIZE, self.OnSize)
969                 self.Bind(wx.EVT_PAINT, self.OnDraw)
970
971                 self._lastDraw = time.time() - 1.0
972                 self._points = []
973                 self._backBuffer = None
974                 self.addPoint([0]*16, [0]*16, 0, 0)
975
976         def Clone(self, parent):
977                 clone = TemperatureGraph(parent)
978                 clone._points = list(self._points)
979                 return clone
980
981         def OnEraseBackground(self, e):
982                 pass
983
984         def OnSize(self, e):
985                 if self._backBuffer is None or self.GetSize() != self._backBuffer.GetSize():
986                         self._backBuffer = wx.EmptyBitmap(*self.GetSizeTuple())
987                         self.UpdateDrawing(True)
988
989         def OnDraw(self, e):
990                 dc = wx.BufferedPaintDC(self, self._backBuffer)
991
992         def UpdateDrawing(self, force=False):
993                 now = time.time()
994                 if (not force and now - self._lastDraw < 1.0) or self._backBuffer is None:
995                         return
996                 self._lastDraw = now
997                 dc = wx.MemoryDC()
998                 dc.SelectObject(self._backBuffer)
999                 dc.Clear()
1000                 dc.SetFont(wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT))
1001                 w, h = self.GetSizeTuple()
1002                 bgLinePen = wx.Pen('#A0A0A0')
1003                 tempPen = wx.Pen('#FF4040')
1004                 tempSPPen = wx.Pen('#FFA0A0')
1005                 tempPenBG = wx.Pen('#FFD0D0')
1006                 bedTempPen = wx.Pen('#4040FF')
1007                 bedTempSPPen = wx.Pen('#A0A0FF')
1008                 bedTempPenBG = wx.Pen('#D0D0FF')
1009
1010                 #Draw the background up to the current temperatures.
1011                 x0 = 0
1012                 t0 = []
1013                 bt0 = 0
1014                 tSP0 = 0
1015                 btSP0 = 0
1016                 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
1017                         x1 = int(w - (now - t))
1018                         for x in xrange(x0, x1 + 1):
1019                                 for n in xrange(0, min(len(t0), len(temp))):
1020                                         t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
1021                                         dc.SetPen(tempPenBG)
1022                                         dc.DrawLine(x, h, x, h - (t * h / 350))
1023                                 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
1024                                 dc.SetPen(bedTempPenBG)
1025                                 dc.DrawLine(x, h, x, h - (bt * h / 350))
1026                         t0 = temp
1027                         bt0 = bedTemp
1028                         tSP0 = tempSP
1029                         btSP0 = bedTempSP
1030                         x0 = x1 + 1
1031
1032                 #Draw the grid
1033                 for x in xrange(w, 0, -30):
1034                         dc.SetPen(bgLinePen)
1035                         dc.DrawLine(x, 0, x, h)
1036                 tmpNr = 0
1037                 for y in xrange(h - 1, 0, -h * 50 / 350):
1038                         dc.SetPen(bgLinePen)
1039                         dc.DrawLine(0, y, w, y)
1040                         dc.DrawText(str(tmpNr), 0, y - dc.GetFont().GetPixelSize().GetHeight())
1041                         tmpNr += 50
1042                 dc.DrawLine(0, 0, w, 0)
1043                 dc.DrawLine(0, 0, 0, h)
1044
1045                 #Draw the main lines
1046                 x0 = 0
1047                 t0 = []
1048                 bt0 = 0
1049                 tSP0 = []
1050                 btSP0 = 0
1051                 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
1052                         x1 = int(w - (now - t))
1053                         for x in xrange(x0, x1 + 1):
1054                                 for n in xrange(0, min(len(t0), len(temp))):
1055                                         t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
1056                                         tSP = float(x - x0) / float(x1 - x0 + 1) * (tempSP[n] - tSP0[n]) + tSP0[n]
1057                                         dc.SetPen(tempSPPen)
1058                                         dc.DrawPoint(x, h - (tSP * h / 350))
1059                                         dc.SetPen(tempPen)
1060                                         dc.DrawPoint(x, h - (t * h / 350))
1061                                 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
1062                                 btSP = float(x - x0) / float(x1 - x0 + 1) * (bedTempSP - btSP0) + btSP0
1063                                 dc.SetPen(bedTempSPPen)
1064                                 dc.DrawPoint(x, h - (btSP * h / 350))
1065                                 dc.SetPen(bedTempPen)
1066                                 dc.DrawPoint(x, h - (bt * h / 350))
1067                         t0 = temp
1068                         bt0 = bedTemp
1069                         tSP0 = tempSP
1070                         btSP0 = bedTempSP
1071                         x0 = x1 + 1
1072
1073                 del dc
1074                 self.Refresh(eraseBackground=False)
1075                 self.Update()
1076
1077                 if len(self._points) > 0 and (time.time() - self._points[0][4]) > w + 20:
1078                         self._points.pop(0)
1079
1080         def addPoint(self, temp, tempSP, bedTemp, bedTempSP):
1081                 if len(self._points) > 0 and time.time() - self._points[-1][4] < 0.5:
1082                         return
1083                 for n in xrange(0, len(temp)):
1084                         if temp[n] is None:
1085                                 temp[n] = 0
1086                 for n in xrange(0, len(tempSP)):
1087                         if tempSP[n] is None:
1088                                 tempSP[n] = 0
1089                 if bedTemp is None:
1090                         bedTemp = 0
1091                 if bedTempSP is None:
1092                         bedTempSP = 0
1093                 self._points.append((temp[:], tempSP[:], bedTemp, bedTempSP, time.time()))
1094                 wx.CallAfter(self.UpdateDrawing)
1095
1096 class LogWindow(wx.Frame):
1097         def __init__(self, logText):
1098                 super(LogWindow, self).__init__(None, title=_("Error log"))
1099                 self.textBox = wx.TextCtrl(self, -1, logText, style=wx.TE_MULTILINE | wx.TE_DONTWRAP | wx.TE_READONLY)
1100                 self.SetSize((500, 400))
1101                 self.Show(True)