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
13 #TODO: This does not belong here!
14 if sys.platform.startswith('win'):
15 def preventComputerFromSleeping(frame, prevent):
17 Function used to prevent the computer from going into sleep mode.
18 :param prevent: True = Prevent the system from going to sleep from this point on.
19 :param prevent: False = No longer prevent the system from going to sleep.
21 ES_CONTINUOUS = 0x80000000
22 ES_SYSTEM_REQUIRED = 0x00000001
23 ES_AWAYMODE_REQUIRED = 0x00000040
24 #SetThreadExecutionState returns 0 when failed, which is ignored. The function should be supported from windows XP and up.
26 # For Vista and up we use ES_AWAYMODE_REQUIRED to prevent a print from failing if the PC does go to sleep
27 # As it's not supported on XP, we catch the error and fallback to using ES_SYSTEM_REQUIRED only
28 if ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED) == 0:
29 ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED)
31 ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS)
33 elif sys.platform.startswith('darwin'):
35 bundle = objc.initFrameworkWrapper("IOKit",
36 frameworkIdentifier="com.apple.iokit",
37 frameworkPath=objc.pathForFramework("/System/Library/Frameworks/IOKit.framework"),
39 objc.loadBundleFunctions(bundle, globals(), [("IOPMAssertionCreateWithName", b"i@I@o^I")])
40 def preventComputerFromSleeping(frame, prevent):
42 success, preventComputerFromSleeping.assertionID = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, "Cura is printing", None)
43 if success != kIOReturnSuccess:
44 preventComputerFromSleeping.assertionID = None
46 if preventComputerFromSleeping.assertionID is not None:
47 IOPMAssertionRelease(preventComputerFromSleeping.assertionID)
48 preventComputerFromSleeping.assertionID = None
50 def preventComputerFromSleeping(frame, prevent):
51 if os.path.isfile("/usr/bin/xdg-screensaver"):
53 cmd = ['xdg-screensaver', 'suspend' if prevent else 'resume', str(frame.GetHandle())]
58 class printWindowPlugin(wx.Frame):
59 def __init__(self, parent, printerConnection, filename):
60 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()))
61 self._printerConnection = printerConnection
62 self._basePath = os.path.dirname(filename)
63 self._backgroundImage = None
64 self._colorCommandMap = {}
67 self._termInput = None
68 self._termHistory = []
69 self._termHistoryIdx = 0
70 self._progressBar = None
71 self._tempGraph = None
73 self._lastUpdateTime = time.time()
74 self._isPrinting = False
77 'setImage': self.script_setImage,
78 'addColorCommand': self.script_addColorCommand,
79 'addTerminal': self.script_addTerminal,
80 'addTemperatureGraph': self.script_addTemperatureGraph,
81 'addProgressbar': self.script_addProgressbar,
82 'addButton': self.script_addButton,
83 'addSpinner': self.script_addSpinner,
84 'addTextButton': self.script_addTextButton,
86 'sendGCode': self.script_sendGCode,
87 'sendMovementGCode': self.script_sendMovementGCode,
88 'connect': self.script_connect,
89 'startPrint': self.script_startPrint,
90 'pausePrint': self.script_pausePrint,
91 'cancelPrint': self.script_cancelPrint,
92 'showErrorLog': self.script_showErrorLog,
94 execfile(filename, variables, variables)
96 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
97 self.Bind(wx.EVT_PAINT, self.OnDraw)
98 self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftClick)
99 self.Bind(wx.EVT_CLOSE, self.OnClose)
101 self._updateButtonStates()
103 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
105 if self._printerConnection.hasActiveConnection() and not self._printerConnection.isActiveConnectionOpen():
106 self._printerConnection.openActiveConnection()
108 def script_setImage(self, guiImage, mapImage):
109 self._backgroundImage = wx.BitmapFromImage(wx.Image(os.path.join(self._basePath, guiImage)))
110 self._mapImage = wx.Image(os.path.join(self._basePath, mapImage))
111 self.SetClientSize(self._mapImage.GetSize())
113 def script_addColorCommand(self, r, g, b, command, data = None):
114 self._colorCommandMap[(r, g, b)] = (command, data)
116 def script_addTerminal(self, r, g, b):
117 x, y, w, h = self._getColoredRect(r, g, b)
118 if x < 0 or self._termLog is not None:
120 f = wx.Font(8, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
121 self._termLog = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.TE_DONTWRAP)
122 self._termLog.SetFont(f)
123 self._termLog.SetEditable(0)
124 self._termInput = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER)
125 self._termInput.SetFont(f)
127 self._termLog.SetPosition((x, y))
128 self._termLog.SetSize((w, h - self._termInput.GetSize().GetHeight()))
129 self._termInput.SetPosition((x, y + h - self._termInput.GetSize().GetHeight()))
130 self._termInput.SetSize((w, self._termInput.GetSize().GetHeight()))
131 self.Bind(wx.EVT_TEXT_ENTER, self.OnTermEnterLine, self._termInput)
132 self._termInput.Bind(wx.EVT_CHAR, self.OnTermKey)
134 def script_addTemperatureGraph(self, r, g, b):
135 x, y, w, h = self._getColoredRect(r, g, b)
136 if x < 0 or self._tempGraph is not None:
138 self._tempGraph = TemperatureGraph(self)
140 self._tempGraph.SetPosition((x, y))
141 self._tempGraph.SetSize((w, h))
143 def script_addProgressbar(self, r, g, b):
144 x, y, w, h = self._getColoredRect(r, g, b)
147 self._progressBar = wx.Gauge(self, -1, range=1000)
149 self._progressBar.SetPosition((x, y))
150 self._progressBar.SetSize((w, h))
152 def script_addButton(self, r, g, b, text, command, data = None):
153 x, y, w, h = self._getColoredRect(r, g, b)
156 button = wx.Button(self, -1, _(text))
157 button.SetPosition((x, y))
158 button.SetSize((w, h))
159 button.command = command
161 self._buttonList.append(button)
162 self.Bind(wx.EVT_BUTTON, lambda e: command(data), button)
164 def script_addSpinner(self, r, g, b, command, data):
165 x, y, w, h = self._getColoredRect(r, g, b)
169 def run_command(spinner):
170 value = spinner.GetValue()
171 print "Value (%s) and (%s)" % (spinner.last_value, value)
172 if spinner.last_value != '' and value != 0:
173 spinner.command(spinner.data % value)
174 spinner.last_value = value
176 spinner = wx.SpinCtrl(self, -1, style=wx.TE_PROCESS_ENTER)
177 spinner.SetRange(0, 300)
178 spinner.SetPosition((x, y))
179 spinner.SetSize((w, h))
181 spinner.command = command
183 spinner.last_value = ''
184 self._buttonList.append(spinner)
185 self.Bind(wx.EVT_SPINCTRL, lambda e: run_command(spinner), spinner)
187 def script_addTextButton(self, r_text, g_text, b_text, r_button, g_button, b_button, button_text, command, data):
188 x_text, y_text, w_text, h_text = self._getColoredRect(r_text, g_text, b_text)
191 x_button, y_button, w_button, h_button = self._getColoredRect(r_button, g_button, b_button)
194 from wx.lib.intctrl import IntCtrl
195 text = IntCtrl(self, -1)
196 text.SetBounds(0, 300)
197 text.SetPosition((x_text, y_text))
198 text.SetSize((w_text, h_text))
200 button = wx.Button(self, -1, _(button_text))
201 button.SetPosition((x_button, y_button))
202 button.SetSize((w_button, h_button))
203 button.command = command
205 self._buttonList.append(button)
206 self.Bind(wx.EVT_BUTTON, lambda e: command(data % text.GetValue()), button)
208 def _getColoredRect(self, r, g, b):
209 for x in xrange(0, self._mapImage.GetWidth()):
210 for y in xrange(0, self._mapImage.GetHeight()):
211 if self._mapImage.GetRed(x, y) == r and self._mapImage.GetGreen(x, y) == g and self._mapImage.GetBlue(x, y) == b:
213 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:
216 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:
219 print "Failed to find color: ", r, g, b
222 def script_sendGCode(self, data = None):
223 for line in data.split(';'):
226 self._printerConnection.sendCommand(line)
228 def script_sendMovementGCode(self, data = None):
229 if not self._printerConnection.isPaused() and not self._printerConnection.isPrinting():
230 self.script_sendGCode(data)
232 def script_connect(self, data = None):
233 self._printerConnection.openActiveConnection()
235 def script_startPrint(self, data = None):
236 if self._printerConnection.isPrinting() or self._printerConnection.isPaused():
237 self._printerConnection.pause(not self._printerConnection.isPaused())
239 self._printerConnection.startPrint()
241 def script_cancelPrint(self, e):
242 self._printerConnection.cancelPrint()
244 def script_pausePrint(self, e):
245 self._printerConnection.pause(not self._printerConnection.isPaused())
247 def script_showErrorLog(self, e):
248 LogWindow(self._printerConnection.getErrorLog())
250 def OnEraseBackground(self, e):
254 dc = wx.BufferedPaintDC(self, self._backgroundImage)
256 def OnLeftClick(self, e):
257 r = self._mapImage.GetRed(e.GetX(), e.GetY())
258 g = self._mapImage.GetGreen(e.GetX(), e.GetY())
259 b = self._mapImage.GetBlue(e.GetX(), e.GetY())
260 if (r, g, b) in self._colorCommandMap:
261 command = self._colorCommandMap[(r, g, b)]
262 command[0](command[1])
264 def OnClose(self, e):
265 if self._printerConnection.hasActiveConnection():
266 if self._printerConnection.isPrinting() or self._printerConnection.isPaused():
267 pass #TODO: Give warning that the close will kill the print.
268 self._printerConnection.closeActiveConnection()
269 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
270 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
271 preventComputerFromSleeping(self, False)
272 self._printerConnection.cancelPrint()
275 def OnTermEnterLine(self, e):
276 if not self._printerConnection.isAbleToSendDirectCommand():
278 line = self._termInput.GetValue()
281 self._addTermLog('> %s\n' % (line))
282 self._printerConnection.sendCommand(line)
283 self._termHistory.append(line)
284 self._termHistoryIdx = len(self._termHistory)
285 self._termInput.SetValue('')
287 def OnTermKey(self, e):
288 if len(self._termHistory) > 0:
289 if e.GetKeyCode() == wx.WXK_UP:
290 self._termHistoryIdx -= 1
291 if self._termHistoryIdx < 0:
292 self._termHistoryIdx = len(self._termHistory) - 1
293 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
294 if e.GetKeyCode() == wx.WXK_DOWN:
295 self._termHistoryIdx -= 1
296 if self._termHistoryIdx >= len(self._termHistory):
297 self._termHistoryIdx = 0
298 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
301 def _addTermLog(self, line):
302 if self._termLog is not None:
303 if len(self._termLog.GetValue()) > 10000:
304 self._termLog.SetValue(self._termLog.GetValue()[-10000:])
305 self._termLog.SetInsertionPointEnd()
306 if type(line) != unicode:
307 line = unicode(line, 'utf-8', 'replace')
308 self._termLog.AppendText(line.encode('utf-8', 'replace'))
310 def _updateButtonStates(self):
311 hasPauseButton = False
312 for button in self._buttonList:
313 if button.command == self.script_pausePrint:
314 hasPauseButton = True
317 for button in self._buttonList:
318 if button.command == self.script_connect:
319 button.Show(self._printerConnection.hasActiveConnection())
320 button.Enable(not self._printerConnection.isActiveConnectionOpen() and \
321 not self._printerConnection.isActiveConnectionOpening())
322 elif button.command == self.script_pausePrint:
323 button.Show(self._printerConnection.hasPause())
324 if not self._printerConnection.hasActiveConnection() or \
325 self._printerConnection.isActiveConnectionOpen():
326 button.Enable(self._printerConnection.isPrinting() or \
327 self._printerConnection.isPaused())
328 if self._printerConnection.isPaused():
329 button.SetLabel(_("Resume"))
331 button.SetLabel(_("Pause"))
334 elif button.command == self.script_startPrint:
335 if hasPauseButton or not self._printerConnection.hasPause():
336 if not self._printerConnection.hasActiveConnection() or \
337 self._printerConnection.isActiveConnectionOpen():
338 button.Enable(not self._printerConnection.isPrinting() and \
339 not self._printerConnection.isPaused())
343 if not self._printerConnection.hasActiveConnection() or \
344 self._printerConnection.isActiveConnectionOpen():
345 if self._printerConnection.isPrinting():
346 button.SetLabel(_("Pause"))
348 if self._printerConnection.isPaused():
349 button.SetLabel(_("Resume"))
351 button.SetLabel(_("Print"))
355 elif button.command == self.script_cancelPrint:
356 if not self._printerConnection.hasActiveConnection() or \
357 self._printerConnection.isActiveConnectionOpen():
358 button.Enable(self._printerConnection.isPrinting() or \
359 self._printerConnection.isPaused())
362 elif button.command == self.script_showErrorLog:
363 button.Show(self._printerConnection.isInErrorState())
364 if self._termInput is not None:
365 self._termInput.Enable(self._printerConnection.isAbleToSendDirectCommand())
367 def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
368 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
369 if self._tempGraph is not None:
371 for n in xrange(0, 4):
372 t = connection.getTemperature(0)
377 self._tempGraph.addPoint(temp, [0] * len(temp), connection.getBedTemperature(), 0)
379 def __doPrinterConnectionUpdate(self, connection, extraInfo):
381 if self._lastUpdateTime + 0.5 > t and extraInfo is None:
383 self._lastUpdateTime = t
385 if extraInfo is not None and len(extraInfo) > 0:
386 self._addTermLog('< %s\n' % (extraInfo))
388 self._updateButtonStates()
389 isPrinting = connection.isPrinting() or connection.isPaused()
390 if self._progressBar is not None:
392 self._progressBar.SetValue(connection.getPrintProgress() * 1000)
394 self._progressBar.SetValue(0)
395 info = connection.getStatusString()
397 if self._printerConnection.getTemperature(0) is not None:
398 info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
399 if self._printerConnection.getBedTemperature() > 0:
400 info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
401 if self._infoText is not None:
402 self._infoText.SetLabel(info)
404 self.SetTitle(info.replace('\n', ', '))
405 if isPrinting != self._isPrinting:
406 self._isPrinting = isPrinting
407 preventComputerFromSleeping(self, self._isPrinting)
409 class printWindowBasic(wx.Frame):
411 Printing window for USB printing, network printing, and any other type of printer connection we can think off.
412 This is only a basic window with minimal information.
414 def __init__(self, parent, printerConnection):
415 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()))
416 self._printerConnection = printerConnection
417 self._lastUpdateTime = 0
418 self._isPrinting = False
420 self.SetSizer(wx.BoxSizer())
421 self.panel = wx.Panel(self)
422 self.GetSizer().Add(self.panel, 1, flag=wx.EXPAND)
423 self.sizer = wx.GridBagSizer(2, 2)
424 self.panel.SetSizer(self.sizer)
426 self.powerWarningText = wx.StaticText(parent=self.panel,
428 label=_("Your computer is running on battery power.\nConnect your computer to AC power or your print might not finish."),
429 style=wx.ALIGN_CENTER)
430 self.powerWarningText.SetBackgroundColour('red')
431 self.powerWarningText.SetForegroundColour('white')
432 self.powerManagement = power.PowerManagement()
433 self.powerWarningTimer = wx.Timer(self)
434 self.Bind(wx.EVT_TIMER, self.OnPowerWarningChange, self.powerWarningTimer)
435 self.OnPowerWarningChange(None)
436 self.powerWarningTimer.Start(10000)
438 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"))
440 self.connectButton = wx.Button(self.panel, -1, _("Connect"))
441 #self.loadButton = wx.Button(self.panel, -1, 'Load')
442 self.printButton = wx.Button(self.panel, -1, _("Print"))
443 self.pauseButton = wx.Button(self.panel, -1, _("Pause"))
444 self.cancelButton = wx.Button(self.panel, -1, _("Cancel print"))
445 self.errorLogButton = wx.Button(self.panel, -1, _("Error log"))
446 self.progress = wx.Gauge(self.panel, -1, range=1000)
448 self.sizer.Add(self.powerWarningText, pos=(0, 0), span=(1, 5), flag=wx.EXPAND|wx.BOTTOM, border=5)
449 self.sizer.Add(self.statsText, pos=(1, 0), span=(1, 5), flag=wx.LEFT, border=5)
450 self.sizer.Add(self.connectButton, pos=(2, 0))
451 #self.sizer.Add(self.loadButton, pos=(2,1))
452 self.sizer.Add(self.printButton, pos=(2, 1))
453 self.sizer.Add(self.pauseButton, pos=(2, 2))
454 self.sizer.Add(self.cancelButton, pos=(2, 3))
455 self.sizer.Add(self.errorLogButton, pos=(2, 4))
456 self.sizer.Add(self.progress, pos=(3, 0), span=(1, 5), flag=wx.EXPAND)
458 self.Bind(wx.EVT_CLOSE, self.OnClose)
459 self.connectButton.Bind(wx.EVT_BUTTON, self.OnConnect)
460 #self.loadButton.Bind(wx.EVT_BUTTON, self.OnLoad)
461 self.printButton.Bind(wx.EVT_BUTTON, self.OnPrint)
462 self.pauseButton.Bind(wx.EVT_BUTTON, self.OnPause)
463 self.cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel)
464 self.errorLogButton.Bind(wx.EVT_BUTTON, self.OnErrorLog)
470 self.progress.SetMinSize(self.progress.GetSize())
471 self.statsText.SetLabel('\n\n\n\n\n\n')
472 self._updateButtonStates()
474 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
476 if self._printerConnection.hasActiveConnection() and not self._printerConnection.isActiveConnectionOpen():
477 self._printerConnection.openActiveConnection()
479 def OnPowerWarningChange(self, e):
480 type = self.powerManagement.get_providing_power_source_type()
481 if type == power.POWER_TYPE_AC and self.powerWarningText.IsShown():
482 self.powerWarningText.Hide()
487 elif type != power.POWER_TYPE_AC and not self.powerWarningText.IsShown():
488 self.powerWarningText.Show()
494 def OnClose(self, e):
495 if self._printerConnection.hasActiveConnection():
496 if self._printerConnection.isPrinting() or self._printerConnection.isPaused():
497 pass #TODO: Give warning that the close will kill the print.
498 self._printerConnection.closeActiveConnection()
499 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
500 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
501 preventComputerFromSleeping(self, False)
504 def OnConnect(self, e):
505 self._printerConnection.openActiveConnection()
510 def OnPrint(self, e):
511 self._printerConnection.startPrint()
513 def OnCancel(self, e):
514 self._printerConnection.cancelPrint()
516 def OnPause(self, e):
517 self._printerConnection.pause(not self._printerConnection.isPaused())
519 def OnErrorLog(self, e):
520 LogWindow(self._printerConnection.getErrorLog())
522 def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
523 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
524 #temp = [connection.getTemperature(0)]
525 #self.temperatureGraph.addPoint(temp, [0], connection.getBedTemperature(), 0)
527 def __doPrinterConnectionUpdate(self, connection, extraInfo):
529 if self._lastUpdateTime + 0.5 > now and extraInfo is None:
531 self._lastUpdateTime = now
533 if extraInfo is not None and len(extraInfo) > 0:
534 self._addTermLog('< %s\n' % (extraInfo))
536 self._updateButtonStates()
537 onGoingPrint = connection.isPrinting() or connection.isPaused()
539 self.progress.SetValue(connection.getPrintProgress() * 1000)
541 self.progress.SetValue(0)
542 info = connection.getStatusString()
544 if self._printerConnection.getTemperature(0) is not None:
545 info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
546 if self._printerConnection.getBedTemperature() > 0:
547 info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
549 self.statsText.SetLabel(info)
550 if onGoingPrint != self._isPrinting:
551 self._isPrinting = onGoingPrint
552 preventComputerFromSleeping(self, self._isPrinting)
554 def _addTermLog(self, msg):
557 def _updateButtonStates(self):
558 self.connectButton.Show(self._printerConnection.hasActiveConnection())
559 self.connectButton.Enable(not self._printerConnection.isActiveConnectionOpen() and not self._printerConnection.isActiveConnectionOpening())
560 self.pauseButton.Show(self._printerConnection.hasPause())
561 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
562 self.printButton.Enable(not self._printerConnection.isPrinting() and \
563 not self._printerConnection.isPaused())
564 self.pauseButton.Enable(self._printerConnection.isPrinting())
565 self.cancelButton.Enable(self._printerConnection.isPrinting())
567 self.printButton.Enable(False)
568 self.pauseButton.Enable(False)
569 self.cancelButton.Enable(False)
570 self.errorLogButton.Show(self._printerConnection.isInErrorState())
572 class printWindowAdvanced(wx.Frame):
573 def __init__(self, parent, printerConnection):
574 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()))
575 self._printerConnection = printerConnection
576 self._lastUpdateTime = time.time()
577 self._isPrinting = False
579 self.SetSizer(wx.BoxSizer(wx.VERTICAL))
580 self.toppanel = wx.Panel(self)
581 self.topsizer = wx.GridBagSizer(2, 2)
582 self.toppanel.SetSizer(self.topsizer)
583 self.toppanel.SetBackgroundColour(wx.WHITE)
584 self.topsizer.SetEmptyCellSize((125, 1))
585 self.panel = wx.Panel(self)
586 self.sizer = wx.GridBagSizer(2, 2)
587 self.panel.SetSizer(self.sizer)
588 self.panel.SetBackgroundColour(wx.WHITE)
589 self.GetSizer().Add(self.toppanel, 0, flag=wx.EXPAND)
590 self.GetSizer().Add(self.panel, 1, flag=wx.EXPAND)
592 self._fullscreenTemperature = None
593 self._termHistory = []
594 self._termHistoryIdx = 0
596 self._mapImage = wx.Image(resources.getPathForImage('print-window-map.png'))
597 self._colorCommandMap = {}
600 self._addMovementCommand(0, 0, 255, self._moveX, 100)
601 self._addMovementCommand(0, 0, 240, self._moveX, 10)
602 self._addMovementCommand(0, 0, 220, self._moveX, 1)
603 self._addMovementCommand(0, 0, 200, self._moveX, 0.1)
604 self._addMovementCommand(0, 0, 180, self._moveX, -0.1)
605 self._addMovementCommand(0, 0, 160, self._moveX, -1)
606 self._addMovementCommand(0, 0, 140, self._moveX, -10)
607 self._addMovementCommand(0, 0, 120, self._moveX, -100)
610 self._addMovementCommand(0, 255, 0, self._moveY, -100)
611 self._addMovementCommand(0, 240, 0, self._moveY, -10)
612 self._addMovementCommand(0, 220, 0, self._moveY, -1)
613 self._addMovementCommand(0, 200, 0, self._moveY, -0.1)
614 self._addMovementCommand(0, 180, 0, self._moveY, 0.1)
615 self._addMovementCommand(0, 160, 0, self._moveY, 1)
616 self._addMovementCommand(0, 140, 0, self._moveY, 10)
617 self._addMovementCommand(0, 120, 0, self._moveY, 100)
620 self._addMovementCommand(255, 0, 0, self._moveZ, 10)
621 self._addMovementCommand(220, 0, 0, self._moveZ, 1)
622 self._addMovementCommand(200, 0, 0, self._moveZ, 0.1)
623 self._addMovementCommand(180, 0, 0, self._moveZ, -0.1)
624 self._addMovementCommand(160, 0, 0, self._moveZ, -1)
625 self._addMovementCommand(140, 0, 0, self._moveZ, -10)
628 self._addMovementCommand(255, 80, 0, self._moveE, 10)
629 self._addMovementCommand(255, 180, 0, self._moveE, -10)
632 self._addMovementCommand(255, 255, 0, self._homeXYZ, None)
633 self._addMovementCommand(240, 255, 0, self._homeXYZ, "X")
634 self._addMovementCommand(220, 255, 0, self._homeXYZ, "Y")
635 self._addMovementCommand(200, 255, 0, self._homeXYZ, "Z")
637 self.powerWarningText = wx.StaticText(parent=self.toppanel,
639 label=_("Your computer is running on battery power.\nConnect your computer to AC power or your print might not finish."),
640 style=wx.ALIGN_CENTER)
641 self.powerWarningText.SetBackgroundColour('red')
642 self.powerWarningText.SetForegroundColour('white')
643 self.powerManagement = power.PowerManagement()
644 self.powerWarningTimer = wx.Timer(self)
645 self.Bind(wx.EVT_TIMER, self.OnPowerWarningChange, self.powerWarningTimer)
646 self.OnPowerWarningChange(None)
647 self.powerWarningTimer.Start(10000)
649 self.connectButton = wx.Button(self.toppanel, -1, _("Connect"), size=(125, 30))
650 self.printButton = wx.Button(self.toppanel, -1, _("Print"), size=(125, 30))
651 self.cancelButton = wx.Button(self.toppanel, -1, _("Cancel"), size=(125, 30))
652 self.errorLogButton = wx.Button(self.toppanel, -1, _("Error log"), size=(125, 30))
653 self.motorsOffButton = wx.Button(self.toppanel, -1, _("Motors off"), size=(125, 30))
654 self.movementBitmap = wx.StaticBitmap(self.panel, -1, wx.BitmapFromImage(wx.Image(
655 resources.getPathForImage('print-window.png'))), (0, 0))
656 self.temperatureBitmap = wx.StaticBitmap(self.panel, -1, wx.BitmapFromImage(wx.Image(
657 resources.getPathForImage('print-window-temperature.png'))), (0, 0))
658 self.temperatureField = TemperatureField(self.panel, self._setHotendTemperature)
659 self.temperatureBedBitmap = wx.StaticBitmap(self.panel, -1, wx.BitmapFromImage(wx.Image(
660 resources.getPathForImage('print-window-temperature-bed.png'))), (0, 0))
661 self.temperatureBedField = TemperatureField(self.panel, self._setBedTemperature)
662 self.temperatureGraph = TemperatureGraph(self.panel)
663 self.progress = wx.Gauge(self.panel, -1, range=1000)
665 f = wx.Font(8, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
666 self._termLog = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE | wx.TE_DONTWRAP)
667 self._termLog.SetFont(f)
668 self._termLog.SetEditable(0)
669 self._termLog.SetMinSize((385, -1))
670 self._termInput = wx.TextCtrl(self.panel, style=wx.TE_PROCESS_ENTER)
671 self._termInput.SetFont(f)
673 self.Bind(wx.EVT_TEXT_ENTER, self.OnTermEnterLine, self._termInput)
674 self._termInput.Bind(wx.EVT_CHAR, self.OnTermKey)
676 self.topsizer.Add(self.powerWarningText, pos=(0, 0), span=(1, 6), flag=wx.EXPAND|wx.BOTTOM, border=5)
677 self.topsizer.Add(self.connectButton, pos=(1, 0), flag=wx.LEFT, border=2)
678 self.topsizer.Add(self.printButton, pos=(1, 1), flag=wx.LEFT, border=2)
679 self.topsizer.Add(self.cancelButton, pos=(1, 2), flag=wx.LEFT, border=2)
680 self.topsizer.Add(self.errorLogButton, pos=(1, 4), flag=wx.LEFT, border=2)
681 self.topsizer.Add(self.motorsOffButton, pos=(1, 5), flag=wx.LEFT|wx.RIGHT, border=2)
682 self.sizer.Add(self.movementBitmap, pos=(0, 0), span=(2, 3))
683 self.sizer.Add(self.temperatureGraph, pos=(2, 0), span=(4, 2), flag=wx.EXPAND)
684 self.sizer.Add(self.temperatureBitmap, pos=(2, 2))
685 self.sizer.Add(self.temperatureField, pos=(3, 2))
686 self.sizer.Add(self.temperatureBedBitmap, pos=(4, 2))
687 self.sizer.Add(self.temperatureBedField, pos=(5, 2))
688 self.sizer.Add(self._termLog, pos=(0, 3), span=(5, 3), flag=wx.EXPAND|wx.RIGHT, border=5)
689 self.sizer.Add(self._termInput, pos=(5, 3), span=(1, 3), flag=wx.EXPAND|wx.RIGHT, border=5)
690 self.sizer.Add(self.progress, pos=(6, 0), span=(1, 6), flag=wx.EXPAND|wx.BOTTOM)
692 self.Bind(wx.EVT_SIZE, self.OnSize)
693 self.Bind(wx.EVT_CLOSE, self.OnClose)
694 self.movementBitmap.Bind(wx.EVT_LEFT_DOWN, self.OnMovementClick)
695 self.temperatureGraph.Bind(wx.EVT_LEFT_UP, self.OnTemperatureClick)
696 self.connectButton.Bind(wx.EVT_BUTTON, self.OnConnect)
697 self.printButton.Bind(wx.EVT_BUTTON, self.OnPrint)
698 self.cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel)
699 self.errorLogButton.Bind(wx.EVT_BUTTON, self.OnErrorLog)
700 self.motorsOffButton.Bind(wx.EVT_BUTTON, self.OnMotorsOff)
705 self.progress.SetMinSize(self.progress.GetSize())
706 self._updateButtonStates()
708 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
710 if self._printerConnection.hasActiveConnection() and \
711 not self._printerConnection.isActiveConnectionOpen():
712 self._printerConnection.openActiveConnection()
715 # HACK ALERT: This is needed for some reason otherwise the window
716 # will be bigger than it should be until a power warning change
721 def OnClose(self, e):
722 if self._printerConnection.hasActiveConnection():
723 if self._printerConnection.isPrinting() or self._printerConnection.isPaused():
724 pass #TODO: Give warning that the close will kill the print.
725 self._printerConnection.closeActiveConnection()
726 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
727 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
728 preventComputerFromSleeping(self, False)
729 self._printerConnection.cancelPrint()
732 def OnPowerWarningChange(self, e):
733 type = self.powerManagement.get_providing_power_source_type()
734 if type == power.POWER_TYPE_AC and self.powerWarningText.IsShown():
735 self.powerWarningText.Hide()
736 self.toppanel.Layout()
740 elif type != power.POWER_TYPE_AC and not self.powerWarningText.IsShown():
741 self.powerWarningText.Show()
742 self.toppanel.Layout()
747 def OnConnect(self, e):
748 self._printerConnection.openActiveConnection()
750 def OnPrint(self, e):
751 if self._printerConnection.isPrinting() or self._printerConnection.isPaused():
752 self._printerConnection.pause(not self._printerConnection.isPaused())
754 self._printerConnection.startPrint()
756 def OnCancel(self, e):
757 self._printerConnection.cancelPrint()
759 def OnErrorLog(self, e):
760 LogWindow(self._printerConnection.getErrorLog())
762 def OnMotorsOff(self, e):
763 self._printerConnection.sendCommand("M18")
765 def GetMapRGB(self, x, y):
766 r = self._mapImage.GetRed(x, y)
767 g = self._mapImage.GetGreen(x, y)
768 b = self._mapImage.GetBlue(x, y)
771 def OnMovementClick(self, e):
772 (r, g, b) = self.GetMapRGB(e.GetX(), e.GetY())
773 if (r, g, b) in self._colorCommandMap:
774 command = self._colorCommandMap[(r, g, b)]
775 command[0](command[1])
777 def _addMovementCommand(self, r, g, b, command, step):
778 self._colorCommandMap[(r, g, b)] = (command, step)
780 def _moveXYZE(self, motor, step, feedrate):
781 if (not self._printerConnection.hasActiveConnection() or \
782 self._printerConnection.isActiveConnectionOpen()) and \
783 (not self._printerConnection.isPaused() and \
784 not self._printerConnection.isPrinting()):
785 self._printerConnection.sendCommand("G91")
786 self._printerConnection.sendCommand("G1 %s%.1f F%d" % (motor, step, feedrate))
787 self._printerConnection.sendCommand("G90")
789 def _moveX(self, step):
790 self._moveXYZE("X", step, 2000)
792 def _moveY(self, step):
793 self._moveXYZE("Y", step, 2000)
795 def _moveZ(self, step):
796 self._moveXYZE("Z", step, 200)
798 def _moveE(self, step):
799 self._moveXYZE("E", step, 120)
801 def _homeXYZ(self, direction):
802 if not self._printerConnection.isPaused() and not self._printerConnection.isPrinting():
803 if direction is None:
804 self._printerConnection.sendCommand("G28")
806 self._printerConnection.sendCommand("G28 %s0" % direction)
808 def _setHotendTemperature(self, value):
809 self._printerConnection.sendCommand("M104 S%d" % value)
811 def _setBedTemperature(self, value):
812 self._printerConnection.sendCommand("M140 S%d" % value)
814 def OnTemperatureClick(self, e):
815 wx.CallAfter(self.ToggleFullScreenTemperature)
817 def ToggleFullScreenTemperature(self):
818 sizer = self.GetSizer()
819 if self._fullscreenTemperature:
820 self._fullscreenTemperature.Show(False)
821 sizer.Detach(self._fullscreenTemperature)
822 self._fullscreenTemperature.Destroy()
823 self._fullscreenTemperature = None
824 self.panel.Show(True)
826 self._fullscreenTemperature = self.temperatureGraph.Clone(self)
827 self._fullscreenTemperature.Bind(wx.EVT_LEFT_UP, self.OnTemperatureClick)
828 sizer.Add(self._fullscreenTemperature, 1, flag=wx.EXPAND)
829 self.panel.Show(False)
833 def OnTermEnterLine(self, e):
834 if not self._printerConnection.isAbleToSendDirectCommand():
836 line = self._termInput.GetValue()
839 self._addTermLog('> %s\n' % (line))
840 self._printerConnection.sendCommand(line)
841 self._termHistory.append(line)
842 self._termHistoryIdx = len(self._termHistory)
843 self._termInput.SetValue('')
845 def OnTermKey(self, e):
846 if len(self._termHistory) > 0:
847 if e.GetKeyCode() == wx.WXK_UP:
848 self._termHistoryIdx -= 1
849 if self._termHistoryIdx < 0:
850 self._termHistoryIdx = len(self._termHistory) - 1
851 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
852 if e.GetKeyCode() == wx.WXK_DOWN:
853 self._termHistoryIdx -= 1
854 if self._termHistoryIdx >= len(self._termHistory):
855 self._termHistoryIdx = 0
856 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
859 def _addTermLog(self, line):
860 if self._termLog is not None:
861 if len(self._termLog.GetValue()) > 10000:
862 self._termLog.SetValue(self._termLog.GetValue()[-10000:])
863 self._termLog.SetInsertionPointEnd()
864 if type(line) != unicode:
865 line = unicode(line, 'utf-8', 'replace')
866 self._termLog.AppendText(line.encode('utf-8', 'replace'))
868 def _updateButtonStates(self):
869 self.connectButton.Show(self._printerConnection.hasActiveConnection())
870 self.connectButton.Enable(not self._printerConnection.isActiveConnectionOpen() and \
871 not self._printerConnection.isActiveConnectionOpening())
872 if not self._printerConnection.hasPause():
873 if not self._printerConnection.hasActiveConnection() or \
874 self._printerConnection.isActiveConnectionOpen():
875 self.printButton.Enable(not self._printerConnection.isPrinting() and \
876 not self._printerConnection.isPaused())
878 self.printButton.Enable(False)
880 if not self._printerConnection.hasActiveConnection() or \
881 self._printerConnection.isActiveConnectionOpen():
882 if self._printerConnection.isPrinting():
883 self.printButton.SetLabel(_("Pause"))
885 if self._printerConnection.isPaused():
886 self.printButton.SetLabel(_("Resume"))
888 self.printButton.SetLabel(_("Print"))
889 self.printButton.Enable(True)
891 self.printButton.Enable(False)
892 if not self._printerConnection.hasActiveConnection() or \
893 self._printerConnection.isActiveConnectionOpen():
894 self.cancelButton.Enable(self._printerConnection.isPrinting() or \
895 self._printerConnection.isPaused())
897 self.cancelButton.Enable(False)
898 self.errorLogButton.Show(self._printerConnection.isInErrorState())
899 self._termInput.Enable(self._printerConnection.isAbleToSendDirectCommand())
901 def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
902 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
904 for n in xrange(0, 4):
905 t = connection.getTemperature(0)
910 self.temperatureGraph.addPoint(temp, [0] * len(temp), connection.getBedTemperature(), 0)
911 if self._fullscreenTemperature is not None:
912 self._fullscreenTemperature.addPoint(temp, [0] * len(temp), connection.getBedTemperature(), 0)
914 def __doPrinterConnectionUpdate(self, connection, extraInfo):
916 if self._lastUpdateTime + 0.5 > t and extraInfo is None:
918 self._lastUpdateTime = t
920 if extraInfo is not None and len(extraInfo) > 0:
921 self._addTermLog('< %s\n' % (extraInfo))
923 self._updateButtonStates()
924 isPrinting = connection.isPrinting() or connection.isPaused()
926 self.progress.SetValue(connection.getPrintProgress() * 1000)
928 self.progress.SetValue(0)
929 info = connection.getStatusString()
931 if self._printerConnection.getTemperature(0) is not None:
932 info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
933 if self._printerConnection.getBedTemperature() > 0:
934 info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
935 self.SetTitle(info.replace('\n', ', '))
936 if isPrinting != self._isPrinting:
937 self._isPrinting = isPrinting
938 preventComputerFromSleeping(self, self._isPrinting)
940 class TemperatureField(wx.Panel):
941 def __init__(self, parent, callback):
942 super(TemperatureField, self).__init__(parent)
943 self.callback = callback
945 self.SetBackgroundColour(wx.WHITE)
947 self.text = IntCtrl(self, -1)
948 self.text.SetBounds(0, 300)
949 self.text.SetSize((60, 25))
951 self.unit = wx.StaticBitmap(self, -1, wx.BitmapFromImage(wx.Image(
952 resources.getPathForImage('print-window-temperature-unit.png'))), (0, 0))
954 self.button = wx.Button(self, -1, _("Set"))
955 self.button.SetSize((35, 25))
956 self.Bind(wx.EVT_BUTTON, lambda e: self.callback(self.text.GetValue()), self.button)
958 self.text.SetPosition((0, 0))
959 self.unit.SetPosition((60, 0))
960 self.button.SetPosition((90, 0))
963 class TemperatureGraph(wx.Panel):
964 def __init__(self, parent):
965 super(TemperatureGraph, self).__init__(parent)
967 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
968 self.Bind(wx.EVT_SIZE, self.OnSize)
969 self.Bind(wx.EVT_PAINT, self.OnDraw)
971 self._lastDraw = time.time() - 1.0
973 self._backBuffer = None
974 self.addPoint([0]*16, [0]*16, 0, 0)
976 def Clone(self, parent):
977 clone = TemperatureGraph(parent)
978 clone._points = list(self._points)
981 def OnEraseBackground(self, e):
985 if self._backBuffer is None or self.GetSize() != self._backBuffer.GetSize():
986 self._backBuffer = wx.EmptyBitmap(*self.GetSizeTuple())
987 self.UpdateDrawing(True)
990 dc = wx.BufferedPaintDC(self, self._backBuffer)
992 def UpdateDrawing(self, force=False):
994 if (not force and now - self._lastDraw < 1.0) or self._backBuffer is None:
998 dc.SelectObject(self._backBuffer)
1000 dc.SetFont(wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT))
1001 w, h = self.GetSizeTuple()
1002 bgLinePen = wx.Pen('#A0A0A0')
1003 tempPen = wx.Pen('#FF4040')
1004 tempSPPen = wx.Pen('#FFA0A0')
1005 tempPenBG = wx.Pen('#FFD0D0')
1006 bedTempPen = wx.Pen('#4040FF')
1007 bedTempSPPen = wx.Pen('#A0A0FF')
1008 bedTempPenBG = wx.Pen('#D0D0FF')
1010 #Draw the background up to the current temperatures.
1016 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
1017 x1 = int(w - (now - t))
1018 for x in xrange(x0, x1 + 1):
1019 for n in xrange(0, min(len(t0), len(temp))):
1020 t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
1021 dc.SetPen(tempPenBG)
1022 dc.DrawLine(x, h, x, h - (t * h / 350))
1023 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
1024 dc.SetPen(bedTempPenBG)
1025 dc.DrawLine(x, h, x, h - (bt * h / 350))
1033 for x in xrange(w, 0, -30):
1034 dc.SetPen(bgLinePen)
1035 dc.DrawLine(x, 0, x, h)
1037 for y in xrange(h - 1, 0, -h * 50 / 350):
1038 dc.SetPen(bgLinePen)
1039 dc.DrawLine(0, y, w, y)
1040 dc.DrawText(str(tmpNr), 0, y - dc.GetFont().GetPixelSize().GetHeight())
1042 dc.DrawLine(0, 0, w, 0)
1043 dc.DrawLine(0, 0, 0, h)
1045 #Draw the main lines
1051 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
1052 x1 = int(w - (now - t))
1053 for x in xrange(x0, x1 + 1):
1054 for n in xrange(0, min(len(t0), len(temp))):
1055 t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
1056 tSP = float(x - x0) / float(x1 - x0 + 1) * (tempSP[n] - tSP0[n]) + tSP0[n]
1057 dc.SetPen(tempSPPen)
1058 dc.DrawPoint(x, h - (tSP * h / 350))
1060 dc.DrawPoint(x, h - (t * h / 350))
1061 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
1062 btSP = float(x - x0) / float(x1 - x0 + 1) * (bedTempSP - btSP0) + btSP0
1063 dc.SetPen(bedTempSPPen)
1064 dc.DrawPoint(x, h - (btSP * h / 350))
1065 dc.SetPen(bedTempPen)
1066 dc.DrawPoint(x, h - (bt * h / 350))
1074 self.Refresh(eraseBackground=False)
1077 if len(self._points) > 0 and (time.time() - self._points[0][4]) > w + 20:
1080 def addPoint(self, temp, tempSP, bedTemp, bedTempSP):
1081 if len(self._points) > 0 and time.time() - self._points[-1][4] < 0.5:
1083 for n in xrange(0, len(temp)):
1086 for n in xrange(0, len(tempSP)):
1087 if tempSP[n] is None:
1091 if bedTempSP is None:
1093 self._points.append((temp[:], tempSP[:], bedTemp, bedTempSP, time.time()))
1094 wx.CallAfter(self.UpdateDrawing)
1096 class LogWindow(wx.Frame):
1097 def __init__(self, logText):
1098 super(LogWindow, self).__init__(None, title=_("Error log"))
1099 self.textBox = wx.TextCtrl(self, -1, logText, style=wx.TE_MULTILINE | wx.TE_DONTWRAP | wx.TE_READONLY)
1100 self.SetSize((500, 400))