1 __copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
10 #TODO: This does not belong here!
11 if sys.platform.startswith('win'):
12 def preventComputerFromSleeping(prevent):
14 Function used to prevent the computer from going into sleep mode.
15 :param prevent: True = Prevent the system from going to sleep from this point on.
16 :param prevent: False = No longer prevent the system from going to sleep.
18 ES_CONTINUOUS = 0x80000000
19 ES_SYSTEM_REQUIRED = 0x00000001
20 #SetThreadExecutionState returns 0 when failed, which is ignored. The function should be supported from windows XP and up.
22 ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED)
24 ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS)
27 def preventComputerFromSleeping(prevent):
28 #No preventComputerFromSleeping for MacOS and Linux yet.
31 class printWindowPlugin(wx.Frame):
32 def __init__(self, parent, printerConnection, filename):
33 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()))
34 self._printerConnection = printerConnection
35 self._basePath = os.path.dirname(filename)
36 self._backgroundImage = None
37 self._colorCommandMap = {}
40 self._termInput = None
41 self._termHistory = []
42 self._termHistoryIdx = 0
43 self._progressBar = None
44 self._tempGraph = None
46 self._lastUpdateTime = time.time()
49 'setImage': self.script_setImage,
50 'addColorCommand': self.script_addColorCommand,
51 'addTerminal': self.script_addTerminal,
52 'addTemperatureGraph': self.script_addTemperatureGraph,
53 'addProgressbar': self.script_addProgressbar,
54 'addButton': self.script_addButton,
55 'addSpinner': self.script_addSpinner,
57 'sendGCode': self.script_sendGCode,
58 'connect': self.script_connect,
59 'startPrint': self.script_startPrint,
60 'pausePrint': self.script_pausePrint,
61 'cancelPrint': self.script_cancelPrint,
62 'showErrorLog': self.script_showErrorLog,
64 execfile(filename, variables, variables)
66 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
67 self.Bind(wx.EVT_PAINT, self.OnDraw)
68 self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftClick)
69 self.Bind(wx.EVT_CLOSE, self.OnClose)
71 self._updateButtonStates()
73 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
75 if self._printerConnection.hasActiveConnection() and not self._printerConnection.isActiveConnectionOpen():
76 self._printerConnection.openActiveConnection()
77 preventComputerFromSleeping(True)
79 def script_setImage(self, guiImage, mapImage):
80 self._backgroundImage = wx.BitmapFromImage(wx.Image(os.path.join(self._basePath, guiImage)))
81 self._mapImage = wx.Image(os.path.join(self._basePath, mapImage))
82 self.SetClientSize(self._mapImage.GetSize())
84 def script_addColorCommand(self, r, g, b, command, data = None):
85 self._colorCommandMap[(r, g, b)] = (command, data)
87 def script_addTerminal(self, r, g, b):
88 x, y, w, h = self._getColoredRect(r, g, b)
89 if x < 0 or self._termLog is not None:
91 f = wx.Font(8, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
92 self._termLog = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.TE_DONTWRAP)
93 self._termLog.SetFont(f)
94 self._termLog.SetEditable(0)
95 self._termInput = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER)
96 self._termInput.SetFont(f)
98 self._termLog.SetPosition((x, y))
99 self._termLog.SetSize((w, h - self._termInput.GetSize().GetHeight()))
100 self._termInput.SetPosition((x, y + h - self._termInput.GetSize().GetHeight()))
101 self._termInput.SetSize((w, self._termInput.GetSize().GetHeight()))
102 self.Bind(wx.EVT_TEXT_ENTER, self.OnTermEnterLine, self._termInput)
103 self._termInput.Bind(wx.EVT_CHAR, self.OnTermKey)
105 def script_addTemperatureGraph(self, r, g, b):
106 x, y, w, h = self._getColoredRect(r, g, b)
107 if x < 0 or self._tempGraph is not None:
109 self._tempGraph = TemperatureGraph(self)
111 self._tempGraph.SetPosition((x, y))
112 self._tempGraph.SetSize((w, h))
114 def script_addProgressbar(self, r, g, b):
115 x, y, w, h = self._getColoredRect(r, g, b)
118 self._progressBar = wx.Gauge(self, -1, range=1000)
120 self._progressBar.SetPosition((x, y))
121 self._progressBar.SetSize((w, h))
123 def script_addButton(self, r, g, b, text, command, data = None):
124 x, y, w, h = self._getColoredRect(r, g, b)
127 button = wx.Button(self, -1, _(text))
128 button.SetPosition((x, y))
129 button.SetSize((w, h))
130 button.command = command
132 self._buttonList.append(button)
133 self.Bind(wx.EVT_BUTTON, lambda e: command(data), button)
135 def script_addSpinner(self, r, g, b, command, data):
136 x, y, w, h = self._getColoredRect(r, g, b)
140 def run_command(spinner):
141 value = spinner.GetValue()
142 if spinner.last_value != value:
143 if spinner.last_value != '' and value != 0:
144 spinner.command(spinner.data % value)
145 spinner.last_value = value
147 spinner = wx.SpinCtrl(self, -1, style=wx.TE_PROCESS_ENTER)
148 spinner.SetRange(0, 300)
149 spinner.SetPosition((x, y))
150 spinner.SetSize((w, h))
151 spinner.command = command
153 spinner.last_value = ''
154 self._buttonList.append(spinner)
155 self.Bind(wx.EVT_SPINCTRL, lambda e: run_command(spinner), spinner)
157 def _getColoredRect(self, r, g, b):
158 for x in xrange(0, self._mapImage.GetWidth()):
159 for y in xrange(0, self._mapImage.GetHeight()):
160 if self._mapImage.GetRed(x, y) == r and self._mapImage.GetGreen(x, y) == g and self._mapImage.GetBlue(x, y) == b:
162 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:
165 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:
168 print "Failed to find color: ", r, g, b
171 def script_sendGCode(self, data = None):
172 for line in data.split(';'):
175 self._printerConnection.sendCommand(line)
177 def script_connect(self, data = None):
178 self._printerConnection.openActiveConnection()
180 def script_startPrint(self, data = None):
181 self._printerConnection.startPrint()
183 def script_cancelPrint(self, e):
184 self._printerConnection.cancelPrint()
186 def script_pausePrint(self, e):
187 self._printerConnection.pause(not self._printerConnection.isPaused())
189 def script_showErrorLog(self, e):
190 LogWindow(self._printerConnection.getErrorLog())
192 def OnEraseBackground(self, e):
196 dc = wx.BufferedPaintDC(self, self._backgroundImage)
198 def OnLeftClick(self, e):
199 r = self._mapImage.GetRed(e.GetX(), e.GetY())
200 g = self._mapImage.GetGreen(e.GetX(), e.GetY())
201 b = self._mapImage.GetBlue(e.GetX(), e.GetY())
202 if (r, g, b) in self._colorCommandMap:
203 command = self._colorCommandMap[(r, g, b)]
204 command[0](command[1])
206 def OnClose(self, e):
207 if self._printerConnection.hasActiveConnection():
208 if self._printerConnection.isPrinting():
209 pass #TODO: Give warning that the close will kill the print.
210 self._printerConnection.closeActiveConnection()
211 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
212 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
213 preventComputerFromSleeping(False)
216 def OnTermEnterLine(self, e):
217 if not self._printerConnection.isAbleToSendDirectCommand():
219 line = self._termInput.GetValue()
222 self._addTermLog('> %s\n' % (line))
223 self._printerConnection.sendCommand(line)
224 self._termHistory.append(line)
225 self._termHistoryIdx = len(self._termHistory)
226 self._termInput.SetValue('')
228 def OnTermKey(self, e):
229 if len(self._termHistory) > 0:
230 if e.GetKeyCode() == wx.WXK_UP:
231 self._termHistoryIdx -= 1
232 if self._termHistoryIdx < 0:
233 self._termHistoryIdx = len(self._termHistory) - 1
234 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
235 if e.GetKeyCode() == wx.WXK_DOWN:
236 self._termHistoryIdx -= 1
237 if self._termHistoryIdx >= len(self._termHistory):
238 self._termHistoryIdx = 0
239 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
242 def _addTermLog(self, line):
243 if self._termLog is not None:
244 if len(self._termLog.GetValue()) > 10000:
245 self._termLog.SetValue(self._termLog.GetValue()[-10000:])
246 self._termLog.SetInsertionPointEnd()
247 if type(line) != unicode:
248 line = unicode(line, 'utf-8', 'replace')
249 self._termLog.AppendText(line.encode('utf-8', 'replace'))
251 def _updateButtonStates(self):
252 for button in self._buttonList:
253 if button.command == self.script_connect:
254 button.Show(self._printerConnection.hasActiveConnection())
255 button.Enable(not self._printerConnection.isActiveConnectionOpen() and not self._printerConnection.isActiveConnectionOpening())
256 elif button.command == self.script_pausePrint:
257 button.Show(self._printerConnection.hasPause())
258 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
259 button.Enable(self._printerConnection.isPrinting() or self._printerConnection.isPaused())
262 elif button.command == self.script_startPrint:
263 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
264 button.Enable(not self._printerConnection.isPrinting())
267 elif button.command == self.script_cancelPrint:
268 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
269 button.Enable(self._printerConnection.isPrinting())
272 elif button.command == self.script_showErrorLog:
273 button.Show(self._printerConnection.isInErrorState())
274 if self._termInput is not None:
275 self._termInput.Enable(self._printerConnection.isAbleToSendDirectCommand())
277 def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
278 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
279 if self._tempGraph is not None:
281 for n in xrange(0, 4):
282 t = connection.getTemperature(0)
287 self._tempGraph.addPoint(temp, [0] * len(temp), connection.getBedTemperature(), 0)
289 def __doPrinterConnectionUpdate(self, connection, extraInfo):
291 if self._lastUpdateTime + 0.5 > t and extraInfo is None:
293 self._lastUpdateTime = t
295 if extraInfo is not None:
296 self._addTermLog('< %s\n' % (extraInfo))
298 self._updateButtonStates()
299 if self._progressBar is not None:
300 if connection.isPrinting():
301 self._progressBar.SetValue(connection.getPrintProgress() * 1000)
303 self._progressBar.SetValue(0)
304 info = connection.getStatusString()
306 if self._printerConnection.getTemperature(0) is not None:
307 info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
308 if self._printerConnection.getBedTemperature() > 0:
309 info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
310 if self._infoText is not None:
311 self._infoText.SetLabel(info)
313 self.SetTitle(info.replace('\n', ', '))
315 class printWindowBasic(wx.Frame):
317 Printing window for USB printing, network printing, and any other type of printer connection we can think off.
318 This is only a basic window with minimal information.
320 def __init__(self, parent, printerConnection):
321 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()))
322 self._printerConnection = printerConnection
323 self._lastUpdateTime = 0
325 self.SetSizer(wx.BoxSizer())
326 self.panel = wx.Panel(self)
327 self.GetSizer().Add(self.panel, 1, flag=wx.EXPAND)
328 self.sizer = wx.GridBagSizer(2, 2)
329 self.panel.SetSizer(self.sizer)
331 self.powerWarningText = wx.StaticText(parent=self.panel,
333 label=_("Your computer is running on battery power.\nConnect your computer to AC power or your print might not finish."),
334 style=wx.ALIGN_CENTER)
335 self.powerWarningText.SetBackgroundColour('red')
336 self.powerWarningText.SetForegroundColour('white')
337 self.powerManagement = power.PowerManagement()
338 self.powerWarningTimer = wx.Timer(self)
339 self.Bind(wx.EVT_TIMER, self.OnPowerWarningChange, self.powerWarningTimer)
340 self.OnPowerWarningChange(None)
341 self.powerWarningTimer.Start(10000)
343 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"))
345 self.connectButton = wx.Button(self.panel, -1, _("Connect"))
346 #self.loadButton = wx.Button(self.panel, -1, 'Load')
347 self.printButton = wx.Button(self.panel, -1, _("Print"))
348 self.pauseButton = wx.Button(self.panel, -1, _("Pause"))
349 self.cancelButton = wx.Button(self.panel, -1, _("Cancel print"))
350 self.errorLogButton = wx.Button(self.panel, -1, _("Error log"))
351 self.progress = wx.Gauge(self.panel, -1, range=1000)
353 self.sizer.Add(self.powerWarningText, pos=(0, 0), span=(1, 5), flag=wx.EXPAND|wx.BOTTOM, border=5)
354 self.sizer.Add(self.statsText, pos=(1, 0), span=(1, 5), flag=wx.LEFT, border=5)
355 self.sizer.Add(self.connectButton, pos=(2, 0))
356 #self.sizer.Add(self.loadButton, pos=(2,1))
357 self.sizer.Add(self.printButton, pos=(2, 1))
358 self.sizer.Add(self.pauseButton, pos=(2, 2))
359 self.sizer.Add(self.cancelButton, pos=(2, 3))
360 self.sizer.Add(self.errorLogButton, pos=(2, 4))
361 self.sizer.Add(self.progress, pos=(3, 0), span=(1, 5), flag=wx.EXPAND)
363 self.Bind(wx.EVT_CLOSE, self.OnClose)
364 self.connectButton.Bind(wx.EVT_BUTTON, self.OnConnect)
365 #self.loadButton.Bind(wx.EVT_BUTTON, self.OnLoad)
366 self.printButton.Bind(wx.EVT_BUTTON, self.OnPrint)
367 self.pauseButton.Bind(wx.EVT_BUTTON, self.OnPause)
368 self.cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel)
369 self.errorLogButton.Bind(wx.EVT_BUTTON, self.OnErrorLog)
375 self.progress.SetMinSize(self.progress.GetSize())
376 self.statsText.SetLabel('\n\n\n\n\n\n')
377 self._updateButtonStates()
379 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
381 if self._printerConnection.hasActiveConnection() and not self._printerConnection.isActiveConnectionOpen():
382 self._printerConnection.openActiveConnection()
383 preventComputerFromSleeping(True)
385 def OnPowerWarningChange(self, e):
386 type = self.powerManagement.get_providing_power_source_type()
387 if type == power.POWER_TYPE_AC and self.powerWarningText.IsShown():
388 self.powerWarningText.Hide()
393 elif type != power.POWER_TYPE_AC and not self.powerWarningText.IsShown():
394 self.powerWarningText.Show()
400 def OnClose(self, e):
401 if self._printerConnection.hasActiveConnection():
402 if self._printerConnection.isPrinting():
403 pass #TODO: Give warning that the close will kill the print.
404 self._printerConnection.closeActiveConnection()
405 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
406 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
407 preventComputerFromSleeping(False)
410 def OnConnect(self, e):
411 self._printerConnection.openActiveConnection()
416 def OnPrint(self, e):
417 self._printerConnection.startPrint()
419 def OnCancel(self, e):
420 self._printerConnection.cancelPrint()
422 def OnPause(self, e):
423 self._printerConnection.pause(not self._printerConnection.isPaused())
425 def OnErrorLog(self, e):
426 LogWindow(self._printerConnection.getErrorLog())
428 def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
429 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
430 #temp = [connection.getTemperature(0)]
431 #self.temperatureGraph.addPoint(temp, [0], connection.getBedTemperature(), 0)
433 def __doPrinterConnectionUpdate(self, connection, extraInfo):
435 if self._lastUpdateTime + 0.5 > t and extraInfo is None:
437 self._lastUpdateTime = t
439 if extraInfo is not None:
440 self._addTermLog('< %s\n' % (extraInfo))
442 self._updateButtonStates()
443 if connection.isPrinting():
444 self.progress.SetValue(connection.getPrintProgress() * 1000)
446 self.progress.SetValue(0)
447 info = connection.getStatusString()
449 if self._printerConnection.getTemperature(0) is not None:
450 info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
451 if self._printerConnection.getBedTemperature() > 0:
452 info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
454 self.statsText.SetLabel(info)
456 def _updateButtonStates(self):
457 self.connectButton.Show(self._printerConnection.hasActiveConnection())
458 self.connectButton.Enable(not self._printerConnection.isActiveConnectionOpen() and not self._printerConnection.isActiveConnectionOpening())
459 self.pauseButton.Show(self._printerConnection.hasPause())
460 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
461 self.printButton.Enable(not self._printerConnection.isPrinting())
462 self.pauseButton.Enable(self._printerConnection.isPrinting())
463 self.cancelButton.Enable(self._printerConnection.isPrinting())
465 self.printButton.Enable(False)
466 self.pauseButton.Enable(False)
467 self.cancelButton.Enable(False)
468 self.errorLogButton.Show(self._printerConnection.isInErrorState())
470 class TemperatureGraph(wx.Panel):
471 def __init__(self, parent):
472 super(TemperatureGraph, self).__init__(parent)
474 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
475 self.Bind(wx.EVT_SIZE, self.OnSize)
476 self.Bind(wx.EVT_PAINT, self.OnDraw)
478 self._lastDraw = time.time() - 1.0
480 self._backBuffer = None
481 self.addPoint([0]*16, [0]*16, 0, 0)
483 def OnEraseBackground(self, e):
487 if self._backBuffer is None or self.GetSize() != self._backBuffer.GetSize():
488 self._backBuffer = wx.EmptyBitmap(*self.GetSizeTuple())
489 self.UpdateDrawing(True)
492 dc = wx.BufferedPaintDC(self, self._backBuffer)
494 def UpdateDrawing(self, force=False):
496 if (not force and now - self._lastDraw < 1.0) or self._backBuffer is None:
500 dc.SelectObject(self._backBuffer)
502 dc.SetFont(wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT))
503 w, h = self.GetSizeTuple()
504 bgLinePen = wx.Pen('#A0A0A0')
505 tempPen = wx.Pen('#FF4040')
506 tempSPPen = wx.Pen('#FFA0A0')
507 tempPenBG = wx.Pen('#FFD0D0')
508 bedTempPen = wx.Pen('#4040FF')
509 bedTempSPPen = wx.Pen('#A0A0FF')
510 bedTempPenBG = wx.Pen('#D0D0FF')
512 #Draw the background up to the current temperatures.
518 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
519 x1 = int(w - (now - t))
520 for x in xrange(x0, x1 + 1):
521 for n in xrange(0, min(len(t0), len(temp))):
522 t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
524 dc.DrawLine(x, h, x, h - (t * h / 350))
525 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
526 dc.SetPen(bedTempPenBG)
527 dc.DrawLine(x, h, x, h - (bt * h / 350))
535 for x in xrange(w, 0, -30):
537 dc.DrawLine(x, 0, x, h)
539 for y in xrange(h - 1, 0, -h * 50 / 350):
541 dc.DrawLine(0, y, w, y)
542 dc.DrawText(str(tmpNr), 0, y - dc.GetFont().GetPixelSize().GetHeight())
544 dc.DrawLine(0, 0, w, 0)
545 dc.DrawLine(0, 0, 0, h)
553 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
554 x1 = int(w - (now - t))
555 for x in xrange(x0, x1 + 1):
556 for n in xrange(0, min(len(t0), len(temp))):
557 t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
558 tSP = float(x - x0) / float(x1 - x0 + 1) * (tempSP[n] - tSP0[n]) + tSP0[n]
560 dc.DrawPoint(x, h - (tSP * h / 350))
562 dc.DrawPoint(x, h - (t * h / 350))
563 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
564 btSP = float(x - x0) / float(x1 - x0 + 1) * (bedTempSP - btSP0) + btSP0
565 dc.SetPen(bedTempSPPen)
566 dc.DrawPoint(x, h - (btSP * h / 350))
567 dc.SetPen(bedTempPen)
568 dc.DrawPoint(x, h - (bt * h / 350))
576 self.Refresh(eraseBackground=False)
579 if len(self._points) > 0 and (time.time() - self._points[0][4]) > w + 20:
582 def addPoint(self, temp, tempSP, bedTemp, bedTempSP):
583 if len(self._points) > 0 and time.time() - self._points[-1][4] < 0.5:
585 for n in xrange(0, len(temp)):
588 for n in xrange(0, len(tempSP)):
589 if tempSP[n] is None:
593 if bedTempSP is None:
595 self._points.append((temp[:], tempSP[:], bedTemp, bedTempSP, time.time()))
596 wx.CallAfter(self.UpdateDrawing)
599 class LogWindow(wx.Frame):
600 def __init__(self, logText):
601 super(LogWindow, self).__init__(None, title="Error log")
602 self.textBox = wx.TextCtrl(self, -1, logText, style=wx.TE_MULTILINE | wx.TE_DONTWRAP | wx.TE_READONLY)
603 self.SetSize((500, 400))