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