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)
139 spinner = wx.SpinCtrl(self, -1, style=wx.TE_PROCESS_ENTER)
140 spinner.SetRange(0, 300)
141 spinner.SetPosition((x, y))
142 spinner.SetSize((w, h))
143 spinner.command = command
145 self._buttonList.append(spinner)
146 self.Bind(wx.EVT_SPINCTRL, lambda e: command(data % (spinner.GetValue())), spinner)
148 def _getColoredRect(self, r, g, b):
149 for x in xrange(0, self._mapImage.GetWidth()):
150 for y in xrange(0, self._mapImage.GetHeight()):
151 if self._mapImage.GetRed(x, y) == r and self._mapImage.GetGreen(x, y) == g and self._mapImage.GetBlue(x, y) == b:
153 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:
156 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:
159 print "Failed to find color: ", r, g, b
162 def script_sendGCode(self, data = None):
163 for line in data.split(';'):
166 self._printerConnection.sendCommand(line)
168 def script_connect(self, data = None):
169 self._printerConnection.openActiveConnection()
171 def script_startPrint(self, data = None):
172 self._printerConnection.startPrint()
174 def script_cancelPrint(self, e):
175 self._printerConnection.cancelPrint()
177 def script_pausePrint(self, e):
178 self._printerConnection.pause(not self._printerConnection.isPaused())
180 def script_showErrorLog(self, e):
181 LogWindow(self._printerConnection.getErrorLog())
183 def OnEraseBackground(self, e):
187 dc = wx.BufferedPaintDC(self, self._backgroundImage)
189 def OnLeftClick(self, e):
190 r = self._mapImage.GetRed(e.GetX(), e.GetY())
191 g = self._mapImage.GetGreen(e.GetX(), e.GetY())
192 b = self._mapImage.GetBlue(e.GetX(), e.GetY())
193 if (r, g, b) in self._colorCommandMap:
194 command = self._colorCommandMap[(r, g, b)]
195 command[0](command[1])
197 def OnClose(self, e):
198 if self._printerConnection.hasActiveConnection():
199 if self._printerConnection.isPrinting():
200 pass #TODO: Give warning that the close will kill the print.
201 self._printerConnection.closeActiveConnection()
202 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
203 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
204 preventComputerFromSleeping(False)
207 def OnTermEnterLine(self, e):
208 if not self._printerConnection.isAbleToSendDirectCommand():
210 line = self._termInput.GetValue()
213 self._addTermLog('> %s\n' % (line))
214 self._printerConnection.sendCommand(line)
215 self._termHistory.append(line)
216 self._termHistoryIdx = len(self._termHistory)
217 self._termInput.SetValue('')
219 def OnTermKey(self, e):
220 if len(self._termHistory) > 0:
221 if e.GetKeyCode() == wx.WXK_UP:
222 self._termHistoryIdx -= 1
223 if self._termHistoryIdx < 0:
224 self._termHistoryIdx = len(self._termHistory) - 1
225 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
226 if e.GetKeyCode() == wx.WXK_DOWN:
227 self._termHistoryIdx -= 1
228 if self._termHistoryIdx >= len(self._termHistory):
229 self._termHistoryIdx = 0
230 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
233 def _addTermLog(self, line):
234 if self._termLog is not None:
235 if len(self._termLog.GetValue()) > 10000:
236 self._termLog.SetValue(self._termLog.GetValue()[-10000:])
237 self._termLog.SetInsertionPointEnd()
238 if type(line) != unicode:
239 line = unicode(line, 'utf-8', 'replace')
240 self._termLog.AppendText(line.encode('utf-8', 'replace'))
242 def _updateButtonStates(self):
243 for button in self._buttonList:
244 if button.command == self.script_connect:
245 button.Show(self._printerConnection.hasActiveConnection())
246 button.Enable(not self._printerConnection.isActiveConnectionOpen() and not self._printerConnection.isActiveConnectionOpening())
247 elif button.command == self.script_pausePrint:
248 button.Show(self._printerConnection.hasPause())
249 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
250 button.Enable(self._printerConnection.isPrinting() or self._printerConnection.isPaused())
253 elif button.command == self.script_startPrint:
254 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
255 button.Enable(not self._printerConnection.isPrinting())
258 elif button.command == self.script_cancelPrint:
259 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
260 button.Enable(self._printerConnection.isPrinting())
263 elif button.command == self.script_showErrorLog:
264 button.Show(self._printerConnection.isInErrorState())
265 if self._termInput is not None:
266 self._termInput.Enable(self._printerConnection.isAbleToSendDirectCommand())
268 def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
269 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
270 if self._tempGraph is not None:
272 for n in xrange(0, 4):
273 t = connection.getTemperature(0)
278 self._tempGraph.addPoint(temp, [0] * len(temp), connection.getBedTemperature(), 0)
280 def __doPrinterConnectionUpdate(self, connection, extraInfo):
282 if self._lastUpdateTime + 0.5 > t and extraInfo is None:
284 self._lastUpdateTime = t
286 if extraInfo is not None:
287 self._addTermLog('< %s\n' % (extraInfo))
289 self._updateButtonStates()
290 if self._progressBar is not None:
291 if connection.isPrinting():
292 self._progressBar.SetValue(connection.getPrintProgress() * 1000)
294 self._progressBar.SetValue(0)
295 info = connection.getStatusString()
297 if self._printerConnection.getTemperature(0) is not None:
298 info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
299 if self._printerConnection.getBedTemperature() > 0:
300 info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
301 if self._infoText is not None:
302 self._infoText.SetLabel(info)
304 self.SetTitle(info.replace('\n', ', '))
306 class printWindowBasic(wx.Frame):
308 Printing window for USB printing, network printing, and any other type of printer connection we can think off.
309 This is only a basic window with minimal information.
311 def __init__(self, parent, printerConnection):
312 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()))
313 self._printerConnection = printerConnection
314 self._lastUpdateTime = 0
316 self.SetSizer(wx.BoxSizer())
317 self.panel = wx.Panel(self)
318 self.GetSizer().Add(self.panel, 1, flag=wx.EXPAND)
319 self.sizer = wx.GridBagSizer(2, 2)
320 self.panel.SetSizer(self.sizer)
322 self.powerWarningText = wx.StaticText(parent=self.panel,
324 label=_("Your computer is running on battery power.\nConnect your computer to AC power or your print might not finish."),
325 style=wx.ALIGN_CENTER)
326 self.powerWarningText.SetBackgroundColour('red')
327 self.powerWarningText.SetForegroundColour('white')
328 self.powerManagement = power.PowerManagement()
329 self.powerWarningTimer = wx.Timer(self)
330 self.Bind(wx.EVT_TIMER, self.OnPowerWarningChange, self.powerWarningTimer)
331 self.OnPowerWarningChange(None)
332 self.powerWarningTimer.Start(10000)
334 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"))
336 self.connectButton = wx.Button(self.panel, -1, _("Connect"))
337 #self.loadButton = wx.Button(self.panel, -1, 'Load')
338 self.printButton = wx.Button(self.panel, -1, _("Print"))
339 self.pauseButton = wx.Button(self.panel, -1, _("Pause"))
340 self.cancelButton = wx.Button(self.panel, -1, _("Cancel print"))
341 self.errorLogButton = wx.Button(self.panel, -1, _("Error log"))
342 self.progress = wx.Gauge(self.panel, -1, range=1000)
344 self.sizer.Add(self.powerWarningText, pos=(0, 0), span=(1, 5), flag=wx.EXPAND|wx.BOTTOM, border=5)
345 self.sizer.Add(self.statsText, pos=(1, 0), span=(1, 5), flag=wx.LEFT, border=5)
346 self.sizer.Add(self.connectButton, pos=(2, 0))
347 #self.sizer.Add(self.loadButton, pos=(2,1))
348 self.sizer.Add(self.printButton, pos=(2, 1))
349 self.sizer.Add(self.pauseButton, pos=(2, 2))
350 self.sizer.Add(self.cancelButton, pos=(2, 3))
351 self.sizer.Add(self.errorLogButton, pos=(2, 4))
352 self.sizer.Add(self.progress, pos=(3, 0), span=(1, 5), flag=wx.EXPAND)
354 self.Bind(wx.EVT_CLOSE, self.OnClose)
355 self.connectButton.Bind(wx.EVT_BUTTON, self.OnConnect)
356 #self.loadButton.Bind(wx.EVT_BUTTON, self.OnLoad)
357 self.printButton.Bind(wx.EVT_BUTTON, self.OnPrint)
358 self.pauseButton.Bind(wx.EVT_BUTTON, self.OnPause)
359 self.cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel)
360 self.errorLogButton.Bind(wx.EVT_BUTTON, self.OnErrorLog)
366 self.progress.SetMinSize(self.progress.GetSize())
367 self.statsText.SetLabel('\n\n\n\n\n\n')
368 self._updateButtonStates()
370 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
372 if self._printerConnection.hasActiveConnection() and not self._printerConnection.isActiveConnectionOpen():
373 self._printerConnection.openActiveConnection()
374 preventComputerFromSleeping(True)
376 def OnPowerWarningChange(self, e):
377 type = self.powerManagement.get_providing_power_source_type()
378 if type == power.POWER_TYPE_AC and self.powerWarningText.IsShown():
379 self.powerWarningText.Hide()
384 elif type != power.POWER_TYPE_AC and not self.powerWarningText.IsShown():
385 self.powerWarningText.Show()
391 def OnClose(self, e):
392 if self._printerConnection.hasActiveConnection():
393 if self._printerConnection.isPrinting():
394 pass #TODO: Give warning that the close will kill the print.
395 self._printerConnection.closeActiveConnection()
396 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
397 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
398 preventComputerFromSleeping(False)
401 def OnConnect(self, e):
402 self._printerConnection.openActiveConnection()
407 def OnPrint(self, e):
408 self._printerConnection.startPrint()
410 def OnCancel(self, e):
411 self._printerConnection.cancelPrint()
413 def OnPause(self, e):
414 self._printerConnection.pause(not self._printerConnection.isPaused())
416 def OnErrorLog(self, e):
417 LogWindow(self._printerConnection.getErrorLog())
419 def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
420 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
421 #temp = [connection.getTemperature(0)]
422 #self.temperatureGraph.addPoint(temp, [0], connection.getBedTemperature(), 0)
424 def __doPrinterConnectionUpdate(self, connection, extraInfo):
426 if self._lastUpdateTime + 0.5 > t and extraInfo is None:
428 self._lastUpdateTime = t
430 if extraInfo is not None:
431 self._addTermLog('< %s\n' % (extraInfo))
433 self._updateButtonStates()
434 if connection.isPrinting():
435 self.progress.SetValue(connection.getPrintProgress() * 1000)
437 self.progress.SetValue(0)
438 info = connection.getStatusString()
440 if self._printerConnection.getTemperature(0) is not None:
441 info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
442 if self._printerConnection.getBedTemperature() > 0:
443 info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
445 self.statsText.SetLabel(info)
447 def _updateButtonStates(self):
448 self.connectButton.Show(self._printerConnection.hasActiveConnection())
449 self.connectButton.Enable(not self._printerConnection.isActiveConnectionOpen() and not self._printerConnection.isActiveConnectionOpening())
450 self.pauseButton.Show(self._printerConnection.hasPause())
451 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
452 self.printButton.Enable(not self._printerConnection.isPrinting())
453 self.pauseButton.Enable(self._printerConnection.isPrinting())
454 self.cancelButton.Enable(self._printerConnection.isPrinting())
456 self.printButton.Enable(False)
457 self.pauseButton.Enable(False)
458 self.cancelButton.Enable(False)
459 self.errorLogButton.Show(self._printerConnection.isInErrorState())
461 class TemperatureGraph(wx.Panel):
462 def __init__(self, parent):
463 super(TemperatureGraph, self).__init__(parent)
465 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
466 self.Bind(wx.EVT_SIZE, self.OnSize)
467 self.Bind(wx.EVT_PAINT, self.OnDraw)
469 self._lastDraw = time.time() - 1.0
471 self._backBuffer = None
472 self.addPoint([0]*16, [0]*16, 0, 0)
474 def OnEraseBackground(self, e):
478 if self._backBuffer is None or self.GetSize() != self._backBuffer.GetSize():
479 self._backBuffer = wx.EmptyBitmap(*self.GetSizeTuple())
480 self.UpdateDrawing(True)
483 dc = wx.BufferedPaintDC(self, self._backBuffer)
485 def UpdateDrawing(self, force=False):
487 if (not force and now - self._lastDraw < 1.0) or self._backBuffer is None:
491 dc.SelectObject(self._backBuffer)
493 dc.SetFont(wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT))
494 w, h = self.GetSizeTuple()
495 bgLinePen = wx.Pen('#A0A0A0')
496 tempPen = wx.Pen('#FF4040')
497 tempSPPen = wx.Pen('#FFA0A0')
498 tempPenBG = wx.Pen('#FFD0D0')
499 bedTempPen = wx.Pen('#4040FF')
500 bedTempSPPen = wx.Pen('#A0A0FF')
501 bedTempPenBG = wx.Pen('#D0D0FF')
503 #Draw the background up to the current temperatures.
509 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
510 x1 = int(w - (now - t))
511 for x in xrange(x0, x1 + 1):
512 for n in xrange(0, min(len(t0), len(temp))):
513 t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
515 dc.DrawLine(x, h, x, h - (t * h / 300))
516 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
517 dc.SetPen(bedTempPenBG)
518 dc.DrawLine(x, h, x, h - (bt * h / 300))
526 for x in xrange(w, 0, -30):
528 dc.DrawLine(x, 0, x, h)
530 for y in xrange(h - 1, 0, -h * 50 / 300):
532 dc.DrawLine(0, y, w, y)
533 dc.DrawText(str(tmpNr), 0, y - dc.GetFont().GetPixelSize().GetHeight())
535 dc.DrawLine(0, 0, w, 0)
536 dc.DrawLine(0, 0, 0, h)
544 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
545 x1 = int(w - (now - t))
546 for x in xrange(x0, x1 + 1):
547 for n in xrange(0, min(len(t0), len(temp))):
548 t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
549 tSP = float(x - x0) / float(x1 - x0 + 1) * (tempSP[n] - tSP0[n]) + tSP0[n]
551 dc.DrawPoint(x, h - (tSP * h / 300))
553 dc.DrawPoint(x, h - (t * h / 300))
554 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
555 btSP = float(x - x0) / float(x1 - x0 + 1) * (bedTempSP - btSP0) + btSP0
556 dc.SetPen(bedTempSPPen)
557 dc.DrawPoint(x, h - (btSP * h / 300))
558 dc.SetPen(bedTempPen)
559 dc.DrawPoint(x, h - (bt * h / 300))
567 self.Refresh(eraseBackground=False)
570 if len(self._points) > 0 and (time.time() - self._points[0][4]) > w + 20:
573 def addPoint(self, temp, tempSP, bedTemp, bedTempSP):
574 if len(self._points) > 0 and time.time() - self._points[-1][4] < 0.5:
576 for n in xrange(0, len(temp)):
579 for n in xrange(0, len(tempSP)):
580 if tempSP[n] is None:
584 if bedTempSP is None:
586 self._points.append((temp[:], tempSP[:], bedTemp, bedTempSP, time.time()))
587 wx.CallAfter(self.UpdateDrawing)
590 class LogWindow(wx.Frame):
591 def __init__(self, logText):
592 super(LogWindow, self).__init__(None, title="Error log")
593 self.textBox = wx.TextCtrl(self, -1, logText, style=wx.TE_MULTILINE | wx.TE_DONTWRAP | wx.TE_READONLY)
594 self.SetSize((500, 400))