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