1 __copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
4 from wx.lib.intctrl import IntCtrl
11 from Cura.util import resources
12 from Cura.util import profile
14 #TODO: This does not belong here!
15 if sys.platform.startswith('win'):
16 def preventComputerFromSleeping(frame, prevent):
18 Function used to prevent the computer from going into sleep mode.
19 :param prevent: True = Prevent the system from going to sleep from this point on.
20 :param prevent: False = No longer prevent the system from going to sleep.
22 ES_CONTINUOUS = 0x80000000
23 ES_SYSTEM_REQUIRED = 0x00000001
24 ES_AWAYMODE_REQUIRED = 0x00000040
25 #SetThreadExecutionState returns 0 when failed, which is ignored. The function should be supported from windows XP and up.
27 # For Vista and up we use ES_AWAYMODE_REQUIRED to prevent a print from failing if the PC does go to sleep
28 # As it's not supported on XP, we catch the error and fallback to using ES_SYSTEM_REQUIRED only
29 if ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED) == 0:
30 ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED)
32 ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS)
34 elif sys.platform.startswith('darwin'):
36 bundle = objc.initFrameworkWrapper("IOKit",
37 frameworkIdentifier="com.apple.iokit",
38 frameworkPath=objc.pathForFramework("/System/Library/Frameworks/IOKit.framework"),
40 objc.loadBundleFunctions(bundle, globals(), [("IOPMAssertionCreateWithName", b"i@I@o^I")])
41 objc.loadBundleFunctions(bundle, globals(), [("IOPMAssertionRelease", b"iI")])
42 def preventComputerFromSleeping(frame, prevent):
44 success, preventComputerFromSleeping.assertionID = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, "Cura is printing", None)
45 if success != kIOReturnSuccess:
46 preventComputerFromSleeping.assertionID = None
48 if hasattr(preventComputerFromSleeping, "assertionID"):
49 if preventComputerFromSleeping.assertionID is not None:
50 IOPMAssertionRelease(preventComputerFromSleeping.assertionID)
51 preventComputerFromSleeping.assertionID = None
53 def preventComputerFromSleeping(frame, prevent):
54 if os.path.isfile("/usr/bin/xdg-screensaver"):
56 cmd = ['xdg-screensaver', 'suspend' if prevent else 'resume', str(frame.GetHandle())]
61 class printWindowPlugin(wx.Frame):
62 def __init__(self, parent, printerConnection, filename):
63 super(printWindowPlugin, self).__init__(parent, -1, style=wx.CLOSE_BOX|wx.CLIP_CHILDREN|wx.CAPTION|wx.SYSTEM_MENU|wx.FRAME_FLOAT_ON_PARENT|wx.MINIMIZE_BOX, title=_("Printing on %s") % (printerConnection.getName()))
64 self._printerConnection = printerConnection
65 self._basePath = os.path.dirname(filename)
66 self._backgroundImage = None
67 self._colorCommandMap = {}
70 self._termInput = None
71 self._termHistory = []
72 self._termHistoryIdx = 0
73 self._progressBar = None
74 self._tempGraph = None
76 self._lastUpdateTime = time.time()
77 self._isPrinting = False
80 'setImage': self.script_setImage,
81 'addColorCommand': self.script_addColorCommand,
82 'addTerminal': self.script_addTerminal,
83 'addTemperatureGraph': self.script_addTemperatureGraph,
84 'addProgressbar': self.script_addProgressbar,
85 'addButton': self.script_addButton,
86 'addSpinner': self.script_addSpinner,
87 'addTextButton': self.script_addTextButton,
89 'sendGCode': self.script_sendGCode,
90 'sendMovementGCode': self.script_sendMovementGCode,
91 'connect': self.script_connect,
92 'startPrint': self.script_startPrint,
93 'pausePrint': self.script_pausePrint,
94 'cancelPrint': self.script_cancelPrint,
95 'showErrorLog': self.script_showErrorLog,
97 execfile(filename, variables, variables)
99 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
100 self.Bind(wx.EVT_PAINT, self.OnDraw)
101 self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftClick)
102 self.Bind(wx.EVT_CLOSE, self.OnClose)
104 self._updateButtonStates()
106 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
108 if self._printerConnection.hasActiveConnection() and not self._printerConnection.isActiveConnectionOpen():
109 self._printerConnection.openActiveConnection()
111 def script_setImage(self, guiImage, mapImage):
112 self._backgroundImage = wx.BitmapFromImage(wx.Image(os.path.join(self._basePath, guiImage)))
113 self._mapImage = wx.Image(os.path.join(self._basePath, mapImage))
114 self.SetClientSize(self._mapImage.GetSize())
116 def script_addColorCommand(self, r, g, b, command, data = None):
117 self._colorCommandMap[(r, g, b)] = (command, data)
119 def script_addTerminal(self, r, g, b):
120 x, y, w, h = self._getColoredRect(r, g, b)
121 if x < 0 or self._termLog is not None:
123 f = wx.Font(8, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
124 self._termLog = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.TE_DONTWRAP)
125 self._termLog.SetFont(f)
126 self._termLog.SetEditable(0)
127 self._termInput = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER)
128 self._termInput.SetFont(f)
130 self._termLog.SetPosition((x, y))
131 self._termLog.SetSize((w, h - self._termInput.GetSize().GetHeight()))
132 self._termInput.SetPosition((x, y + h - self._termInput.GetSize().GetHeight()))
133 self._termInput.SetSize((w, self._termInput.GetSize().GetHeight()))
134 self.Bind(wx.EVT_TEXT_ENTER, self.OnTermEnterLine, self._termInput)
135 self._termInput.Bind(wx.EVT_CHAR, self.OnTermKey)
137 def script_addTemperatureGraph(self, r, g, b):
138 x, y, w, h = self._getColoredRect(r, g, b)
139 if x < 0 or self._tempGraph is not None:
141 self._tempGraph = TemperatureGraph(self)
143 self._tempGraph.SetPosition((x, y))
144 self._tempGraph.SetSize((w, h))
146 def script_addProgressbar(self, r, g, b):
147 x, y, w, h = self._getColoredRect(r, g, b)
150 self._progressBar = wx.Gauge(self, -1, range=1000)
152 self._progressBar.SetPosition((x, y))
153 self._progressBar.SetSize((w, h))
155 def script_addButton(self, r, g, b, text, command, data = None):
156 x, y, w, h = self._getColoredRect(r, g, b)
159 button = wx.Button(self, -1, _(text))
160 button.SetPosition((x, y))
161 button.SetSize((w, h))
162 button.command = command
164 self._buttonList.append(button)
165 self.Bind(wx.EVT_BUTTON, lambda e: command(data), button)
167 def script_addSpinner(self, r, g, b, command, data):
168 x, y, w, h = self._getColoredRect(r, g, b)
172 def run_command(spinner):
173 value = spinner.GetValue()
174 print "Value (%s) and (%s)" % (spinner.last_value, value)
175 if spinner.last_value != '' and value != 0:
176 spinner.command(spinner.data % value)
177 spinner.last_value = value
179 spinner = wx.SpinCtrl(self, -1, style=wx.TE_PROCESS_ENTER)
180 spinner.SetRange(0, 300)
181 spinner.SetPosition((x, y))
182 spinner.SetSize((w, h))
184 spinner.command = command
186 spinner.last_value = ''
187 self._buttonList.append(spinner)
188 self.Bind(wx.EVT_SPINCTRL, lambda e: run_command(spinner), spinner)
190 def script_addTextButton(self, r_text, g_text, b_text, r_button, g_button, b_button, button_text, command, data):
191 x_text, y_text, w_text, h_text = self._getColoredRect(r_text, g_text, b_text)
194 x_button, y_button, w_button, h_button = self._getColoredRect(r_button, g_button, b_button)
197 from wx.lib.intctrl import IntCtrl
198 text = IntCtrl(self, -1)
199 text.SetBounds(0, 300)
200 text.SetPosition((x_text, y_text))
201 text.SetSize((w_text, h_text))
203 button = wx.Button(self, -1, _(button_text))
204 button.SetPosition((x_button, y_button))
205 button.SetSize((w_button, h_button))
206 button.command = command
208 self._buttonList.append(button)
209 self.Bind(wx.EVT_BUTTON, lambda e: command(data % text.GetValue()), button)
211 def _getColoredRect(self, r, g, b):
212 for x in xrange(0, self._mapImage.GetWidth()):
213 for y in xrange(0, self._mapImage.GetHeight()):
214 if self._mapImage.GetRed(x, y) == r and self._mapImage.GetGreen(x, y) == g and self._mapImage.GetBlue(x, y) == b:
216 while x+w < self._mapImage.GetWidth() and self._mapImage.GetRed(x + w, y) == r and self._mapImage.GetGreen(x + w, y) == g and self._mapImage.GetBlue(x + w, y) == b:
219 while y+h < self._mapImage.GetHeight() and self._mapImage.GetRed(x, y + h) == r and self._mapImage.GetGreen(x, y + h) == g and self._mapImage.GetBlue(x, y + h) == b:
222 print "Failed to find color: ", r, g, b
225 def script_sendGCode(self, data = None):
226 for line in data.split(';'):
229 self._printerConnection.sendCommand(line)
231 def script_sendMovementGCode(self, data = None):
232 if not self._printerConnection.isPaused() and not self._printerConnection.isPrinting():
233 self.script_sendGCode(data)
235 def script_connect(self, data = None):
236 self._printerConnection.openActiveConnection()
238 def script_startPrint(self, data = None):
239 if self._printerConnection.isPrinting() or self._printerConnection.isPaused():
240 self._printerConnection.pause(not self._printerConnection.isPaused())
242 self._printerConnection.startPrint()
244 def script_cancelPrint(self, e):
245 self._printerConnection.cancelPrint()
247 def script_pausePrint(self, e):
248 self._printerConnection.pause(not self._printerConnection.isPaused())
250 def script_showErrorLog(self, e):
251 LogWindow(self._printerConnection.getErrorLog())
253 def OnEraseBackground(self, e):
257 dc = wx.BufferedPaintDC(self, self._backgroundImage)
259 def OnLeftClick(self, e):
260 r = self._mapImage.GetRed(e.GetX(), e.GetY())
261 g = self._mapImage.GetGreen(e.GetX(), e.GetY())
262 b = self._mapImage.GetBlue(e.GetX(), e.GetY())
263 if (r, g, b) in self._colorCommandMap:
264 command = self._colorCommandMap[(r, g, b)]
265 command[0](command[1])
267 def OnClose(self, e):
268 if self._printerConnection.hasActiveConnection():
269 if self._printerConnection.isPrinting() or self._printerConnection.isPaused():
270 pass #TODO: Give warning that the close will kill the print.
271 self._printerConnection.closeActiveConnection()
272 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
273 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
274 preventComputerFromSleeping(self, False)
275 self._printerConnection.cancelPrint()
278 def OnTermEnterLine(self, e):
279 if not self._printerConnection.isAbleToSendDirectCommand():
281 line = self._termInput.GetValue()
284 self._addTermLog('> %s\n' % (line))
285 self._printerConnection.sendCommand(line)
286 self._termHistory.append(line)
287 self._termHistoryIdx = len(self._termHistory)
288 self._termInput.SetValue('')
290 def OnTermKey(self, e):
291 if len(self._termHistory) > 0:
292 if e.GetKeyCode() == wx.WXK_UP:
293 self._termHistoryIdx -= 1
294 if self._termHistoryIdx < 0:
295 self._termHistoryIdx = len(self._termHistory) - 1
296 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
297 if e.GetKeyCode() == wx.WXK_DOWN:
298 self._termHistoryIdx -= 1
299 if self._termHistoryIdx >= len(self._termHistory):
300 self._termHistoryIdx = 0
301 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
304 def _addTermLog(self, line):
305 if self._termLog is not None:
306 if len(self._termLog.GetValue()) > 10000:
307 self._termLog.SetValue(self._termLog.GetValue()[-10000:])
308 self._termLog.SetInsertionPointEnd()
309 if type(line) != unicode:
310 line = unicode(line, 'utf-8', 'replace')
311 self._termLog.AppendText(line.encode('utf-8', 'replace'))
313 def _updateButtonStates(self):
314 hasPauseButton = False
315 for button in self._buttonList:
316 if button.command == self.script_pausePrint:
317 hasPauseButton = True
320 for button in self._buttonList:
321 if button.command == self.script_connect:
322 button.Show(self._printerConnection.hasActiveConnection())
323 button.Enable(not self._printerConnection.isActiveConnectionOpen() and \
324 not self._printerConnection.isActiveConnectionOpening())
325 elif button.command == self.script_pausePrint:
326 button.Show(self._printerConnection.hasPause())
327 if not self._printerConnection.hasActiveConnection() or \
328 self._printerConnection.isActiveConnectionOpen():
329 button.Enable(self._printerConnection.isPrinting() or \
330 self._printerConnection.isPaused())
331 if self._printerConnection.isPaused():
332 button.SetLabel(_("Resume"))
334 button.SetLabel(_("Pause"))
337 elif button.command == self.script_startPrint:
338 if hasPauseButton or not self._printerConnection.hasPause():
339 if not self._printerConnection.hasActiveConnection() or \
340 self._printerConnection.isActiveConnectionOpen():
341 button.Enable(not self._printerConnection.isPrinting() and \
342 not self._printerConnection.isPaused())
346 if not self._printerConnection.hasActiveConnection() or \
347 self._printerConnection.isActiveConnectionOpen():
348 if self._printerConnection.isPrinting():
349 button.SetLabel(_("Pause"))
351 if self._printerConnection.isPaused():
352 button.SetLabel(_("Resume"))
354 button.SetLabel(_("Print"))
358 elif button.command == self.script_cancelPrint:
359 if not self._printerConnection.hasActiveConnection() or \
360 self._printerConnection.isActiveConnectionOpen():
361 button.Enable(self._printerConnection.isPrinting() or \
362 self._printerConnection.isPaused())
365 elif button.command == self.script_showErrorLog:
366 button.Show(self._printerConnection.isInErrorState())
367 if self._termInput is not None:
368 self._termInput.Enable(self._printerConnection.isAbleToSendDirectCommand())
370 def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
371 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
372 if self._tempGraph is not None:
374 for n in xrange(0, 4):
375 t = connection.getTemperature(0)
380 self._tempGraph.addPoint(temp, [0] * len(temp), connection.getBedTemperature(), 0)
382 def __doPrinterConnectionUpdate(self, connection, extraInfo):
384 if self._lastUpdateTime + 0.5 > t and extraInfo is None:
386 self._lastUpdateTime = t
388 if extraInfo is not None and len(extraInfo) > 0:
389 self._addTermLog('< %s\n' % (extraInfo))
391 self._updateButtonStates()
392 isPrinting = connection.isPrinting() or connection.isPaused()
393 if self._progressBar is not None:
395 self._progressBar.SetValue(connection.getPrintProgress() * 1000)
397 self._progressBar.SetValue(0)
398 info = connection.getStatusString()
400 if self._printerConnection.getTemperature(0) is not None:
401 info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
402 if self._printerConnection.getBedTemperature() > 0:
403 info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
404 if self._infoText is not None:
405 self._infoText.SetLabel(info)
407 self.SetTitle(info.replace('\n', ', ').strip(', '))
408 if isPrinting != self._isPrinting:
409 self._isPrinting = isPrinting
410 preventComputerFromSleeping(self, self._isPrinting)
412 class printWindowBasic(wx.Frame):
414 Printing window for USB printing, network printing, and any other type of printer connection we can think off.
415 This is only a basic window with minimal information.
417 def __init__(self, parent, printerConnection):
418 super(printWindowBasic, self).__init__(parent, -1, style=wx.CLOSE_BOX|wx.CLIP_CHILDREN|wx.CAPTION|wx.SYSTEM_MENU|wx.FRAME_TOOL_WINDOW|wx.FRAME_FLOAT_ON_PARENT, title=_("Printing on %s") % (printerConnection.getName()))
419 self._printerConnection = printerConnection
420 self._lastUpdateTime = 0
421 self._isPrinting = False
423 self.SetSizer(wx.BoxSizer())
424 self.panel = wx.Panel(self)
425 self.GetSizer().Add(self.panel, 1, flag=wx.EXPAND)
426 self.sizer = wx.GridBagSizer(2, 2)
427 self.panel.SetSizer(self.sizer)
429 self.powerWarningText = wx.StaticText(parent=self.panel,
431 label=_("Your computer is running on battery power.\nConnect your computer to AC power or your print might not finish."),
432 style=wx.ALIGN_CENTER)
433 self.powerWarningText.SetBackgroundColour('red')
434 self.powerWarningText.SetForegroundColour('white')
435 self.powerManagement = power.PowerManagement()
436 self.powerWarningTimer = wx.Timer(self)
437 self.Bind(wx.EVT_TIMER, self.OnPowerWarningChange, self.powerWarningTimer)
438 self.OnPowerWarningChange(None)
439 self.powerWarningTimer.Start(10000)
441 self.statsText = wx.StaticText(self.panel, -1, _("InfoLine from printer connection\nInfoLine from dialog\nExtra line\nMore lines for layout\nMore lines for layout\nMore lines for layout"))
443 self.connectButton = wx.Button(self.panel, -1, _("Connect"))
444 #self.loadButton = wx.Button(self.panel, -1, 'Load')
445 self.printButton = wx.Button(self.panel, -1, _("Print"))
446 self.pauseButton = wx.Button(self.panel, -1, _("Pause"))
447 self.cancelButton = wx.Button(self.panel, -1, _("Cancel print"))
448 self.errorLogButton = wx.Button(self.panel, -1, _("Error log"))
449 self.progress = wx.Gauge(self.panel, -1, range=1000)
451 self.sizer.Add(self.powerWarningText, pos=(0, 0), span=(1, 5), flag=wx.EXPAND|wx.BOTTOM, border=5)
452 self.sizer.Add(self.statsText, pos=(1, 0), span=(1, 5), flag=wx.LEFT, border=5)
453 self.sizer.Add(self.connectButton, pos=(2, 0))
454 #self.sizer.Add(self.loadButton, pos=(2,1))
455 self.sizer.Add(self.printButton, pos=(2, 1))
456 self.sizer.Add(self.pauseButton, pos=(2, 2))
457 self.sizer.Add(self.cancelButton, pos=(2, 3))
458 self.sizer.Add(self.errorLogButton, pos=(2, 4))
459 self.sizer.Add(self.progress, pos=(3, 0), span=(1, 5), flag=wx.EXPAND)
461 self.Bind(wx.EVT_CLOSE, self.OnClose)
462 self.connectButton.Bind(wx.EVT_BUTTON, self.OnConnect)
463 #self.loadButton.Bind(wx.EVT_BUTTON, self.OnLoad)
464 self.printButton.Bind(wx.EVT_BUTTON, self.OnPrint)
465 self.pauseButton.Bind(wx.EVT_BUTTON, self.OnPause)
466 self.cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel)
467 self.errorLogButton.Bind(wx.EVT_BUTTON, self.OnErrorLog)
473 self.progress.SetMinSize(self.progress.GetSize())
474 self.statsText.SetLabel('\n\n\n\n\n\n')
475 self._updateButtonStates()
477 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
479 if self._printerConnection.hasActiveConnection() and not self._printerConnection.isActiveConnectionOpen():
480 self._printerConnection.openActiveConnection()
482 def OnPowerWarningChange(self, e):
483 type = self.powerManagement.get_providing_power_source_type()
484 if type == power.POWER_TYPE_AC and self.powerWarningText.IsShown():
485 self.powerWarningText.Hide()
490 elif type != power.POWER_TYPE_AC and not self.powerWarningText.IsShown():
491 self.powerWarningText.Show()
497 def OnClose(self, e):
498 if self._printerConnection.hasActiveConnection():
499 if self._printerConnection.isPrinting() or self._printerConnection.isPaused():
500 pass #TODO: Give warning that the close will kill the print.
501 self._printerConnection.closeActiveConnection()
502 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
503 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
504 preventComputerFromSleeping(self, False)
507 def OnConnect(self, e):
508 self._printerConnection.openActiveConnection()
513 def OnPrint(self, e):
514 self._printerConnection.startPrint()
516 def OnCancel(self, e):
517 self._printerConnection.cancelPrint()
519 def OnPause(self, e):
520 self._printerConnection.pause(not self._printerConnection.isPaused())
522 def OnErrorLog(self, e):
523 LogWindow(self._printerConnection.getErrorLog())
525 def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
526 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
527 #temp = [connection.getTemperature(0)]
528 #self.temperatureGraph.addPoint(temp, [0], connection.getBedTemperature(), 0)
530 def __doPrinterConnectionUpdate(self, connection, extraInfo):
532 if self._lastUpdateTime + 0.5 > now and extraInfo is None:
534 self._lastUpdateTime = now
536 if extraInfo is not None and len(extraInfo) > 0:
537 self._addTermLog('< %s\n' % (extraInfo))
539 self._updateButtonStates()
540 onGoingPrint = connection.isPrinting() or connection.isPaused()
542 self.progress.SetValue(connection.getPrintProgress() * 1000)
544 self.progress.SetValue(0)
545 info = connection.getStatusString()
547 if self._printerConnection.getTemperature(0) is not None:
548 info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
549 if self._printerConnection.getBedTemperature() > 0:
550 info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
552 self.statsText.SetLabel(info)
553 if onGoingPrint != self._isPrinting:
554 self._isPrinting = onGoingPrint
555 preventComputerFromSleeping(self, self._isPrinting)
557 def _addTermLog(self, msg):
560 def _updateButtonStates(self):
561 self.connectButton.Show(self._printerConnection.hasActiveConnection())
562 self.connectButton.Enable(not self._printerConnection.isActiveConnectionOpen() and not self._printerConnection.isActiveConnectionOpening())
563 self.pauseButton.Show(self._printerConnection.hasPause())
564 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
565 self.printButton.Enable(not self._printerConnection.isPrinting() and \
566 not self._printerConnection.isPaused())
567 self.pauseButton.Enable(self._printerConnection.isPrinting())
568 self.cancelButton.Enable(self._printerConnection.isPrinting())
570 self.printButton.Enable(False)
571 self.pauseButton.Enable(False)
572 self.cancelButton.Enable(False)
573 self.errorLogButton.Show(self._printerConnection.isInErrorState())
575 class printWindowAdvanced(wx.Frame):
576 def __init__(self, parent, printerConnection):
577 super(printWindowAdvanced, self).__init__(parent, -1, style=wx.CLOSE_BOX|wx.CLIP_CHILDREN|wx.CAPTION|wx.SYSTEM_MENU|wx.FRAME_FLOAT_ON_PARENT|wx.MINIMIZE_BOX, title=_("Printing on %s") % (printerConnection.getName()))
578 self._printerConnection = printerConnection
579 self._lastUpdateTime = time.time()
580 self._isPrinting = False
582 self.SetSizer(wx.BoxSizer(wx.VERTICAL))
583 self.toppanel = wx.Panel(self)
584 self.topsizer = wx.GridBagSizer(2, 2)
585 self.toppanel.SetSizer(self.topsizer)
586 self.toppanel.SetBackgroundColour(wx.WHITE)
587 self.topsizer.SetEmptyCellSize((125, 1))
588 self.panel = wx.Panel(self)
589 self.sizer = wx.GridBagSizer(2, 2)
590 self.sizer.SetEmptyCellSize((125, 1))
591 self.panel.SetSizer(self.sizer)
592 self.panel.SetBackgroundColour(wx.WHITE)
593 self.GetSizer().Add(self.toppanel, 0, flag=wx.EXPAND)
594 self.GetSizer().Add(self.panel, 1, flag=wx.EXPAND)
596 self._fullscreenTemperature = None
597 self._termHistory = []
598 self._termHistoryIdx = 0
600 self._mapImage = wx.Image(resources.getPathForImage('print-window-map.png'))
601 self._colorCommandMap = {}
604 self._addMovementCommand(0, 0, 255, self._moveX, 100)
605 self._addMovementCommand(0, 0, 240, self._moveX, 10)
606 self._addMovementCommand(0, 0, 220, self._moveX, 1)
607 self._addMovementCommand(0, 0, 200, self._moveX, 0.1)
608 self._addMovementCommand(0, 0, 180, self._moveX, -0.1)
609 self._addMovementCommand(0, 0, 160, self._moveX, -1)
610 self._addMovementCommand(0, 0, 140, self._moveX, -10)
611 self._addMovementCommand(0, 0, 120, self._moveX, -100)
614 self._addMovementCommand(0, 255, 0, self._moveY, -100)
615 self._addMovementCommand(0, 240, 0, self._moveY, -10)
616 self._addMovementCommand(0, 220, 0, self._moveY, -1)
617 self._addMovementCommand(0, 200, 0, self._moveY, -0.1)
618 self._addMovementCommand(0, 180, 0, self._moveY, 0.1)
619 self._addMovementCommand(0, 160, 0, self._moveY, 1)
620 self._addMovementCommand(0, 140, 0, self._moveY, 10)
621 self._addMovementCommand(0, 120, 0, self._moveY, 100)
624 self._addMovementCommand(255, 0, 0, self._moveZ, 10)
625 self._addMovementCommand(220, 0, 0, self._moveZ, 1)
626 self._addMovementCommand(200, 0, 0, self._moveZ, 0.1)
627 self._addMovementCommand(180, 0, 0, self._moveZ, -0.1)
628 self._addMovementCommand(160, 0, 0, self._moveZ, -1)
629 self._addMovementCommand(140, 0, 0, self._moveZ, -10)
632 self._addMovementCommand(255, 80, 0, self._moveE, 10)
633 self._addMovementCommand(255, 180, 0, self._moveE, -10)
636 self._addMovementCommand(255, 255, 0, self._homeXYZ, None)
637 self._addMovementCommand(240, 255, 0, self._homeXYZ, "X")
638 self._addMovementCommand(220, 255, 0, self._homeXYZ, "Y")
639 self._addMovementCommand(200, 255, 0, self._homeXYZ, "Z")
641 self.powerWarningText = wx.StaticText(parent=self.toppanel,
643 label=_("Your computer is running on battery power.\nConnect your computer to AC power or your print might not finish."),
644 style=wx.ALIGN_CENTER)
645 self.powerWarningText.SetBackgroundColour('red')
646 self.powerWarningText.SetForegroundColour('white')
647 self.powerManagement = power.PowerManagement()
648 self.powerWarningTimer = wx.Timer(self)
649 self.Bind(wx.EVT_TIMER, self.OnPowerWarningChange, self.powerWarningTimer)
650 self.OnPowerWarningChange(None)
651 self.powerWarningTimer.Start(10000)
653 self.connectButton = wx.Button(self.toppanel, -1, _("Connect"), size=(125, 30))
654 self.printButton = wx.Button(self.toppanel, -1, _("Print"), size=(125, 30))
655 self.cancelButton = wx.Button(self.toppanel, -1, _("Cancel"), size=(125, 30))
656 self.errorLogButton = wx.Button(self.toppanel, -1, _("Error log"), size=(125, 30))
657 self.motorsOffButton = wx.Button(self.toppanel, -1, _("Motors off"), size=(125, 30))
658 self.movementBitmap = wx.StaticBitmap(self.panel, -1, wx.BitmapFromImage(wx.Image(
659 resources.getPathForImage('print-window.png'))), (0, 0))
660 self.temperatureBitmap = wx.StaticBitmap(self.panel, -1, wx.BitmapFromImage(wx.Image(
661 resources.getPathForImage('print-window-temperature.png'))), (0, 0))
662 self.temperatureField = TemperatureField(self.panel, self._setHotendTemperature)
663 self.temperatureBedBitmap = wx.StaticBitmap(self.panel, -1, wx.BitmapFromImage(wx.Image(
664 resources.getPathForImage('print-window-temperature-bed.png'))), (0, 0))
665 self.temperatureBedField = TemperatureField(self.panel, self._setBedTemperature)
666 self.temperatureGraph = TemperatureGraph(self.panel)
667 self.temperatureGraph.SetMinSize((250, 100))
668 self.progress = wx.Gauge(self.panel, -1, range=1000)
670 f = wx.Font(8, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
671 self._termLog = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE)
672 self._termLog.SetFont(f)
673 self._termLog.SetEditable(0)
674 self._termLog.SetMinSize((385, -1))
675 self._termInput = wx.TextCtrl(self.panel, style=wx.TE_PROCESS_ENTER)
676 self._termInput.SetFont(f)
678 self.Bind(wx.EVT_TEXT_ENTER, self.OnTermEnterLine, self._termInput)
679 self._termInput.Bind(wx.EVT_CHAR, self.OnTermKey)
681 self.topsizer.Add(self.powerWarningText, pos=(0, 0), span=(1, 6), flag=wx.EXPAND|wx.BOTTOM, border=5)
682 self.topsizer.Add(self.connectButton, pos=(1, 0), flag=wx.LEFT, border=2)
683 self.topsizer.Add(self.printButton, pos=(1, 1), flag=wx.LEFT, border=2)
684 self.topsizer.Add(self.cancelButton, pos=(1, 2), flag=wx.LEFT, border=2)
685 self.topsizer.Add(self.errorLogButton, pos=(1, 4), flag=wx.LEFT, border=2)
686 self.topsizer.Add(self.motorsOffButton, pos=(1, 5), flag=wx.LEFT|wx.RIGHT, border=2)
687 self.sizer.Add(self.movementBitmap, pos=(0, 0), span=(2, 3))
688 self.sizer.Add(self.temperatureGraph, pos=(2, 0), span=(4, 2), flag=wx.EXPAND)
689 self.sizer.Add(self.temperatureBitmap, pos=(2, 2))
690 self.sizer.Add(self.temperatureField, pos=(3, 2))
691 self.sizer.Add(self.temperatureBedBitmap, pos=(4, 2))
692 self.sizer.Add(self.temperatureBedField, pos=(5, 2))
693 self.sizer.Add(self._termLog, pos=(0, 3), span=(5, 3), flag=wx.EXPAND|wx.RIGHT, border=5)
694 self.sizer.Add(self._termInput, pos=(5, 3), span=(1, 3), flag=wx.EXPAND|wx.RIGHT, border=5)
695 self.sizer.Add(self.progress, pos=(6, 0), span=(1, 6), flag=wx.EXPAND|wx.BOTTOM)
697 self.Bind(wx.EVT_SIZE, self.OnSize)
698 self.Bind(wx.EVT_CLOSE, self.OnClose)
699 self.movementBitmap.Bind(wx.EVT_LEFT_DOWN, self.OnMovementClick)
700 self.temperatureGraph.Bind(wx.EVT_LEFT_UP, self.OnTemperatureClick)
701 self.connectButton.Bind(wx.EVT_BUTTON, self.OnConnect)
702 self.printButton.Bind(wx.EVT_BUTTON, self.OnPrint)
703 self.cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel)
704 self.errorLogButton.Bind(wx.EVT_BUTTON, self.OnErrorLog)
705 self.motorsOffButton.Bind(wx.EVT_BUTTON, self.OnMotorsOff)
710 self.progress.SetMinSize(self.progress.GetSize())
711 self._updateButtonStates()
713 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
715 if self._printerConnection.hasActiveConnection() and \
716 not self._printerConnection.isActiveConnectionOpen():
717 self._printerConnection.openActiveConnection()
720 # HACK ALERT: This is needed for some reason otherwise the window
721 # will be bigger than it should be until a power warning change
726 def OnClose(self, e):
727 if self._printerConnection.hasActiveConnection():
728 if self._printerConnection.isPrinting() or self._printerConnection.isPaused():
729 pass #TODO: Give warning that the close will kill the print.
730 self._printerConnection.closeActiveConnection()
731 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
732 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
733 preventComputerFromSleeping(self, False)
734 self._printerConnection.cancelPrint()
737 def OnPowerWarningChange(self, e):
738 type = self.powerManagement.get_providing_power_source_type()
739 if type == power.POWER_TYPE_AC and self.powerWarningText.IsShown():
740 self.powerWarningText.Hide()
741 self.toppanel.Layout()
745 elif type != power.POWER_TYPE_AC and not self.powerWarningText.IsShown():
746 self.powerWarningText.Show()
747 self.toppanel.Layout()
752 def OnConnect(self, e):
753 self._printerConnection.openActiveConnection()
755 def OnPrint(self, e):
756 if self._printerConnection.isPrinting() or self._printerConnection.isPaused():
757 self._printerConnection.pause(not self._printerConnection.isPaused())
759 self._printerConnection.startPrint()
761 def OnCancel(self, e):
762 self._printerConnection.cancelPrint()
764 def OnErrorLog(self, e):
765 LogWindow(self._printerConnection.getErrorLog())
767 def OnMotorsOff(self, e):
768 self._printerConnection.sendCommand("M18")
770 def GetMapRGB(self, x, y):
771 r = self._mapImage.GetRed(x, y)
772 g = self._mapImage.GetGreen(x, y)
773 b = self._mapImage.GetBlue(x, y)
776 def OnMovementClick(self, e):
777 (r, g, b) = self.GetMapRGB(e.GetX(), e.GetY())
778 if (r, g, b) in self._colorCommandMap:
779 command = self._colorCommandMap[(r, g, b)]
780 command[0](command[1])
782 def _addMovementCommand(self, r, g, b, command, step):
783 self._colorCommandMap[(r, g, b)] = (command, step)
785 def _moveXYZE(self, motor, step, feedrate):
786 # Prevent Z movement when paused and all moves when printing
787 if (not self._printerConnection.hasActiveConnection() or \
788 self._printerConnection.isActiveConnectionOpen()) and \
789 (not (self._printerConnection.isPaused() and motor == 'Z') and \
790 not self._printerConnection.isPrinting()):
791 self._printerConnection.sendCommand("G91")
792 self._printerConnection.sendCommand("G1 %s%.1f F%d" % (motor, step, feedrate))
793 self._printerConnection.sendCommand("G90")
795 def _moveX(self, step):
796 self._moveXYZE("X", step, 2000)
798 def _moveY(self, step):
799 self._moveXYZE("Y", step, 2000)
801 def _moveZ(self, step):
802 self._moveXYZE("Z", step, 200)
804 def _moveE(self, step):
806 if "lulzbot_" in profile.getMachineSetting("machine_type"):
807 toolhead_name = profile.getMachineSetting("toolhead")
808 toolhead_name = toolhead_name.lower()
809 if "flexy" in toolhead_name:
811 self._moveXYZE("E", step, feedrate)
813 def _homeXYZ(self, direction):
814 if not self._printerConnection.isPaused() and not self._printerConnection.isPrinting():
815 if direction is None:
816 self._printerConnection.sendCommand("G28")
818 self._printerConnection.sendCommand("G28 %s0" % direction)
820 def _setHotendTemperature(self, value):
821 self._printerConnection.sendCommand("M104 S%d" % value)
823 def _setBedTemperature(self, value):
824 self._printerConnection.sendCommand("M140 S%d" % value)
826 def OnTemperatureClick(self, e):
827 wx.CallAfter(self.ToggleFullScreenTemperature)
829 def ToggleFullScreenTemperature(self):
830 sizer = self.GetSizer()
831 if self._fullscreenTemperature:
832 self._fullscreenTemperature.Show(False)
833 sizer.Detach(self._fullscreenTemperature)
834 self._fullscreenTemperature.Destroy()
835 self._fullscreenTemperature = None
836 self.panel.Show(True)
838 self._fullscreenTemperature = self.temperatureGraph.Clone(self)
839 self._fullscreenTemperature.Bind(wx.EVT_LEFT_UP, self.OnTemperatureClick)
840 self._fullscreenTemperature.SetMinSize(self.panel.GetSize())
841 sizer.Add(self._fullscreenTemperature, 1, flag=wx.EXPAND)
842 self.panel.Show(False)
846 def OnTermEnterLine(self, e):
847 if not self._printerConnection.isAbleToSendDirectCommand():
849 line = self._termInput.GetValue()
852 self._addTermLog('> %s\n' % (line))
853 self._printerConnection.sendCommand(line)
854 self._termHistory.append(line)
855 self._termHistoryIdx = len(self._termHistory)
856 self._termInput.SetValue('')
858 def OnTermKey(self, e):
859 if len(self._termHistory) > 0:
860 if e.GetKeyCode() == wx.WXK_UP:
861 self._termHistoryIdx -= 1
862 if self._termHistoryIdx < 0:
863 self._termHistoryIdx = len(self._termHistory) - 1
864 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
865 if e.GetKeyCode() == wx.WXK_DOWN:
866 self._termHistoryIdx -= 1
867 if self._termHistoryIdx >= len(self._termHistory):
868 self._termHistoryIdx = 0
869 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
872 def _addTermLog(self, line):
873 if self._termLog is not None:
874 if len(self._termLog.GetValue()) > 10000:
875 self._termLog.SetValue(self._termLog.GetValue()[-10000:])
876 self._termLog.SetInsertionPointEnd()
877 if type(line) != unicode:
878 line = unicode(line, 'utf-8', 'replace')
879 self._termLog.AppendText(line.encode('utf-8', 'replace'))
881 def _updateButtonStates(self):
882 self.connectButton.Show(self._printerConnection.hasActiveConnection())
883 self.connectButton.Enable(not self._printerConnection.isActiveConnectionOpen() and \
884 not self._printerConnection.isActiveConnectionOpening())
885 if not self._printerConnection.hasPause():
886 if not self._printerConnection.hasActiveConnection() or \
887 self._printerConnection.isActiveConnectionOpen():
888 self.printButton.Enable(not self._printerConnection.isPrinting() and \
889 not self._printerConnection.isPaused())
891 self.printButton.Enable(False)
893 if not self._printerConnection.hasActiveConnection() or \
894 self._printerConnection.isActiveConnectionOpen():
895 if self._printerConnection.isPrinting():
896 self.printButton.SetLabel(_("Pause"))
898 if self._printerConnection.isPaused():
899 self.printButton.SetLabel(_("Resume"))
901 self.printButton.SetLabel(_("Print"))
902 self.printButton.Enable(True)
904 self.printButton.Enable(False)
905 if not self._printerConnection.hasActiveConnection() or \
906 self._printerConnection.isActiveConnectionOpen():
907 self.cancelButton.Enable(self._printerConnection.isPrinting() or \
908 self._printerConnection.isPaused())
910 self.cancelButton.Enable(False)
911 self.errorLogButton.Show(self._printerConnection.isInErrorState())
912 self._termInput.Enable(self._printerConnection.isAbleToSendDirectCommand())
915 def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
916 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
918 for n in xrange(0, 4):
919 t = connection.getTemperature(0)
924 self.temperatureGraph.addPoint(temp, [0] * len(temp), connection.getBedTemperature(), 0)
925 if self._fullscreenTemperature is not None:
926 self._fullscreenTemperature.addPoint(temp, [0] * len(temp), connection.getBedTemperature(), 0)
928 def __doPrinterConnectionUpdate(self, connection, extraInfo):
930 if self._lastUpdateTime + 0.5 > t and extraInfo is None:
932 self._lastUpdateTime = t
934 if extraInfo is not None and len(extraInfo) > 0:
935 self._addTermLog('< %s\n' % (extraInfo))
937 self._updateButtonStates()
938 isPrinting = connection.isPrinting() or connection.isPaused()
940 self.progress.SetValue(connection.getPrintProgress() * 1000)
942 self.progress.SetValue(0)
943 info = connection.getStatusString()
945 if self._printerConnection.getTemperature(0) is not None:
946 info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
947 if self._printerConnection.getBedTemperature() > 0:
948 info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
949 self.SetTitle(info.replace('\n', ', ').strip(', '))
950 if isPrinting != self._isPrinting:
951 self._isPrinting = isPrinting
952 preventComputerFromSleeping(self, self._isPrinting)
954 class TemperatureField(wx.Panel):
955 def __init__(self, parent, callback):
956 super(TemperatureField, self).__init__(parent)
957 self.callback = callback
959 self.SetBackgroundColour(wx.WHITE)
961 self.text = IntCtrl(self, -1)
962 self.text.SetBounds(0, 300)
963 self.text.SetSize((60, 28))
965 self.unit = wx.StaticBitmap(self, -1, wx.BitmapFromImage(wx.Image(
966 resources.getPathForImage('print-window-temperature-unit.png'))), (0, 0))
968 self.button = wx.Button(self, -1, _("Set"))
969 self.button.SetSize((35, 25))
970 self.Bind(wx.EVT_BUTTON, lambda e: self.callback(self.text.GetValue()), self.button)
972 self.text.SetPosition((0, 0))
973 self.unit.SetPosition((60, 0))
974 self.button.SetPosition((90, 0))
977 class TemperatureGraph(wx.Panel):
978 def __init__(self, parent):
979 super(TemperatureGraph, self).__init__(parent)
981 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
982 self.Bind(wx.EVT_SIZE, self.OnSize)
983 self.Bind(wx.EVT_PAINT, self.OnDraw)
985 self._lastDraw = time.time() - 1.0
987 self._backBuffer = None
988 self.addPoint([0]*16, [0]*16, 0, 0)
990 def Clone(self, parent):
991 clone = TemperatureGraph(parent)
992 clone._points = list(self._points)
995 def OnEraseBackground(self, e):
999 if self._backBuffer is None or self.GetSize() != self._backBuffer.GetSize():
1000 self._backBuffer = wx.EmptyBitmap(*self.GetSizeTuple())
1001 self.UpdateDrawing(True)
1003 def OnDraw(self, e):
1004 dc = wx.BufferedPaintDC(self, self._backBuffer)
1006 def UpdateDrawing(self, force=False):
1008 if (not force and now - self._lastDraw < 1.0) or self._backBuffer is None:
1010 self._lastDraw = now
1012 dc.SelectObject(self._backBuffer)
1013 dc.SetBackground(wx.Brush(wx.WHITE))
1015 dc.SetFont(wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT))
1016 w, h = self.GetSizeTuple()
1017 bgLinePen = wx.Pen('#A0A0A0')
1018 tempPen = wx.Pen('#FF4040')
1019 tempSPPen = wx.Pen('#FFA0A0')
1020 tempPenBG = wx.Pen('#FFD0D0')
1021 bedTempPen = wx.Pen('#4040FF')
1022 bedTempSPPen = wx.Pen('#A0A0FF')
1023 bedTempPenBG = wx.Pen('#D0D0FF')
1025 #Draw the background up to the current temperatures.
1031 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
1032 x1 = int(w - (now - t))
1033 for x in xrange(x0, x1 + 1):
1034 for n in xrange(0, min(len(t0), len(temp))):
1035 t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
1036 dc.SetPen(tempPenBG)
1037 dc.DrawLine(x, h, x, h - (t * h / 350))
1038 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
1039 dc.SetPen(bedTempPenBG)
1040 dc.DrawLine(x, h, x, h - (bt * h / 350))
1048 for x in xrange(w, 0, -30):
1049 dc.SetPen(bgLinePen)
1050 dc.DrawLine(x, 0, x, h)
1052 for y in xrange(h - 1, 0, -h * 50 / 350):
1053 dc.SetPen(bgLinePen)
1054 dc.DrawLine(0, y, w, y)
1055 dc.DrawText(str(tmpNr), 0, y - dc.GetFont().GetPixelSize().GetHeight())
1057 dc.DrawLine(0, 0, w, 0)
1058 dc.DrawLine(0, 0, 0, h)
1060 #Draw the main lines
1066 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
1067 x1 = int(w - (now - t))
1068 for x in xrange(x0, x1 + 1):
1069 for n in xrange(0, min(len(t0), len(temp))):
1070 t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
1071 tSP = float(x - x0) / float(x1 - x0 + 1) * (tempSP[n] - tSP0[n]) + tSP0[n]
1072 dc.SetPen(tempSPPen)
1073 dc.DrawPoint(x, h - (tSP * h / 350))
1075 dc.DrawPoint(x, h - (t * h / 350))
1076 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
1077 btSP = float(x - x0) / float(x1 - x0 + 1) * (bedTempSP - btSP0) + btSP0
1078 dc.SetPen(bedTempSPPen)
1079 dc.DrawPoint(x, h - (btSP * h / 350))
1080 dc.SetPen(bedTempPen)
1081 dc.DrawPoint(x, h - (bt * h / 350))
1089 self.Refresh(eraseBackground=False)
1092 if len(self._points) > 0 and (time.time() - self._points[0][4]) > w + 20:
1095 def addPoint(self, temp, tempSP, bedTemp, bedTempSP):
1096 if len(self._points) > 0 and time.time() - self._points[-1][4] < 0.5:
1098 for n in xrange(0, len(temp)):
1101 for n in xrange(0, len(tempSP)):
1102 if tempSP[n] is None:
1106 if bedTempSP is None:
1108 self._points.append((temp[:], tempSP[:], bedTemp, bedTempSP, time.time()))
1109 wx.CallAfter(self.UpdateDrawing)
1111 class LogWindow(wx.Frame):
1112 def __init__(self, logText):
1113 super(LogWindow, self).__init__(None, title=_("Error log"))
1114 self.textBox = wx.TextCtrl(self, -1, logText, style=wx.TE_MULTILINE | wx.TE_DONTWRAP | wx.TE_READONLY)
1115 self.SetSize((500, 400))