chiark / gitweb /
Increment version number
[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         foo = objc.loadBundleFunctions(bundle, globals(), [("IOPMAssertionCreateWithName", b"i@I@o^I")])
41         foo = 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                                                         if self.pauseTimer.IsRunning():
350                                                                 self.printButton.Enable(False)
351                                                                 self.printButton.SetLabel(_("Please wait..."))
352                                                         else:
353                                                                 self.printButton.Enable(True)
354                                                                 button.SetLabel(_("Pause"))
355                                                 else:
356                                                         if self._printerConnection.isPaused():
357                                                                 if self.pauseTimer.IsRunning():
358                                                                         self.printButton.Enable(False)
359                                                                         self.printButton.SetLabel(_("Please wait..."))
360                                                                 else:
361                                                                         self.printButton.Enable(True)
362                                                                         button.SetLabel(_("Resume"))
363                                                         else:
364                                                                 button.SetLabel(_("Print"))
365                                                                 button.Enable(True)
366                                                                 self.pauseTimer.Stop()
367                                         else:
368                                                 button.Enable(False)
369                         elif button.command == self.script_cancelPrint:
370                                 if not self._printerConnection.hasActiveConnection() or \
371                                    self._printerConnection.isActiveConnectionOpen():
372                                         button.Enable(self._printerConnection.isPrinting() or \
373                                                                   self._printerConnection.isPaused())
374                                 else:
375                                         button.Enable(False)
376                         elif button.command == self.script_showErrorLog:
377                                 button.Show(self._printerConnection.isInErrorState())
378                 if self._termInput is not None:
379                         self._termInput.Enable(self._printerConnection.isAbleToSendDirectCommand())
380
381         def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
382                 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
383                 if self._tempGraph is not None:
384                         temp = []
385                         for n in xrange(0, 4):
386                                 t = connection.getTemperature(0)
387                                 if t is not None:
388                                         temp.append(t)
389                                 else:
390                                         break
391                         self._tempGraph.addPoint(temp, [0] * len(temp), connection.getBedTemperature(), 0)
392
393         def __doPrinterConnectionUpdate(self, connection, extraInfo):
394                 t = time.time()
395                 if self._lastUpdateTime + 0.5 > t and extraInfo is None:
396                         return
397                 self._lastUpdateTime = t
398
399                 if extraInfo is not None and len(extraInfo) > 0:
400                         self._addTermLog('< %s\n' % (extraInfo))
401
402                 self._updateButtonStates()
403                 isPrinting = connection.isPrinting() or connection.isPaused()
404                 if self._progressBar is not None:
405                         if isPrinting:
406                                 (current, total, z) = connection.getPrintProgress()
407                                 progress = 0.0
408                                 if total > 0:
409                                         progress = float(current) / float(total)
410                                 self._progressBar.SetValue(progress * 1000)
411                         else:
412                                 self._progressBar.SetValue(0)
413                 info = connection.getStatusString()
414                 info += '\n'
415                 if self._printerConnection.getTemperature(0) is not None:
416                         info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
417                 if self._printerConnection.getBedTemperature() > 0:
418                         info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
419                 if self._infoText is not None:
420                         self._infoText.SetLabel(info)
421                 else:
422                         self.SetTitle(info.replace('\n', ', ').strip(', '))
423                 if isPrinting != self._isPrinting:
424                         self._isPrinting = isPrinting
425                         preventComputerFromSleeping(self, self._isPrinting)
426
427 class printWindowBasic(wx.Frame):
428         """
429         Printing window for USB printing, network printing, and any other type of printer connection we can think off.
430         This is only a basic window with minimal information.
431         """
432         def __init__(self, parent, printerConnection):
433                 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()))
434                 self._printerConnection = printerConnection
435                 self._lastUpdateTime = 0
436                 self._isPrinting = False
437
438                 self.SetSizer(wx.BoxSizer())
439                 self.panel = wx.Panel(self)
440                 self.GetSizer().Add(self.panel, 1, flag=wx.EXPAND)
441                 self.sizer = wx.GridBagSizer(2, 2)
442                 self.panel.SetSizer(self.sizer)
443
444                 self.powerWarningText = wx.StaticText(parent=self.panel,
445                         id=-1,
446                         label=_("Your computer is running on battery power.\nConnect your computer to AC power or your print might not finish."),
447                         style=wx.ALIGN_CENTER)
448                 self.powerWarningText.SetBackgroundColour('red')
449                 self.powerWarningText.SetForegroundColour('white')
450                 self.powerManagement = power.PowerManagement()
451                 self.powerWarningTimer = wx.Timer(self)
452                 self.Bind(wx.EVT_TIMER, self.OnPowerWarningChange, self.powerWarningTimer)
453                 self.OnPowerWarningChange(None)
454                 self.powerWarningTimer.Start(10000)
455
456                 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"))
457
458                 self.connectButton = wx.Button(self.panel, -1, _("Connect"))
459                 #self.loadButton = wx.Button(self.panel, -1, 'Load')
460                 self.printButton = wx.Button(self.panel, -1, _("Print"))
461                 self.pauseButton = wx.Button(self.panel, -1, _("Pause"))
462                 self.cancelButton = wx.Button(self.panel, -1, _("Cancel print"))
463                 self.errorLogButton = wx.Button(self.panel, -1, _("Error log"))
464                 self.progress = wx.Gauge(self.panel, -1, range=1000)
465
466                 self.pauseTimer = wx.Timer(self)
467                 self.Bind(wx.EVT_TIMER, self.OnPauseTimer, self.pauseTimer)
468
469                 self.sizer.Add(self.powerWarningText, pos=(0, 0), span=(1, 5), flag=wx.EXPAND|wx.BOTTOM, border=5)
470                 self.sizer.Add(self.statsText, pos=(1, 0), span=(1, 5), flag=wx.LEFT, border=5)
471                 self.sizer.Add(self.connectButton, pos=(2, 0))
472                 #self.sizer.Add(self.loadButton, pos=(2,1))
473                 self.sizer.Add(self.printButton, pos=(2, 1))
474                 self.sizer.Add(self.pauseButton, pos=(2, 2))
475                 self.sizer.Add(self.cancelButton, pos=(2, 3))
476                 self.sizer.Add(self.errorLogButton, pos=(2, 4))
477                 self.sizer.Add(self.progress, pos=(3, 0), span=(1, 5), flag=wx.EXPAND)
478
479                 self.Bind(wx.EVT_CLOSE, self.OnClose)
480                 self.connectButton.Bind(wx.EVT_BUTTON, self.OnConnect)
481                 #self.loadButton.Bind(wx.EVT_BUTTON, self.OnLoad)
482                 self.printButton.Bind(wx.EVT_BUTTON, self.OnPrint)
483                 self.pauseButton.Bind(wx.EVT_BUTTON, self.OnPause)
484                 self.cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel)
485                 self.errorLogButton.Bind(wx.EVT_BUTTON, self.OnErrorLog)
486
487                 self.Layout()
488                 self.Fit()
489                 self.Centre()
490
491                 self.progress.SetMinSize(self.progress.GetSize())
492                 self.statsText.SetLabel('\n\n\n\n\n\n')
493                 self._updateButtonStates()
494
495                 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
496
497                 if self._printerConnection.hasActiveConnection() and not self._printerConnection.isActiveConnectionOpen():
498                         self._printerConnection.openActiveConnection()
499
500         def OnPowerWarningChange(self, e):
501                 type = self.powerManagement.get_providing_power_source_type()
502                 if type == power.POWER_TYPE_AC and self.powerWarningText.IsShown():
503                         self.powerWarningText.Hide()
504                         self.panel.Layout()
505                         self.Layout()
506                         self.Fit()
507                         self.Refresh()
508                 elif type != power.POWER_TYPE_AC and not self.powerWarningText.IsShown():
509                         self.powerWarningText.Show()
510                         self.panel.Layout()
511                         self.Layout()
512                         self.Fit()
513                         self.Refresh()
514
515         def OnClose(self, e):
516                 if self._printerConnection.hasActiveConnection():
517                         if self._printerConnection.isPrinting() or self._printerConnection.isPaused():
518                                 pass #TODO: Give warning that the close will kill the print.
519                         self._printerConnection.closeActiveConnection()
520                 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
521                 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
522                 preventComputerFromSleeping(self, False)
523                 self.powerWarningTimer.Stop()
524                 self.pauseTimer.Stop()
525                 self.Destroy()
526
527         def OnConnect(self, e):
528                 self._printerConnection.openActiveConnection()
529
530         def OnLoad(self, e):
531                 pass
532
533         def OnPrint(self, e):
534                 self._printerConnection.startPrint()
535
536         def OnCancel(self, e):
537                 self._printerConnection.cancelPrint()
538
539         def OnPause(self, e):
540                 self._printerConnection.pause(not self._printerConnection.isPaused())
541                 self.pauseButton.Enable(False)
542                 self.pauseTimer.Stop()
543                 self.pauseTimer.Start(10000)
544
545         def OnPauseTimer(self, e):
546                 self.pauseButton.Enable(True)
547                 self.pauseTimer.Stop()
548                 self._updateButtonStates()
549
550         def OnErrorLog(self, e):
551                 LogWindow(self._printerConnection.getErrorLog())
552
553         def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
554                 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
555                 #temp = [connection.getTemperature(0)]
556                 #self.temperatureGraph.addPoint(temp, [0], connection.getBedTemperature(), 0)
557
558         def __doPrinterConnectionUpdate(self, connection, extraInfo):
559                 now = time.time()
560                 if self._lastUpdateTime + 0.5 > now and extraInfo is None:
561                         return
562                 self._lastUpdateTime = now
563
564                 if extraInfo is not None and len(extraInfo) > 0:
565                         self._addTermLog('< %s\n' % (extraInfo))
566
567                 self._updateButtonStates()
568                 onGoingPrint = connection.isPrinting() or connection.isPaused()
569                 if onGoingPrint:
570                         (current, total, z) = connection.getPrintProgress()
571                         progress = 0.0
572                         if total > 0:
573                                 progress = float(current) / float(total)
574                         self.progress.SetValue(progress * 1000)
575                 else:
576                         self.progress.SetValue(0)
577                 info = connection.getStatusString()
578                 info += '\n'
579                 if self._printerConnection.getTemperature(0) is not None:
580                         info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
581                 if self._printerConnection.getBedTemperature() > 0:
582                         info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
583                 info += '\n\n'
584                 self.statsText.SetLabel(info)
585                 if onGoingPrint != self._isPrinting:
586                         self._isPrinting = onGoingPrint
587                         preventComputerFromSleeping(self, self._isPrinting)
588
589         def _addTermLog(self, msg):
590                 pass
591
592         def _updateButtonStates(self):
593                 self.connectButton.Show(self._printerConnection.hasActiveConnection())
594                 self.connectButton.Enable(not self._printerConnection.isActiveConnectionOpen() and not self._printerConnection.isActiveConnectionOpening())
595                 self.pauseButton.Show(self._printerConnection.hasPause())
596                 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
597                         self.printButton.Enable(not self._printerConnection.isPrinting() and \
598                                                                         not self._printerConnection.isPaused())
599                         self.pauseButton.Enable(self._printerConnection.isPrinting())
600                         self.cancelButton.Enable(self._printerConnection.isPrinting())
601                 else:
602                         self.printButton.Enable(False)
603                         self.pauseButton.Enable(False)
604                         self.cancelButton.Enable(False)
605                 self.errorLogButton.Show(self._printerConnection.isInErrorState())
606
607 class printWindowAdvanced(wx.Frame):
608         def __init__(self, parent, printerConnection):
609                 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()))
610                 self._printerConnection = printerConnection
611                 self._lastUpdateTime = time.time()
612                 self._isPrinting = False
613
614                 self.SetSizer(wx.BoxSizer(wx.VERTICAL))
615                 self.toppanel = wx.Panel(self)
616                 self.topsizer = wx.GridBagSizer(2, 2)
617                 self.toppanel.SetSizer(self.topsizer)
618                 self.toppanel.SetBackgroundColour(wx.WHITE)
619                 self.topsizer.SetEmptyCellSize((125, 1))
620                 self.panel = wx.Panel(self)
621                 self.sizer = wx.GridBagSizer(2, 2)
622                 self.sizer.SetEmptyCellSize((125, 1))
623                 self.panel.SetSizer(self.sizer)
624                 self.panel.SetBackgroundColour(wx.WHITE)
625                 self.GetSizer().Add(self.toppanel, 0, flag=wx.EXPAND)
626                 self.GetSizer().Add(self.panel, 1, flag=wx.EXPAND)
627
628                 self._fullscreenTemperature = None
629                 self._termHistory = []
630                 self._termHistoryIdx = 0
631
632                 self._mapImage = wx.Image(resources.getPathForImage('print-window-map.png'))
633                 self._colorCommandMap = {}
634
635                 # Move X
636                 self._addMovementCommand(0, 0, 255, self._moveX, 100)
637                 self._addMovementCommand(0, 0, 240, self._moveX, 10)
638                 self._addMovementCommand(0, 0, 220, self._moveX, 1)
639                 self._addMovementCommand(0, 0, 200, self._moveX, 0.1)
640                 self._addMovementCommand(0, 0, 180, self._moveX, -0.1)
641                 self._addMovementCommand(0, 0, 160, self._moveX, -1)
642                 self._addMovementCommand(0, 0, 140, self._moveX, -10)
643                 self._addMovementCommand(0, 0, 120, self._moveX, -100)
644
645                 # Move Y
646                 self._addMovementCommand(0, 255, 0, self._moveY, -100)
647                 self._addMovementCommand(0, 240, 0, self._moveY, -10)
648                 self._addMovementCommand(0, 220, 0, self._moveY, -1)
649                 self._addMovementCommand(0, 200, 0, self._moveY, -0.1)
650                 self._addMovementCommand(0, 180, 0, self._moveY, 0.1)
651                 self._addMovementCommand(0, 160, 0, self._moveY, 1)
652                 self._addMovementCommand(0, 140, 0, self._moveY, 10)
653                 self._addMovementCommand(0, 120, 0, self._moveY, 100)
654
655                 # Move Z
656                 self._addMovementCommand(255, 0, 0, self._moveZ, 10)
657                 self._addMovementCommand(220, 0, 0, self._moveZ, 1)
658                 self._addMovementCommand(200, 0, 0, self._moveZ, 0.1)
659                 self._addMovementCommand(180, 0, 0, self._moveZ, -0.1)
660                 self._addMovementCommand(160, 0, 0, self._moveZ, -1)
661                 self._addMovementCommand(140, 0, 0, self._moveZ, -10)
662
663                 # Extrude/Retract
664                 self._addMovementCommand(255, 80, 0, self._moveE, 10)
665                 self._addMovementCommand(255, 180, 0, self._moveE, -10)
666
667                 # Home
668                 self._addMovementCommand(255, 255, 0, self._homeXYZ, None)
669                 self._addMovementCommand(240, 255, 0, self._homeXYZ, "X")
670                 self._addMovementCommand(220, 255, 0, self._homeXYZ, "Y")
671                 self._addMovementCommand(200, 255, 0, self._homeXYZ, "Z")
672
673                 self.powerWarningText = wx.StaticText(parent=self.toppanel,
674                         id=-1,
675                         label=_("Your computer is running on battery power.\nConnect your computer to AC power or your print might not finish."),
676                         style=wx.ALIGN_CENTER)
677                 self.powerWarningText.SetBackgroundColour('red')
678                 self.powerWarningText.SetForegroundColour('white')
679                 self.powerManagement = power.PowerManagement()
680                 self.powerWarningTimer = wx.Timer(self)
681                 self.Bind(wx.EVT_TIMER, self.OnPowerWarningChange, self.powerWarningTimer)
682                 self.OnPowerWarningChange(None)
683                 self.powerWarningTimer.Start(10000)
684
685                 self.pauseTimer = wx.Timer(self)
686                 self.Bind(wx.EVT_TIMER, self.OnPauseTimer, self.pauseTimer)
687
688                 self.connectButton = wx.Button(self.toppanel, -1, _("Connect"), size=(125, 30))
689                 self.printButton = wx.Button(self.toppanel, -1, _("Print"), size=(125, 30))
690                 self.cancelButton = wx.Button(self.toppanel, -1, _("Cancel"), size=(125, 30))
691                 self.errorLogButton = wx.Button(self.toppanel, -1, _("Error log"), size=(125, 30))
692                 self.motorsOffButton = wx.Button(self.toppanel, -1, _("Motors off"), size=(125, 30))
693                 self.movementBitmap = wx.StaticBitmap(self.panel, -1, wx.BitmapFromImage(wx.Image(
694                                 resources.getPathForImage('print-window.png'))), (0, 0))
695                 self.temperatureBitmap = wx.StaticBitmap(self.panel, -1, wx.BitmapFromImage(wx.Image(
696                                 resources.getPathForImage('print-window-temperature.png'))), (0, 0))
697                 self.temperatureField = TemperatureField(self.panel, self._setHotendTemperature)
698                 self.temperatureBedBitmap = wx.StaticBitmap(self.panel, -1, wx.BitmapFromImage(wx.Image(
699                                 resources.getPathForImage('print-window-temperature-bed.png'))), (0, 0))
700                 self.temperatureBedField = TemperatureField(self.panel, self._setBedTemperature)
701                 self.temperatureGraph = TemperatureGraph(self.panel)
702                 self.temperatureGraph.SetMinSize((250, 100))
703                 self.progress = wx.Gauge(self.panel, -1, range=1000)
704
705                 f = wx.Font(8, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
706                 self._termLog = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE)
707                 self._termLog.SetFont(f)
708                 self._termLog.SetEditable(0)
709                 self._termLog.SetMinSize((385, -1))
710                 self._termInput = wx.TextCtrl(self.panel, style=wx.TE_PROCESS_ENTER)
711                 self._termInput.SetFont(f)
712
713                 self.Bind(wx.EVT_TEXT_ENTER, self.OnTermEnterLine, self._termInput)
714                 self._termInput.Bind(wx.EVT_CHAR, self.OnTermKey)
715
716                 self.topsizer.Add(self.powerWarningText, pos=(0, 0), span=(1, 6), flag=wx.EXPAND|wx.BOTTOM, border=5)
717                 self.topsizer.Add(self.connectButton, pos=(1, 0), flag=wx.LEFT, border=2)
718                 self.topsizer.Add(self.printButton, pos=(1, 1), flag=wx.LEFT, border=2)
719                 self.topsizer.Add(self.cancelButton, pos=(1, 2), flag=wx.LEFT, border=2)
720                 self.topsizer.Add(self.errorLogButton, pos=(1, 4), flag=wx.LEFT, border=2)
721                 self.topsizer.Add(self.motorsOffButton, pos=(1, 5), flag=wx.LEFT|wx.RIGHT, border=2)
722                 self.sizer.Add(self.movementBitmap, pos=(0, 0), span=(2, 3))
723                 self.sizer.Add(self.temperatureGraph, pos=(2, 0), span=(4, 2), flag=wx.EXPAND)
724                 self.sizer.Add(self.temperatureBitmap, pos=(2, 2))
725                 self.sizer.Add(self.temperatureField, pos=(3, 2))
726                 self.sizer.Add(self.temperatureBedBitmap, pos=(4, 2))
727                 self.sizer.Add(self.temperatureBedField, pos=(5, 2))
728                 self.sizer.Add(self._termLog, pos=(0, 3), span=(5, 3), flag=wx.EXPAND|wx.RIGHT, border=5)
729                 self.sizer.Add(self._termInput, pos=(5, 3), span=(1, 3), flag=wx.EXPAND|wx.RIGHT, border=5)
730                 self.sizer.Add(self.progress, pos=(7, 0), span=(1, 6), flag=wx.EXPAND|wx.BOTTOM)
731
732                 self.Bind(wx.EVT_SIZE, self.OnSize)
733                 self.Bind(wx.EVT_CLOSE, self.OnClose)
734                 self.movementBitmap.Bind(wx.EVT_LEFT_DOWN, self.OnMovementClick)
735                 self.temperatureGraph.Bind(wx.EVT_LEFT_UP, self.OnTemperatureClick)
736                 self.connectButton.Bind(wx.EVT_BUTTON, self.OnConnect)
737                 self.printButton.Bind(wx.EVT_BUTTON, self.OnPrint)
738                 self.cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel)
739                 self.errorLogButton.Bind(wx.EVT_BUTTON, self.OnErrorLog)
740                 self.motorsOffButton.Bind(wx.EVT_BUTTON, self.OnMotorsOff)
741
742                 self.Layout()
743                 self.Fit()
744                 self.Refresh()
745                 self.progress.SetMinSize(self.progress.GetSize())
746                 self._updateButtonStates()
747
748                 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
749
750                 if self._printerConnection.hasActiveConnection() and \
751                    not self._printerConnection.isActiveConnectionOpen():
752                         self._printerConnection.openActiveConnection()
753
754         def OnSize(self, e):
755                 # HACK ALERT: This is needed for some reason otherwise the window
756                 # will be bigger than it should be until a power warning change
757                 self.Layout()
758                 self.Fit()
759                 e.Skip()
760
761         def OnClose(self, e):
762                 if self._printerConnection.hasActiveConnection():
763                         if self._printerConnection.isPrinting() or self._printerConnection.isPaused():
764                                 pass #TODO: Give warning that the close will kill the print.
765                         self._printerConnection.closeActiveConnection()
766                 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
767                 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
768                 preventComputerFromSleeping(self, False)
769                 self._printerConnection.cancelPrint()
770                 self.powerWarningTimer.Stop()
771                 self.pauseTimer.Stop()
772                 self.Destroy()
773
774         def OnPowerWarningChange(self, e):
775                 type = self.powerManagement.get_providing_power_source_type()
776                 if type == power.POWER_TYPE_AC and self.powerWarningText.IsShown():
777                         self.powerWarningText.Hide()
778                         self.toppanel.Layout()
779                         self.Layout()
780                         self.Fit()
781                         self.Refresh()
782                 elif type != power.POWER_TYPE_AC and not self.powerWarningText.IsShown():
783                         self.powerWarningText.Show()
784                         self.toppanel.Layout()
785                         self.Layout()
786                         self.Fit()
787                         self.Refresh()
788
789         def OnConnect(self, e):
790                 self._printerConnection.openActiveConnection()
791
792         def OnPrint(self, e):
793                 if self._printerConnection.isPrinting() or self._printerConnection.isPaused():
794                         self._printerConnection.pause(not self._printerConnection.isPaused())
795                         self.pauseTimer.Stop()
796                         self.printButton.Enable(False)
797                         self.pauseTimer.Start(10000)
798                 else:
799                         self._printerConnection.startPrint()
800
801         def OnPauseTimer(self, e):
802                 self.printButton.Enable(True)
803                 self.pauseTimer.Stop()
804                 self._updateButtonStates()
805
806         def OnCancel(self, e):
807                 self._printerConnection.cancelPrint()
808
809         def OnErrorLog(self, e):
810                 LogWindow(self._printerConnection.getErrorLog())
811
812         def OnMotorsOff(self, e):
813                 self._printerConnection.sendCommand("M18")
814
815         def GetMapRGB(self, x, y):
816                 r = self._mapImage.GetRed(x, y)
817                 g = self._mapImage.GetGreen(x, y)
818                 b = self._mapImage.GetBlue(x, y)
819                 return (r, g, b)
820
821         def OnMovementClick(self, e):
822                 (r, g, b) = self.GetMapRGB(e.GetX(), e.GetY())
823                 if (r, g, b) in self._colorCommandMap:
824                         command = self._colorCommandMap[(r, g, b)]
825                         command[0](command[1])
826
827         def _addMovementCommand(self, r, g, b, command, step):
828                 self._colorCommandMap[(r, g, b)] = (command, step)
829
830         def _moveXYZE(self, motor, step, feedrate):
831                 # Prevent Z movement when paused and all moves when printing
832                 if (not self._printerConnection.hasActiveConnection() or \
833                         self._printerConnection.isActiveConnectionOpen()) and \
834                         (not (self._printerConnection.isPaused() and motor != 'E') and \
835                          not self._printerConnection.isPrinting()):
836                         self._printerConnection.sendCommand("G91")
837                         self._printerConnection.sendCommand("G1 %s%.1f F%d" % (motor, step, feedrate))
838                         self._printerConnection.sendCommand("G90")
839
840         def _moveX(self, step):
841                 self._moveXYZE("X", step, 2000)
842
843         def _moveY(self, step):
844                 self._moveXYZE("Y", step, 2000)
845
846         def _moveZ(self, step):
847                 self._moveXYZE("Z", step, 200)
848
849         def _moveE(self, step):
850                 feedrate = 120
851                 if "lulzbot_" in profile.getMachineSetting("machine_type"):
852                         toolhead_name = profile.getMachineSetting("toolhead")
853                         toolhead_name = toolhead_name.lower()
854                         if "flexy" in toolhead_name:
855                                 feedrate = 30
856                 self._moveXYZE("E", step, feedrate)
857
858         def _homeXYZ(self, direction):
859                 if not self._printerConnection.isPaused() and not self._printerConnection.isPrinting():
860                         if direction is None:
861                                 self._printerConnection.sendCommand("G28")
862                         else:
863                                 self._printerConnection.sendCommand("G28 %s0" % direction)
864
865         def _setHotendTemperature(self, value):
866                 self._printerConnection.sendCommand("M104 S%d" % value)
867
868         def _setBedTemperature(self, value):
869                 self._printerConnection.sendCommand("M140 S%d" % value)
870
871         def OnTemperatureClick(self, e):
872                 wx.CallAfter(self.ToggleFullScreenTemperature)
873
874         def ToggleFullScreenTemperature(self):
875                 sizer = self.GetSizer()
876                 if self._fullscreenTemperature:
877                         self._fullscreenTemperature.Show(False)
878                         sizer.Detach(self._fullscreenTemperature)
879                         self._fullscreenTemperature.Destroy()
880                         self._fullscreenTemperature = None
881                         self.panel.Show(True)
882                 else:
883                         self._fullscreenTemperature = self.temperatureGraph.Clone(self)
884                         self._fullscreenTemperature.Bind(wx.EVT_LEFT_UP, self.OnTemperatureClick)
885                         self._fullscreenTemperature.SetMinSize(self.panel.GetSize())
886                         sizer.Add(self._fullscreenTemperature, 1, flag=wx.EXPAND)
887                         self.panel.Show(False)
888                 self.Layout()
889                 self.Refresh()
890
891         def OnTermEnterLine(self, e):
892                 if not self._printerConnection.isAbleToSendDirectCommand():
893                         return
894                 line = self._termInput.GetValue()
895                 if line == '':
896                         return
897                 self._addTermLog('> %s\n' % (line))
898                 self._printerConnection.sendCommand(line)
899                 self._termHistory.append(line)
900                 self._termHistoryIdx = len(self._termHistory)
901                 self._termInput.SetValue('')
902
903         def OnTermKey(self, e):
904                 if len(self._termHistory) > 0:
905                         if e.GetKeyCode() == wx.WXK_UP:
906                                 self._termHistoryIdx -= 1
907                                 if self._termHistoryIdx < 0:
908                                         self._termHistoryIdx = len(self._termHistory) - 1
909                                 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
910                         if e.GetKeyCode() == wx.WXK_DOWN:
911                                 self._termHistoryIdx -= 1
912                                 if self._termHistoryIdx >= len(self._termHistory):
913                                         self._termHistoryIdx = 0
914                                 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
915                 e.Skip()
916
917         def _addTermLog(self, line):
918                 if self._termLog is not None:
919                         if len(self._termLog.GetValue()) > 10000:
920                                 self._termLog.SetValue(self._termLog.GetValue()[-10000:])
921                         self._termLog.SetInsertionPointEnd()
922                         if type(line) != unicode:
923                                 line = unicode(line, 'utf-8', 'replace')
924                         self._termLog.AppendText(line.encode('utf-8', 'replace'))
925
926         def _updateButtonStates(self):
927                 self.connectButton.Show(self._printerConnection.hasActiveConnection())
928                 self.connectButton.Enable(not self._printerConnection.isActiveConnectionOpen() and \
929                                                                   not self._printerConnection.isActiveConnectionOpening())
930                 if not self._printerConnection.hasPause():
931                         if not self._printerConnection.hasActiveConnection() or \
932                            self._printerConnection.isActiveConnectionOpen():
933                                 self.printButton.Enable(not self._printerConnection.isPrinting() and \
934                                                                                 not self._printerConnection.isPaused())
935                         else:
936                                 self.printButton.Enable(False)
937                 else:
938                         if not self._printerConnection.hasActiveConnection() or \
939                            self._printerConnection.isActiveConnectionOpen():
940                                 if self._printerConnection.isPrinting():
941                                         if self.pauseTimer.IsRunning():
942                                                 self.printButton.Enable(False)
943                                                 self.printButton.SetLabel(_("Please wait..."))
944                                         else:
945                                                 self.printButton.Enable(True)
946                                                 self.printButton.SetLabel(_("Pause"))
947                                 else:
948                                         if self._printerConnection.isPaused():
949                                                 if self.pauseTimer.IsRunning():
950                                                         self.printButton.Enable(False)
951                                                         self.printButton.SetLabel(_("Please wait..."))
952                                                 else:
953                                                         self.printButton.SetLabel(_("Resume"))
954                                                         self.printButton.Enable(True)
955                                         else:
956                                                 self.printButton.SetLabel(_("Print"))
957                                                 self.printButton.Enable(True)
958                                                 self.pauseTimer.Stop()
959                         else:
960                                 self.printButton.Enable(False)
961                 if not self._printerConnection.hasActiveConnection() or \
962                    self._printerConnection.isActiveConnectionOpen():
963                         self.cancelButton.Enable(self._printerConnection.isPrinting() or \
964                                                                          self._printerConnection.isPaused())
965                 else:
966                         self.cancelButton.Enable(False)
967                 self.errorLogButton.Show(self._printerConnection.isInErrorState())
968                 self._termInput.Enable(self._printerConnection.isAbleToSendDirectCommand())
969                 self.Layout()
970
971         def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
972                 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
973                 temp = []
974                 for n in xrange(0, 4):
975                         t = connection.getTemperature(0)
976                         if t is not None:
977                                 temp.append(t)
978                         else:
979                                 break
980                 self.temperatureGraph.addPoint(temp, [0] * len(temp), connection.getBedTemperature(), 0)
981                 if self._fullscreenTemperature is not None:
982                         self._fullscreenTemperature.addPoint(temp, [0] * len(temp), connection.getBedTemperature(), 0)
983
984         def __doPrinterConnectionUpdate(self, connection, extraInfo):
985                 t = time.time()
986                 if self._lastUpdateTime + 0.5 > t and extraInfo is None:
987                         return
988                 self._lastUpdateTime = t
989
990                 if extraInfo is not None and len(extraInfo) > 0:
991                         self._addTermLog('< %s\n' % (extraInfo))
992
993                 self._updateButtonStates()
994                 
995                 info = connection.getStatusString()
996                 isPrinting = connection.isPrinting() or connection.isPaused()
997                 if isPrinting:
998                         (current, total, z) = connection.getPrintProgress()
999                         progress = 0.0
1000                         if total > 0:
1001                                 progress = float(current) / float(total)
1002                         self.progress.SetValue(progress * 1000)
1003                         info += (" {:3.1f}% | ".format(progress * 100))
1004                         info += (("Z: %.3fmm") % (z))
1005                 else:
1006                         self.progress.SetValue(0)
1007
1008                 if self._printerConnection.getTemperature(0) is not None:
1009                         info += ' | Temperature: %d ' % (self._printerConnection.getTemperature(0))
1010                 if self._printerConnection.getBedTemperature() > 0:
1011                         info += 'Bed: %d' % (self._printerConnection.getBedTemperature())
1012                 self.SetTitle(info.replace('\n', ', ').strip(', '))
1013                 if isPrinting != self._isPrinting:
1014                         self._isPrinting = isPrinting
1015                         preventComputerFromSleeping(self, self._isPrinting)
1016
1017 class TemperatureField(wx.Panel):
1018         def __init__(self, parent, callback):
1019                 super(TemperatureField, self).__init__(parent)
1020                 self.callback = callback
1021
1022                 self.SetBackgroundColour(wx.WHITE)
1023
1024                 self.text = IntCtrl(self, -1)
1025                 self.text.SetBounds(0, 300)
1026                 self.text.SetSize((60, 28))
1027
1028                 self.unit = wx.StaticBitmap(self, -1, wx.BitmapFromImage(wx.Image(
1029                                 resources.getPathForImage('print-window-temperature-unit.png'))), (0, 0))
1030
1031                 self.button = wx.Button(self, -1, _("Set"))
1032                 self.button.SetSize((35, 25))
1033                 self.Bind(wx.EVT_BUTTON, lambda e: self.callback(self.text.GetValue()), self.button)
1034
1035                 self.text.SetPosition((0, 0))
1036                 self.unit.SetPosition((60, 0))
1037                 self.button.SetPosition((90, 0))
1038
1039
1040 class TemperatureGraph(wx.Panel):
1041         def __init__(self, parent):
1042                 super(TemperatureGraph, self).__init__(parent)
1043
1044                 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
1045                 self.Bind(wx.EVT_SIZE, self.OnSize)
1046                 self.Bind(wx.EVT_PAINT, self.OnDraw)
1047
1048                 self._lastDraw = time.time() - 1.0
1049                 self._points = []
1050                 self._backBuffer = None
1051                 self.addPoint([0]*16, [0]*16, 0, 0)
1052
1053         def Clone(self, parent):
1054                 clone = TemperatureGraph(parent)
1055                 clone._points = list(self._points)
1056                 return clone
1057
1058         def OnEraseBackground(self, e):
1059                 pass
1060
1061         def OnSize(self, e):
1062                 if self._backBuffer is None or self.GetSize() != self._backBuffer.GetSize():
1063                         self._backBuffer = wx.EmptyBitmap(*self.GetSizeTuple())
1064                         self.UpdateDrawing(True)
1065
1066         def OnDraw(self, e):
1067                 dc = wx.BufferedPaintDC(self, self._backBuffer)
1068
1069         def UpdateDrawing(self, force=False):
1070                 now = time.time()
1071                 if (not force and now - self._lastDraw < 1.0) or self._backBuffer is None:
1072                         return
1073                 self._lastDraw = now
1074                 dc = wx.MemoryDC()
1075                 dc.SelectObject(self._backBuffer)
1076                 dc.SetBackground(wx.Brush(wx.WHITE))
1077                 dc.Clear()
1078                 dc.SetFont(wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT))
1079                 w, h = self.GetSizeTuple()
1080                 bgLinePen = wx.Pen('#A0A0A0')
1081                 tempPen = wx.Pen('#FF4040')
1082                 tempSPPen = wx.Pen('#FFA0A0')
1083                 tempPenBG = wx.Pen('#FFD0D0')
1084                 bedTempPen = wx.Pen('#4040FF')
1085                 bedTempSPPen = wx.Pen('#A0A0FF')
1086                 bedTempPenBG = wx.Pen('#D0D0FF')
1087
1088                 #Draw the background up to the current temperatures.
1089                 x0 = 0
1090                 t0 = []
1091                 bt0 = 0
1092                 tSP0 = 0
1093                 btSP0 = 0
1094                 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
1095                         x1 = int(w - (now - t))
1096                         for x in xrange(x0, x1 + 1):
1097                                 for n in xrange(0, min(len(t0), len(temp))):
1098                                         t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
1099                                         dc.SetPen(tempPenBG)
1100                                         dc.DrawLine(x, h, x, h - (t * h / 350))
1101                                 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
1102                                 dc.SetPen(bedTempPenBG)
1103                                 dc.DrawLine(x, h, x, h - (bt * h / 350))
1104                         t0 = temp
1105                         bt0 = bedTemp
1106                         tSP0 = tempSP
1107                         btSP0 = bedTempSP
1108                         x0 = x1 + 1
1109
1110                 #Draw the grid
1111                 for x in xrange(w, 0, -30):
1112                         dc.SetPen(bgLinePen)
1113                         dc.DrawLine(x, 0, x, h)
1114                 tmpNr = 0
1115                 for y in xrange(h - 1, 0, -h * 50 / 350):
1116                         dc.SetPen(bgLinePen)
1117                         dc.DrawLine(0, y, w, y)
1118                         dc.DrawText(str(tmpNr), 0, y - dc.GetFont().GetPixelSize().GetHeight())
1119                         tmpNr += 50
1120                 dc.DrawLine(0, 0, w, 0)
1121                 dc.DrawLine(0, 0, 0, h)
1122
1123                 #Draw the main lines
1124                 x0 = 0
1125                 t0 = []
1126                 bt0 = 0
1127                 tSP0 = []
1128                 btSP0 = 0
1129                 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
1130                         x1 = int(w - (now - t))
1131                         for x in xrange(x0, x1 + 1):
1132                                 for n in xrange(0, min(len(t0), len(temp))):
1133                                         t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
1134                                         tSP = float(x - x0) / float(x1 - x0 + 1) * (tempSP[n] - tSP0[n]) + tSP0[n]
1135                                         dc.SetPen(tempSPPen)
1136                                         dc.DrawPoint(x, h - (tSP * h / 350))
1137                                         dc.SetPen(tempPen)
1138                                         dc.DrawPoint(x, h - (t * h / 350))
1139                                 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
1140                                 btSP = float(x - x0) / float(x1 - x0 + 1) * (bedTempSP - btSP0) + btSP0
1141                                 dc.SetPen(bedTempSPPen)
1142                                 dc.DrawPoint(x, h - (btSP * h / 350))
1143                                 dc.SetPen(bedTempPen)
1144                                 dc.DrawPoint(x, h - (bt * h / 350))
1145                         t0 = temp
1146                         bt0 = bedTemp
1147                         tSP0 = tempSP
1148                         btSP0 = bedTempSP
1149                         x0 = x1 + 1
1150
1151                 del dc
1152                 self.Refresh(eraseBackground=False)
1153                 self.Update()
1154
1155                 if len(self._points) > 0 and (time.time() - self._points[0][4]) > w + 20:
1156                         self._points.pop(0)
1157
1158         def addPoint(self, temp, tempSP, bedTemp, bedTempSP):
1159                 if len(self._points) > 0 and time.time() - self._points[-1][4] < 0.5:
1160                         return
1161                 for n in xrange(0, len(temp)):
1162                         if temp[n] is None:
1163                                 temp[n] = 0
1164                 for n in xrange(0, len(tempSP)):
1165                         if tempSP[n] is None:
1166                                 tempSP[n] = 0
1167                 if bedTemp is None:
1168                         bedTemp = 0
1169                 if bedTempSP is None:
1170                         bedTempSP = 0
1171                 self._points.append((temp[:], tempSP[:], bedTemp, bedTempSP, time.time()))
1172                 wx.CallAfter(self.UpdateDrawing)
1173
1174 class LogWindow(wx.Frame):
1175         def __init__(self, logText):
1176                 super(LogWindow, self).__init__(None, title=_("Error log"))
1177                 self.textBox = wx.TextCtrl(self, -1, logText, style=wx.TE_MULTILINE | wx.TE_DONTWRAP | wx.TE_READONLY)
1178                 self.SetSize((500, 400))
1179                 self.Show(True)