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_TOOL_WINDOW|wx.FRAME_FLOAT_ON_PARENT, 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,
56 'sendGCode': self.script_sendGCode,
57 'connect': self.script_connect,
58 'startPrint': self.script_startPrint,
59 'pausePrint': self.script_pausePrint,
60 'cancelPrint': self.script_cancelPrint,
61 'showErrorLog': self.script_showErrorLog,
63 execfile(filename, variables, variables)
65 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
66 self.Bind(wx.EVT_PAINT, self.OnDraw)
67 self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftClick)
68 self.Bind(wx.EVT_CLOSE, self.OnClose)
70 self._updateButtonStates()
72 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
74 if self._printerConnection.hasActiveConnection() and not self._printerConnection.isActiveConnectionOpen():
75 self._printerConnection.openActiveConnection()
76 preventComputerFromSleeping(True)
78 def script_setImage(self, guiImage, mapImage):
79 self._backgroundImage = wx.BitmapFromImage(wx.Image(os.path.join(self._basePath, guiImage)))
80 self._mapImage = wx.Image(os.path.join(self._basePath, mapImage))
81 self.SetClientSize(self._mapImage.GetSize())
83 def script_addColorCommand(self, r, g, b, command, data = None):
84 self._colorCommandMap[(r, g, b)] = (command, data)
86 def script_addTerminal(self, r, g, b):
87 x, y, w, h = self._getColoredRect(r, g, b)
88 if x < 0 or self._termLog is not None:
90 f = wx.Font(8, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
91 self._termLog = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.TE_DONTWRAP)
92 self._termLog.SetFont(f)
93 self._termLog.SetEditable(0)
94 self._termInput = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER)
95 self._termInput.SetFont(f)
97 self._termLog.SetPosition((x, y))
98 self._termLog.SetSize((w, h - self._termInput.GetSize().GetHeight()))
99 self._termInput.SetPosition((x, y + h - self._termInput.GetSize().GetHeight()))
100 self._termInput.SetSize((w, self._termInput.GetSize().GetHeight()))
101 self.Bind(wx.EVT_TEXT_ENTER, self.OnTermEnterLine, self._termInput)
102 self._termInput.Bind(wx.EVT_CHAR, self.OnTermKey)
104 def script_addTemperatureGraph(self, r, g, b):
105 x, y, w, h = self._getColoredRect(r, g, b)
106 if x < 0 or self._tempGraph is not None:
108 self._tempGraph = TemperatureGraph(self)
110 self._tempGraph.SetPosition((x, y))
111 self._tempGraph.SetSize((w, h))
113 def script_addProgressbar(self, r, g, b):
114 x, y, w, h = self._getColoredRect(r, g, b)
117 self._progressBar = wx.Gauge(self, -1, range=1000)
119 self._progressBar.SetPosition((x, y))
120 self._progressBar.SetSize((w, h))
122 def script_addButton(self, r, g, b, text, command, data = None):
123 x, y, w, h = self._getColoredRect(r, g, b)
126 button = wx.Button(self, -1, _(text))
127 button.SetPosition((x, y))
128 button.SetSize((w, h))
129 button.command = command
131 self._buttonList.append(button)
132 self.Bind(wx.EVT_BUTTON, lambda e: command(data), button)
134 def _getColoredRect(self, r, g, b):
135 for x in xrange(0, self._mapImage.GetWidth()):
136 for y in xrange(0, self._mapImage.GetHeight()):
137 if self._mapImage.GetRed(x, y) == r and self._mapImage.GetGreen(x, y) == g and self._mapImage.GetBlue(x, y) == b:
139 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:
142 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:
145 print "Failed to find color: ", r, g, b
148 def script_sendGCode(self, data = None):
149 for line in data.split(';'):
152 self._printerConnection.sendCommand(line)
154 def script_connect(self, data = None):
155 self._printerConnection.openActiveConnection()
157 def script_startPrint(self, data = None):
158 self._printerConnection.startPrint()
160 def script_cancelPrint(self, e):
161 self._printerConnection.cancelPrint()
163 def script_pausePrint(self, e):
164 self._printerConnection.pause(not self._printerConnection.isPaused())
166 def script_showErrorLog(self, e):
167 LogWindow(self._printerConnection.getErrorLog())
169 def OnEraseBackground(self, e):
173 dc = wx.BufferedPaintDC(self, self._backgroundImage)
175 def OnLeftClick(self, e):
176 r = self._mapImage.GetRed(e.GetX(), e.GetY())
177 g = self._mapImage.GetGreen(e.GetX(), e.GetY())
178 b = self._mapImage.GetBlue(e.GetX(), e.GetY())
179 if (r, g, b) in self._colorCommandMap:
180 command = self._colorCommandMap[(r, g, b)]
181 command[0](command[1])
183 def OnClose(self, e):
184 if self._printerConnection.hasActiveConnection():
185 if self._printerConnection.isPrinting():
186 pass #TODO: Give warning that the close will kill the print.
187 self._printerConnection.closeActiveConnection()
188 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
189 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
190 preventComputerFromSleeping(False)
193 def OnTermEnterLine(self, e):
194 if not self._printerConnection.isAbleToSendDirectCommand():
196 line = self._termInput.GetValue()
199 self._addTermLog('> %s\n' % (line))
200 self._printerConnection.sendCommand(line)
201 self._termHistory.append(line)
202 self._termHistoryIdx = len(self._termHistory)
203 self._termInput.SetValue('')
205 def OnTermKey(self, e):
206 if len(self._termHistory) > 0:
207 if e.GetKeyCode() == wx.WXK_UP:
208 self._termHistoryIdx -= 1
209 if self._termHistoryIdx < 0:
210 self._termHistoryIdx = len(self._termHistory) - 1
211 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
212 if e.GetKeyCode() == wx.WXK_DOWN:
213 self._termHistoryIdx -= 1
214 if self._termHistoryIdx >= len(self._termHistory):
215 self._termHistoryIdx = 0
216 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
219 def _addTermLog(self, line):
220 if self._termLog is not None:
221 if len(self._termLog.GetValue()) > 10000:
222 self._termLog.SetValue(self._termLog.GetValue()[-10000:])
223 self._termLog.SetInsertionPointEnd()
224 if type(line) != unicode:
225 line = unicode(line, 'utf-8', 'replace')
226 self._termLog.AppendText(line.encode('utf-8', 'replace'))
228 def _updateButtonStates(self):
229 for button in self._buttonList:
230 if button.command == self.script_connect:
231 button.Show(self._printerConnection.hasActiveConnection())
232 button.Enable(not self._printerConnection.isActiveConnectionOpen() and not self._printerConnection.isActiveConnectionOpening())
233 elif button.command == self.script_pausePrint:
234 button.Show(self._printerConnection.hasPause())
235 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
236 button.Enable(self._printerConnection.isPrinting() or self._printerConnection.isPaused())
239 elif button.command == self.script_startPrint:
240 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
241 button.Enable(not self._printerConnection.isPrinting())
244 elif button.command == self.script_cancelPrint:
245 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
246 button.Enable(self._printerConnection.isPrinting())
249 elif button.command == self.script_showErrorLog:
250 button.Show(self._printerConnection.isInErrorState())
251 if self._termInput is not None:
252 self._termInput.Enable(self._printerConnection.isAbleToSendDirectCommand())
254 def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
255 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
256 if self._tempGraph is not None:
258 for n in xrange(0, 4):
259 t = connection.getTemperature(0)
264 self._tempGraph.addPoint(temp, [0] * len(temp), connection.getBedTemperature(), 0)
266 def __doPrinterConnectionUpdate(self, connection, extraInfo):
268 if self._lastUpdateTime + 0.5 > t and extraInfo is None:
270 self._lastUpdateTime = t
272 if extraInfo is not None:
273 self._addTermLog('< %s\n' % (extraInfo))
275 self._updateButtonStates()
276 if self._progressBar is not None:
277 if connection.isPrinting():
278 self._progressBar.SetValue(connection.getPrintProgress() * 1000)
280 self._progressBar.SetValue(0)
281 info = connection.getStatusString()
283 if self._printerConnection.getTemperature(0) is not None:
284 info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
285 if self._printerConnection.getBedTemperature() > 0:
286 info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
287 if self._infoText is not None:
288 self._infoText.SetLabel(info)
290 self.SetTitle(info.replace('\n', ', '))
292 class printWindowBasic(wx.Frame):
294 Printing window for USB printing, network printing, and any other type of printer connection we can think off.
295 This is only a basic window with minimal information.
297 def __init__(self, parent, printerConnection):
298 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()))
299 self._printerConnection = printerConnection
300 self._lastUpdateTime = 0
302 self.SetSizer(wx.BoxSizer())
303 self.panel = wx.Panel(self)
304 self.GetSizer().Add(self.panel, 1, flag=wx.EXPAND)
305 self.sizer = wx.GridBagSizer(2, 2)
306 self.panel.SetSizer(self.sizer)
308 self.powerWarningText = wx.StaticText(parent=self.panel,
310 label=_("Your computer is running on battery power.\nConnect your computer to AC power or your print might not finish."),
311 style=wx.ALIGN_CENTER)
312 self.powerWarningText.SetBackgroundColour('red')
313 self.powerWarningText.SetForegroundColour('white')
314 self.sizer.Add(self.powerWarningText, pos=(0, 0), span=(1, 5), flag=wx.EXPAND|wx.BOTTOM, border=5)
315 self.powerManagement = power.PowerManagement()
316 self.powerWarningTimer = wx.Timer(self)
317 self.Bind(wx.EVT_TIMER, self.OnPowerWarningChange, self.powerWarningTimer)
318 self.OnPowerWarningChange(None)
319 self.powerWarningTimer.Start(10000)
321 self.statsText = wx.StaticText(self.panel, -1, _("InfoLine from printer connection\nInfoLine from dialog"))
322 self.sizer.Add(self.statsText, pos=(1, 0), span=(1, 5), flag=wx.LEFT, border=5)
324 self.connectButton = wx.Button(self.panel, -1, _("Connect"))
325 #self.loadButton = wx.Button(self.panel, -1, 'Load')
326 self.printButton = wx.Button(self.panel, -1, _("Print"))
327 self.pauseButton = wx.Button(self.panel, -1, _("Pause"))
328 self.cancelButton = wx.Button(self.panel, -1, _("Cancel print"))
329 self.errorLogButton = wx.Button(self.panel, -1, _("Error log"))
330 self.progress = wx.Gauge(self.panel, -1, range=1000)
332 self.sizer.Add(self.connectButton, pos=(2, 0))
333 #self.sizer.Add(self.loadButton, pos=(2,1))
334 self.sizer.Add(self.printButton, pos=(2, 1))
335 self.sizer.Add(self.pauseButton, pos=(2, 2))
336 self.sizer.Add(self.cancelButton, pos=(2, 3))
337 self.sizer.Add(self.errorLogButton, pos=(2, 4))
338 self.sizer.Add(self.progress, pos=(3, 0), span=(1, 5), flag=wx.EXPAND)
340 self.Bind(wx.EVT_CLOSE, self.OnClose)
341 self.connectButton.Bind(wx.EVT_BUTTON, self.OnConnect)
342 #self.loadButton.Bind(wx.EVT_BUTTON, self.OnLoad)
343 self.printButton.Bind(wx.EVT_BUTTON, self.OnPrint)
344 self.pauseButton.Bind(wx.EVT_BUTTON, self.OnPause)
345 self.cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel)
346 self.errorLogButton.Bind(wx.EVT_BUTTON, self.OnErrorLog)
352 self.progress.SetMinSize(self.progress.GetSize())
353 self.statsText.SetLabel('')
354 self._updateButtonStates()
356 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
358 if self._printerConnection.hasActiveConnection() and not self._printerConnection.isActiveConnectionOpen():
359 self._printerConnection.openActiveConnection()
360 preventComputerFromSleeping(True)
362 def OnPowerWarningChange(self, e):
363 type = self.powerManagement.get_providing_power_source_type()
364 if type == power.POWER_TYPE_AC and self.powerWarningText.IsShown():
365 self.powerWarningText.Hide()
370 elif type != power.POWER_TYPE_AC and not self.powerWarningText.IsShown():
371 self.powerWarningText.Show()
377 def OnClose(self, e):
378 if self._printerConnection.hasActiveConnection():
379 if self._printerConnection.isPrinting():
380 pass #TODO: Give warning that the close will kill the print.
381 self._printerConnection.closeActiveConnection()
382 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
383 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
384 preventComputerFromSleeping(False)
387 def OnConnect(self, e):
388 self._printerConnection.openActiveConnection()
393 def OnPrint(self, e):
394 self._printerConnection.startPrint()
396 def OnCancel(self, e):
397 self._printerConnection.cancelPrint()
399 def OnPause(self, e):
400 self._printerConnection.pause(not self._printerConnection.isPaused())
402 def OnErrorLog(self, e):
403 LogWindow(self._printerConnection.getErrorLog())
405 def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
406 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
407 #temp = [connection.getTemperature(0)]
408 #self.temperatureGraph.addPoint(temp, [0], connection.getBedTemperature(), 0)
410 def __doPrinterConnectionUpdate(self, connection, extraInfo):
412 if self._lastUpdateTime + 0.5 > t and extraInfo is None:
414 self._lastUpdateTime = t
416 if extraInfo is not None:
417 self._addTermLog('< %s\n' % (extraInfo))
419 self._updateButtonStates()
420 if connection.isPrinting():
421 self.progress.SetValue(connection.getPrintProgress() * 1000)
423 self.progress.SetValue(0)
424 info = connection.getStatusString()
426 if self._printerConnection.getTemperature(0) is not None:
427 info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
428 if self._printerConnection.getBedTemperature() > 0:
429 info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
430 self.statsText.SetLabel(info)
432 def _updateButtonStates(self):
433 self.connectButton.Show(self._printerConnection.hasActiveConnection())
434 self.connectButton.Enable(not self._printerConnection.isActiveConnectionOpen() and not self._printerConnection.isActiveConnectionOpening())
435 self.pauseButton.Show(self._printerConnection.hasPause())
436 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
437 self.printButton.Enable(not self._printerConnection.isPrinting())
438 self.pauseButton.Enable(self._printerConnection.isPrinting())
439 self.cancelButton.Enable(self._printerConnection.isPrinting())
441 self.printButton.Enable(False)
442 self.pauseButton.Enable(False)
443 self.cancelButton.Enable(False)
444 self.errorLogButton.Show(self._printerConnection.isInErrorState())
446 class TemperatureGraph(wx.Panel):
447 def __init__(self, parent):
448 super(TemperatureGraph, self).__init__(parent)
450 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
451 self.Bind(wx.EVT_SIZE, self.OnSize)
452 self.Bind(wx.EVT_PAINT, self.OnDraw)
454 self._lastDraw = time.time() - 1.0
456 self._backBuffer = None
457 self.addPoint([0]*16, [0]*16, 0, 0)
459 def OnEraseBackground(self, e):
463 if self._backBuffer is None or self.GetSize() != self._backBuffer.GetSize():
464 self._backBuffer = wx.EmptyBitmap(*self.GetSizeTuple())
465 self.UpdateDrawing(True)
468 dc = wx.BufferedPaintDC(self, self._backBuffer)
470 def UpdateDrawing(self, force=False):
472 if (not force and now - self._lastDraw < 1.0) or self._backBuffer is None:
476 dc.SelectObject(self._backBuffer)
478 dc.SetFont(wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT))
479 w, h = self.GetSizeTuple()
480 bgLinePen = wx.Pen('#A0A0A0')
481 tempPen = wx.Pen('#FF4040')
482 tempSPPen = wx.Pen('#FFA0A0')
483 tempPenBG = wx.Pen('#FFD0D0')
484 bedTempPen = wx.Pen('#4040FF')
485 bedTempSPPen = wx.Pen('#A0A0FF')
486 bedTempPenBG = wx.Pen('#D0D0FF')
488 #Draw the background up to the current temperatures.
494 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
495 x1 = int(w - (now - t))
496 for x in xrange(x0, x1 + 1):
497 for n in xrange(0, min(len(t0), len(temp))):
498 t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
500 dc.DrawLine(x, h, x, h - (t * h / 300))
501 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
502 dc.SetPen(bedTempPenBG)
503 dc.DrawLine(x, h, x, h - (bt * h / 300))
511 for x in xrange(w, 0, -30):
513 dc.DrawLine(x, 0, x, h)
515 for y in xrange(h - 1, 0, -h * 50 / 300):
517 dc.DrawLine(0, y, w, y)
518 dc.DrawText(str(tmpNr), 0, y - dc.GetFont().GetPixelSize().GetHeight())
520 dc.DrawLine(0, 0, w, 0)
521 dc.DrawLine(0, 0, 0, h)
529 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
530 x1 = int(w - (now - t))
531 for x in xrange(x0, x1 + 1):
532 for n in xrange(0, min(len(t0), len(temp))):
533 t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
534 tSP = float(x - x0) / float(x1 - x0 + 1) * (tempSP[n] - tSP0[n]) + tSP0[n]
536 dc.DrawPoint(x, h - (tSP * h / 300))
538 dc.DrawPoint(x, h - (t * h / 300))
539 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
540 btSP = float(x - x0) / float(x1 - x0 + 1) * (bedTempSP - btSP0) + btSP0
541 dc.SetPen(bedTempSPPen)
542 dc.DrawPoint(x, h - (btSP * h / 300))
543 dc.SetPen(bedTempPen)
544 dc.DrawPoint(x, h - (bt * h / 300))
552 self.Refresh(eraseBackground=False)
555 if len(self._points) > 0 and (time.time() - self._points[0][4]) > w + 20:
558 def addPoint(self, temp, tempSP, bedTemp, bedTempSP):
559 if len(self._points) > 0 and time.time() - self._points[-1][4] < 0.5:
561 for n in xrange(0, len(temp)):
564 for n in xrange(0, len(tempSP)):
565 if tempSP[n] is None:
569 if bedTempSP is None:
571 self._points.append((temp[:], tempSP[:], bedTemp, bedTempSP, time.time()))
572 wx.CallAfter(self.UpdateDrawing)
575 class LogWindow(wx.Frame):
576 def __init__(self, logText):
577 super(LogWindow, self).__init__(None, title="Error log")
578 self.textBox = wx.TextCtrl(self, -1, logText, style=wx.TE_MULTILINE | wx.TE_DONTWRAP | wx.TE_READONLY)
579 self.SetSize((500, 400))