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