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