def __init__(self, parent=None, title="PocketPyGui", action=None, menu=None, tab_traversal=True, visible=True, enabled=True, has_sip=True, has_toolbar=False): '''\ Arguments : - parent: the parent window of this CeFrame. - title: the title as appearing in the title bar. - action : a tuple ('Label', callback) . - menu : the title of the right menu as a string if not None, the menu can be filled via the cb_menu attribute after CeFrame initialization. ''' Frame.__init__(self, parent, title, tab_traversal=tab_traversal, visible=visible, enabled=enabled) self.bind(_activate=self._on_activate, _settingchanged=self._on_setting_changed) if has_toolbar: self.toolbar = ToolBar(self) else: self.toolbar = None self.__create_menubar(action, menu, has_sip)
def __init__(self, parent=None): super(AfelApp, self).__init__(parent) self.setGeometry(10, 10, 1000, 1200) # self.setStyleSheet(""" # # font-size: 200; # # """) # Flags self.modes = { 'outer_window': True, 'live_mode': False } self.result_box_group = None self.result_box = None self.module_btns = [] mainWindow = QWidget(self) self.setCentralWidget(mainWindow) mainlay = QHBoxLayout() mainWindow.setLayout(mainlay) # load area btns_group = QGroupBox() btns_lay = QVBoxLayout() btns_group.setLayout(btns_lay) btns_lay.addStretch(1) self.btns_lay = btns_lay self.load_modules_btns() startbtn = QPushButton('start process') startbtn.clicked.connect(self.start_process) btns_lay.addWidget(startbtn) # sandbox area self.sandbox = SandBox() self.sandboxlay = QVBoxLayout() # self.sandboxlay.addStretch(209) self.sandbox.setLayout(self.sandboxlay) mainlay.addWidget(btns_group,1) mainlay.addWidget(self.sandbox,10) # toolbar # toolbar.setIconSize(QSize(16, 16)) self.toolbar = ToolBar(self) self.addToolBar(self.toolbar)
def initGui(self, screen_width, screen_height): bar_height = 30 self._statusbar = StatusBar(text=u"", panel_size=bar_height) self._toolbar = ToolBar(title=u"Toolbar", button_style=0) self._menubar = MenuBar(min_size=(screen_width, bar_height), position=(0, 0)) # Set up root widget self._rootwidget = pychan.widgets.VBox(padding=0, vexpand=1, hexpand=1) self._rootwidget.min_size = \ self._rootwidget.max_size = (screen_width, screen_height) self._rootwidget.opaque = False self._dockareas[DOCKAREA['left']] = DockArea("left") self._dockareas[DOCKAREA['right']] = DockArea("right") self._dockareas[DOCKAREA['top']] = DockArea("top") self._dockareas[DOCKAREA['bottom']] = DockArea("bottom") self._toolbarareas[DOCKAREA['left']] = pychan.widgets.VBox(margins=(0,0,0,0)) self._toolbarareas[DOCKAREA['right']] = pychan.widgets.VBox(margins=(0,0,0,0)) self._toolbarareas[DOCKAREA['top']] = pychan.widgets.HBox(margins=(0,0,0,0)) self._toolbarareas[DOCKAREA['bottom']] = pychan.widgets.HBox(margins=(0,0,0,0)) # This is where the map will be displayed self._centralwidget = pychan.widgets.VBox(vexpand=1, hexpand=1) self._centralwidget.opaque = False middle = pychan.widgets.HBox(padding=0, vexpand=1, hexpand=1) middle.opaque = False # Pychan bug? Adding a spacer instead of a container creates # a gap after the right dockarea middle.addChild(self._toolbarareas['left']) middle.addChild(self._dockareas['left']) middle.addChild(self._centralwidget) #middle.addSpacer(pychan.widgets.Spacer()) middle.addChild(self._dockareas['right']) middle.addChild(self._toolbarareas['right']) self._rootwidget.addChild(self._menubar) #self._rootwidget.addChild(self._toolbar) self._rootwidget.addChild(self._toolbarareas['top']) self._rootwidget.addChild(self._dockareas['top']) self._rootwidget.addChild(middle) self._rootwidget.addChild(self._dockareas['bottom']) self._rootwidget.addChild(self._toolbarareas['bottom']) self._rootwidget.addChild(self._statusbar) self._toolbar.setDocked(True) self.dockWidgetTo(self._toolbar, "top") self._rootwidget.show()
def __init__(self): tk.Tk.__init__(self) self.filename = None self.origin_image = None self.processed_image = None self.title("Segmentation and Edge Detection") self.toolbar = ToolBar(master=self) separator = ttk.Separator(master=self) self.image_viewer = Viewer(master=self) self.toolbar.pack(pady=10) separator.pack(fill=tk.X, padx=20, pady=5) self.image_viewer.pack(fill=tk.BOTH, padx=20, pady=10, expand=1)
def __init__(self, parent=None, title="PocketPyGui", action=None, menu=None, right_action=None, tab_traversal=True, visible=True, enabled=True, has_sip=True, has_toolbar=False): '''\ Arguments : - parent: the parent window of this CeFrame. - title: the title as appearing in the title bar. - action : a tuple ('Label', callback) . - menu : the title of the right menu as a string if not None, the menu can be filled via the cb_menu attribute after CeFrame initialization. ''' Frame.__init__(self, parent, title, tab_traversal=tab_traversal, visible=visible, enabled=enabled) self.bind(_activate=self._on_activate, _settingchanged=self._on_setting_changed, size=self._on_size) if has_toolbar : self.toolbar = ToolBar(self) else: self.toolbar = None self.__create_menubar(action, menu, right_action, has_sip)
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.mdiArea = QMdiArea(self) self.setCentralWidget(self.mdiArea) self.mainMenu = QMenuBar(self) self.setMenuBar(self.mainMenu) m = self.mainMenu.addMenu("Window") a = m.addAction("Cascade windows") a.triggered.connect(self.mdiArea.cascadeSubWindows) self.treePanel = QDockWidget("Дерево задач", self) w = QWidget(self.treePanel) lay = QVBoxLayout(w) lay.setSpacing(1) lay.setContentsMargins(1, 1, 1, 1) w.setLayout(lay) self.tree = TreeWidget(self.treePanel) lay.addWidget(self.tree) edit = QTextEdit(w) lay.addWidget(edit) self.treePanel.setWidget(w) self.tree.activated.connect(self.handle_dblclick) self.addDockWidget(Qt.LeftDockWidgetArea, self.treePanel) self.tools = ToolBar("tools.ini", self) self.addToolBar(self.tools)
def _build_widgets(self): """Builds own widgets.""" self.lastActiveLayer = None self._disconnect_connect_from_to_iface() self.iface.currentLayerChanged.connect( self._disconnect_connect_from_to_iface) QgsMapLayerRegistry.instance().legendLayersAdded.connect( self._check_added_perimeter_layer) self.toolBar = ToolBar( self, self.dWName, self.iface, self.pluginDir) self.gridLayout.addWidget(self.toolBar, 0, 0, 1, 1) self.statusBar = StatusBar( self, self.dWName, self.iface, self.pluginDir) self.gridLayout.addWidget(self.statusBar, 2, 0, 1, 1) self.frame = QFrame(self) self.frame.setObjectName(u'frame') self.frame.setFrameShape(QFrame.StyledPanel) self.frame.setFrameShadow(QFrame.Raised) self.gridLayout.addWidget(self.frame, 1, 0, 1, 1) self.stackedWidget = StackedWidget( self, self.dWName, self.iface, self.pluginDir) self.gridLayout.addWidget(self.stackedWidget, 1, 0, 1, 1)
def initGui(self, screen_width, screen_height): bar_height = 30 self._dockareas[DOCKAREA['left']] = DockArea("left") self._dockareas[DOCKAREA['right']] = DockArea("right") self._dockareas[DOCKAREA['top']] = DockArea("top") self._dockareas[DOCKAREA['bottom']] = DockArea("bottom") self._toolbarareas[DOCKAREA['left']] = pychan.widgets.VBox(margins=(0,0,0,0)) self._toolbarareas[DOCKAREA['right']] = pychan.widgets.VBox(margins=(0,0,0,0)) self._toolbarareas[DOCKAREA['top']] = pychan.widgets.HBox(margins=(0,0,0,0)) self._toolbarareas[DOCKAREA['bottom']] = pychan.widgets.HBox(margins=(0,0,0,0)) self._statusbar = StatusBar(text=u"", panel_size=bar_height) self._toolbar = ToolBar(title=u"Toolbar", button_style=0) self._menubar = MenuBar(min_size=(screen_width, bar_height), position=(0, 0)) # Set up root widget self._rootwidget = pychan.widgets.VBox(padding=0, vexpand=1, hexpand=1) self._rootwidget.min_size = \ self._rootwidget.max_size = (screen_width, screen_height) self._rootwidget.opaque = False # This is where the map will be displayed self._centralwidget = pychan.widgets.VBox(vexpand=1, hexpand=1) self._centralwidget.opaque = False middle = pychan.widgets.HBox(padding=0, vexpand=1, hexpand=1) middle.opaque = False # Pychan bug? Adding a spacer instead of a container creates # a gap after the right dockarea middle.addChild(self._toolbarareas['left']) middle.addChild(self._dockareas['left']) middle.addChild(self._centralwidget) #middle.addSpacer(pychan.widgets.Spacer()) middle.addChild(self._dockareas['right']) middle.addChild(self._toolbarareas['right']) self._rootwidget.addChild(self._menubar) #self._rootwidget.addChild(self._toolbar) self._rootwidget.addChild(self._toolbarareas['top']) self._rootwidget.addChild(self._dockareas['top']) self._rootwidget.addChild(middle) self._rootwidget.addChild(self._dockareas['bottom']) self._rootwidget.addChild(self._toolbarareas['bottom']) self._rootwidget.addChild(self._statusbar) self._toolbar.setDocked(True) self.dockWidgetTo(self._toolbar, "top") self._rootwidget.show()
def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.setWindowTitle("Ini Editor") self.initMenu() self.docks = [] self.statusBar() self.toolbar = ToolBar() self.addToolBar(self.toolbar) self.show()
def __init__(self, master=None, periodeManager=None, **kwargs): """ Constructeur de CalendarZone. @param master: master du tkinter.Frame() que cet objet est. @param periodeManager: le PeriodeManager pour la barre d'outil des périodes, connue dans cet objet. @param **kwargs: Les options d'affichages pour le tkinter.Frame() que cet objet est. """ Frame.__init__(self, master, **kwargs) # Note : self.master est référence vers l'Application. self.__isBarrePeriode = False # Barre du haut self.outilBar = ToolBar(self) # frame avec tous les boutons outils self.outilBar.pack(side=TOP, fill=X, expand=NO) # Barre du haut pour les périodes self.outilBarPeriode = PeriodToolBar( self, periodeManager) # frame avec tous les boutons outils # Zone calendrier self.zoneDynamicCalendarFrame = ZoneAffichage( self ) # frame avec la zone d'affichage des paramètre et la zone avec les données self.zoneDynamicCalendarFrame.pack(side=BOTTOM, fill=BOTH, expand=YES)
def __init__(self, tasksFile, parent=None): super(MainWindow, self).__init__(parent) self.mdiArea = QMdiArea(self) self.setCentralWidget(self.mdiArea) self.mainMenu = QMenuBar(self) self.setMenuBar(self.mainMenu) m = self.mainMenu.addMenu("Window") a = m.addAction("Cascade windows") a.triggered.connect(self.mdiArea.cascadeSubWindows) self.treePanel = QDockWidget("Дерево задач", self) w = QWidget(self.treePanel) lay = QVBoxLayout(w) lay.setSpacing(1) lay.setContentsMargins(1, 1, 1, 1) w.setLayout(lay) self.tree = TreeWidget(self.treePanel) lay.addWidget(self.tree) self.treePanel.setWidget(w) self.tree.activated.connect(self.handle_dblclick) self.addDockWidget(Qt.LeftDockWidgetArea, self.treePanel) self.winsPanel = QDockWidget("Окна", self) self.winlist = WinList(self.winsPanel) self.winsPanel.setWidget(self.winlist) self.addDockWidget(Qt.LeftDockWidgetArea, self.winsPanel) global wins wins = self.winsPanel self.tools = ToolBar("data/tools.ini", self) self.addToolBar(self.tools) model = TreeModel(tasksFile) self.tree.setModel(model) self.tree.expandAll() self.tree.setColumnHidden(1, True) self.dataPath = os.path.split(tasksFile)[0]
def __setup_layout(self): """One time setup of the scene.""" if not self.__need_setup: return stat_size = self.config['pyos']['status_size'].split(',') tool_size = self.config['pyos']['toolbar_size'].split(',') layout = TableLayout(self.config.getfloat('pyos', 'card_ratio'), self.config.getfloat('pyos', 'padding'), tuple([float(i) for i in stat_size]), tuple([float(i) for i in tool_size])) layout.root.reparent_to(self.root) hud = HUD(layout.status, tuple([float(i) for i in stat_size]), self.config['font']['normal'], self.config['font']['bold']) toolbar = ToolBar(self.ui.bottom_center, tuple([float(i) for i in tool_size]), self.config['font']['bold'], (self.__new_deal, self.__reset_deal, self.__undo_move, self.__menu)) game_table = Table(layout.callback) layout.set_table(game_table) self.__systems = GameSystems(game_table, layout, hud, toolbar) self.__need_setup = False
def initUI(self): #init Text edit self.textEdit = TextEdit(self) self.textEdit.textChanged.connect(self.textChanged) self.bTextChanged = False self.bTextSaved = True self.bCursorPosChanged = False #init Tool bar self.toolBar = ToolBar(self) initToolBar(self) #init textSplitter self.textSplitter = QSplitter(Qt.Horizontal, self) self.textSplitter.addWidget(self.textEdit) #init textBrowser self.bShowPW = False self.textBrowser = None #init timer self.timer = None #init layout self.centerVBox = QVBoxLayout() self.centerVBox.addWidget(self.textSplitter) self.centerVBox.addWidget(self.toolBar) self.centerVBox.setSpacing(0) self.centerVBox.setContentsMargins(0, 0, 0, 0) self.setLayout(self.centerVBox) #init tile self.updateWindowTitle() #init position screen = QDesktopWidget().screenGeometry() self.setGeometry(screen.width() / 4, screen.height() / 6, screen.width() / 2, screen.height() * 2 / 3) self.show()
class App(Frame): def __init__(self, master=None): self.master = master Frame.__init__(self, master, relief=SUNKEN, bd=2) self.gcode = [] self.slicing = False self.printing = False self.connected = False self.monitorTemp = False self.paused = False self.sdpresent = False self.sdlisting = False self.sdchecking = False self.sdprinting = False self.sdpaused = False self.sduploading = False self.sdbytes = 0 self.sdmaxbytes = 0 self.insidelisting = False self.readingFirmware = False self.sdfiles = [] self.bedtemp = float(0) self.bedtarget = float(0) self.exttemp = float(0) self.exttarget = float(0) self.acceleration = 0 self.m114count = 0 self.speedcount = 0 self.location = [0, 0, 0, 0] self.pausePoint = [0, 0, 0, 0] self.percent = 0.0 self.ets = "??" self.gcodeInfo = None self.GCodeFile = None self.StlFile = None self.Profile = None self.printStartLine = 0 self.startTime = 0 self.endTime = 0 self.elapsedTime = 0 self.FanSpeed = 0 self.FeedMultiply = 100 self.ExtrudeMultiply = 100 self.timingReport = None self.filamentReport = None self.measurementsReport = None self.macroButtons = None self.rpt1re = re.compile(" *T:([0-9\.]+) *E:[0-9\.]+ *B:([0-9\.]+)") self.rpt2re = re.compile(" *T:([0-9\.]+) *E:[0-9\.]+ *W:.*") self.locrptre = re.compile("^X:([0-9\.\-]+)Y:([0-9\.\-]+)Z:([0-9\.\-]+)E:([0-9\.\-]+) *Count") self.speedrptre = re.compile("Fan speed:([0-9]+) Feed Multiply:([0-9]+) Extrude Multiply:([0-9]+)") self.sdre = re.compile("SD printing byte *([0-9]+) *\/ *([0-9]+)") self.printer = printcore() self.settings = Settings() self.settings.cmdFolder = cmd_folder self.logger = Logger(self) if self.settings.speedcommand is not None: allow_while_printing.append(self.settings.speedcommand) self.acceleration = self.settings.acceleration self.dataLoggers = {} for d in DLLIST: self.dataLoggers[d] = DataLogger(self, d) self.skeinforge = Skeinforge(self.settings) self.slic3r = Slic3r(self.settings) self.httpServer = RepRapServer(self, self.printer, self.settings, self.logger, self.settings.port) self.menubar = Menu(self) self.filemenu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="File", menu=self.filemenu) self.filemenu.add_command(label="Slice", command=self.openSTLFile) self.filemenu.add_command(label="Load GCode", command=self.openGCodeFile) self.slicemenuindex = self.filemenu.index("Slice") self.loadgcodemenuindex = self.filemenu.index("Load GCode") self.filemenu.add_separator() self.filemenu.add_command(label="Exit", command=self.quitApp) self.editmenu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="Edit", menu=self.editmenu) self.editmenu.add_command(label="Settings", command=self.editSettings) self.editmenu.add_command(label="Firmware Settings", command=self.FirmwareSettings) self.editmenu.add_separator() self.editmenu.add_command(label=GCODE_MENU_TEXT, command=self.doGEdit, state=DISABLED) self.slicermenu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="Slicer", menu=self.slicermenu) self.rbSlicer = StringVar() self.slicermenu.add_radiobutton( label="Skeinforge", command=self.selSlicer, value=SKEINFORGE, variable=self.rbSlicer ) self.slicermenu.add_command(label="Settings", command=self.skeinforgeSettings) self.slicermenu.add_command(label="Choose Profile", command=self.chooseSFProfile) self.SFprofileindex = self.slicermenu.index("Choose Profile") self.setSFProfileMenuText() self.slicermenu.add_command(label="Alterations", command=self.doEditAlterations) self.slicermenu.add_separator() self.slicermenu.add_radiobutton(label="Slic3r", command=self.selSlicer, value=SLIC3R, variable=self.rbSlicer) self.slicermenu.add_command(label="Settings", command=self.slic3rSettings) self.slicermenu.add_command(label="Choose Profile", command=self.chooseS3Profile) self.S3profileindex = self.slicermenu.index("Choose Profile") self.setS3ProfileMenuText() self.rbSlicer.set(self.settings.slicer) self.macromenu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="Macros", menu=self.macromenu) self.macromenu.add_command(label="New", command=self.doNewMacro) self.macromenu.add_command(label="Edit", command=self.doEditMacro) self.macromenu.add_command(label="Delete", command=self.doDelMacro) self.macromenu.add_separator() self.cbShowMacroButtons = BooleanVar() self.cbShowMacroButtons.set(self.settings.showmacrobuttons) self.macromenu.add_checkbutton( label="Show Macro Buttons", command=self.doShowButtons, onvalue=True, offvalue=False, variable=self.cbShowMacroButtons, ) self.macromenu.add_separator() self.runmacromenu = Menu(self.macromenu, tearoff=0) self.loadMacros() self.macromenu.add_cascade(label="Run", menu=self.runmacromenu) self.reportmenu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="View", menu=self.reportmenu) self.cbShowPrevious = BooleanVar() self.cbShowPrevious.set(self.settings.showprevious) self.reportmenu.add_checkbutton( label="Show Previous Layer", command=self.toggleShowPrevious, onvalue=True, offvalue=False, variable=self.cbShowPrevious, ) self.cbShowMoves = BooleanVar() self.cbShowMoves.set(self.settings.showmoves) self.reportmenu.add_checkbutton( label="Show Non-extrusion Moves", command=self.toggleShowMoves, onvalue=True, offvalue=False, variable=self.cbShowMoves, ) self.reportmenu.add_separator() self.reportmenu.add_command(label="Show Hours of Usage", command=self.doDataLogReport) self.reportmenu.add_command(label="Reset Hours of Usage", command=self.doDataLogReset) self.reportmenu.add_separator() self.reportmenu.add_command(label="Layer by Layer Timing", command=self.doTimingReport) self.reportmenu.add_command(label="Layer by Layer Filament Usage", command=self.doFilamentReport) self.reportmenu.add_command(label="GCode Measurements", command=self.doMeasurementsReport) self.toolsmenu = Menu(self.menubar, tearoff=0) n = 0 if self.settings.platercmd is not None: n += 1 self.toolsmenu.add_command(label="Plater", command=self.doPlater) if self.settings.gcodeviewcmd is not None: n += 1 self.toolsmenu.add_command(label="GCode Viewer", command=self.doGCodeView) if self.settings.stlviewcmd is not None: n += 1 self.toolsmenu.add_command(label="STL Viewer", command=self.doSTLView) if self.settings.openscadcmd is not None: n += 1 self.toolsmenu.add_command(label="OpenSCAD", command=self.doOpenSCAD) if n > 0: self.menubar.add_cascade(label="Tools", menu=self.toolsmenu) try: self.master.config(menu=self.menubar) except AttributeError: self.master.tk.call(master, "config", "-menu", self.menubar) self.toolbar = ToolBar(self, self.printer, self.settings, self.logger) self.toolbar.grid(row=1, column=1, columnspan=4, sticky=W) self.ctl = MoveControl(self, self.printer, self.settings, self.logger) self.ctl.grid(row=2, column=1, rowspan=3, sticky=N) self.extr = Extruder(self, self.printer, self.settings, self.logger) self.extr.grid(row=2, column=2, rowspan=1, sticky=N + E + W) self.temps = Temperatures(self, self.printer, self.settings, self.logger) self.temps.grid(row=3, column=2, rowspan=2, sticky=N + E + W) self.gc = GcFrame(self, None, [], self.settings, self.logger) self.gc.grid(row=2, column=3, rowspan=3, sticky=N) self.statline = Status(self, self.printer, self.settings, self.logger) self.statline.grid(row=5, column=1, columnspan=4, sticky=E + W) self.logger.grid(row=2, column=4, rowspan=2, sticky=N + E + W) self.sendgcode = SendGCode(self, self.printer, self.settings, self.logger) self.sendgcode.grid(row=4, column=4, sticky=N + E + W) self.printer.errorcb = self.errorcb self.printer.sendcb = self.sendcb self.printer.recvcb = self.recvcb self.sd = SDCard(self, self.printer, self.settings, self.logger) self.firmware = FirmwareParms(self, self.printer, self.settings, self.logger) self.bind(MWM_FIRMWARECOMPLETE, self.firmwareReportComplete) self.bind(MWM_SLICERCOMPLETE, self.sliceComplete) self.bind(MWM_GCODELOADCOMPLETE, self.loadgcodeFinished) self.bind(MWM_GEDITMEASURECOMPLETE, self.geditMeasureComplete) self.bind(MWM_REQUESTPOSITIONREPORT, self.requestPosition) self.doShowButtons() def doStopAll(self): self.toolbar.doPause() self.temps.doOffBed() self.temps.doOffExt() def requestPosition(self, *arg): self.m114count += 1 self.printer.send_now("M400") # finish all moves self.printer.send_now("M114") def doShowButtons(self): self.settings.showmacrobuttons = self.cbShowMacroButtons.get() == 1 self.settings.setModified() if self.settings.showmacrobuttons: self.macroButtons = MacroButtons(self, self.printer, self.settings, self.logger) else: if self.macroButtons: self.macroButtons.close() self.macroButtons = None def toggleShowPrevious(self): self.settings.showprevious = self.cbShowPrevious.get() == 1 self.settings.setModified() self.gc.drawCanvas() def toggleShowMoves(self): self.settings.showmoves = self.cbShowMoves.get() == 1 self.settings.setModified() self.gc.drawCanvas() def selSlicer(self): self.settings.slicer = self.rbSlicer.get() self.settings.setModified() self.toolbar.setSliceText() def macroButtonClose(self): self.settings.showmacrobuttons = False self.settings.setModified() self.cbShowMacroButtons.set(False) def firmwareReportComplete(self, *arg): p = self.firmware.reportComplete() if p is not None: self.acceleration = p["m204_s"].getFlash() print "Retrieved acc value of ", self.acceleration def openSTLFile(self): if self.printing: self.logger.logMsg("Cannot open a new file while printing") return if self.StlFile is None: fn = askopenfilename( filetypes=[("STL files", "*.stl"), ("G Code files", "*.gcode")], initialdir=self.settings.lastdirectory ) else: fn = askopenfilename( filetypes=[("STL files", "*.stl"), ("G Code files", "*.gcode")], initialdir=self.settings.lastdirectory, initialfile=os.path.basename(self.StlFile), ) if fn: self.settings.lastdirectory = os.path.dirname(os.path.abspath(fn)) self.settings.setModified() if fn.lower().endswith(".gcode"): self.StlFile = None self.loadgcode(fn) elif fn.lower().endswith(".stl"): self.StlFile = fn self.doSlice(fn) else: self.logger.logMsg("Invalid file type") def openGCodeFile(self): if self.printing: self.logger.logMsg("Cannot open a new file while printing") return fn = askopenfilename(filetypes=[("G Code files", "*.gcode")], initialdir=self.settings.lastdirectory) if fn: self.settings.lastdirectory = os.path.dirname(os.path.abspath(fn)) self.settings.setModified() if fn.lower().endswith(".gcode"): self.StlFile = None self.loadgcode(fn) else: self.logger.logMsg("Invalid file type") else: self.toolbar.clearCancelMode() def loadgcode(self, fn): self.GCodeFile = fn self.gcodeloadSuccess = True self.toolbar.setLoading(True) self.loader = threading.Thread(target=self.loadgcodeThread) self.loader.daemon = True self.loader.start() def loadgcodeFinished(self, *arg): self.toolbar.setLoading(False) if self.gcodeloadSuccess: self.showMetrics() def loadgcodeThread(self): try: self.gcode = [] l = list(open(self.GCodeFile)) for s in l: self.gcode.append(s.rstrip()) self.logger.logMsg("read %d lines from %s" % (len(self.gcode), os.path.basename(self.GCodeFile))) except: self.logger.logMsg("Problem reading gcode from %s" % self.GCodeFile) self.gcode = [] self.GCodeFile = None if len(self.gcode) != 0: self.logger.logMsg("Processing...") self.gc.loadFile(self.GCodeFile, self.gcode) self.printStartLine = self.gc.getPrintStartLine() self.gcodeInfo = GCode(self.gcode) self.logger.logMsg("Measuring...") self.gcodeInfo.measure(self.acceleration) self.estEta = self.gcodeInfo.totalduration self.timeLayers = self.gcodeInfo.layerdurations else: self.gcodeloadSuccess = False self.event_generate(MWM_GCODELOADCOMPLETE) def replace(self, s, slicer): if slicer == SLIC3R: d = os.path.expandvars(os.path.expanduser(self.settings.s3profiledir)) profile = os.path.join(d, self.slic3r.getProfile() + ".ini") else: profile = self.skeinforge.getProfile() d = {} d["%starttime%"] = time.strftime("%H:%M:%S", time.localtime(self.startTime)) d["%endtime%"] = time.strftime("%H:%M:%S", time.localtime(self.endTime)) d["%elapsed%"] = formatElapsed(self.elapsedTime) d["%profile%"] = profile d["%slicer%"] = self.settings.slicer if self.StlFile is not None: d["%stlbase%"] = os.path.basename(self.StlFile) d["%stl%"] = self.StlFile else: d["%stlbase%"] = "" d["%stl%"] = "" if self.GCodeFile is not None: d["%gcodebase%"] = os.path.basename(self.GCodeFile) d["%gcode%"] = self.GCodeFile else: d["%gcodebase%"] = "" d["%gcode%"] = "" for t in d.keys(): if d[t] is not None: s = s.replace(t, d[t]) s = s.replace('""', "") return s def showMetrics(self): if len(self.gcode) != 0: self.paused = False self.toolbar.initializeToolbar() self.toolbar.checkAllowPrint() self.allowGEdit() self.logger.logMsg( "Width: %f mm (%f -> %f)" % (self.gcodeInfo.width, self.gcodeInfo.xmin, self.gcodeInfo.xmax) ) self.logger.logMsg( "Depth: %f mm (%f -> %f)" % (self.gcodeInfo.depth, self.gcodeInfo.ymin, self.gcodeInfo.ymax) ) self.logger.logMsg( "Height: is %f mm (%f -> %f)" % (self.gcodeInfo.height, self.gcodeInfo.zmin, self.gcodeInfo.zmax) ) self.logger.logMsg("Total extrusion length: %f mm" % self.gcodeInfo.filament_length()) self.logger.logMsg("Estimated print time: %s" % formatElapsed(self.estEta)) def calcEta(self, line, timeThusFar): foundLayer = False for i in range(len(self.timeLayers)): if self.timeLayers[i][0] > line: foundLayer = True break if not foundLayer: return 0 currentLayer = i - 1 if currentLayer < 0: return 0 totalInLayer = self.timeLayers[i][0] - self.timeLayers[currentLayer][0] printedInLayer = line - self.timeLayers[currentLayer][0] pct = printedInLayer / float(totalInLayer) thisLayerTime = (self.timeLayers[currentLayer][1]) * pct ratio = (self.timeLayers[currentLayer][2] - self.timeLayers[currentLayer][1] + thisLayerTime) / float( timeThusFar ) ne = self.estEta / float(ratio) return ne - timeThusFar def doTimingReport(self): if not self.printing: self.logger.logMsg("Only available while printing") return self.timingReport = TimingReport(self, self.printer, self.settings, self.logger) def closeTimingReport(self): if self.timingReport is not None: self.timingReport.cleanup() self.timingReport.destroy() self.timingReport = None def doMeasurementsReport(self): if not self.gcodeInfo: self.logger.logMsg("Only available when GCode loaded") return self.measurementsReport = MeasurementsReport(self, self.printer, self.settings, self.logger) def closeMeasurementsReport(self): if self.measurementsReport is not None: self.measurementsReport.destroy() self.measurementsReport = None def doFilamentReport(self): if not self.gcodeInfo: self.logger.logMsg("Only available when GCode loaded") return if len(self.gcodeInfo.filLayers) == 0: self.logger.logMsg("No filament usage in this gcode") return self.filamentReport = FilamentReport(self, self.printer, self.settings, self.logger) def closeFilamentReport(self): if self.filamentReport is not None: self.filamentReport.destroy() self.filamentReport = None def closeAllReports(self): self.closeTimingReport() self.closeFilamentReport() self.closeMeasurementsReport() def doPlater(self): s = self.replace(self.settings.platercmd, self.settings.slicer) args = shlex.split(os.path.expandvars(os.path.expanduser(s))) subprocess.Popen(args, close_fds=True) def doGCodeView(self): s = self.replace(self.settings.gcodeviewcmd, self.settings.slicer) args = shlex.split(os.path.expandvars(os.path.expanduser(s))) subprocess.Popen(args, close_fds=True) def doSTLView(self): s = self.replace(self.settings.stlviewcmd, self.settings.slicer) self.logger.logMsg(s) args = shlex.split(os.path.expandvars(os.path.expanduser(s))) subprocess.Popen(args, close_fds=True) def doOpenSCAD(self): s = self.replace(self.settings.openscadcmd, self.settings.slicer) args = shlex.split(os.path.expandvars(os.path.expanduser(s))) subprocess.Popen(args, close_fds=True) def doSlice(self, fn): self.paused = False self.toolbar.initializeToolbar() self.slicerfn = fn self.slicing = True self.slicerCancel = False self.toolbar.setCancelMode() if self.settings.slicer == SLIC3R: self.GCodeFile = fn.replace(".stl", ".gcode") cmd = self.replace(os.path.expandvars(os.path.expanduser(self.settings.s3cmd)), SLIC3R) else: self.GCodeFile = fn.replace(".stl", "_export.gcode") cmd = self.replace(os.path.expandvars(os.path.expanduser(self.settings.sfcmd)), SKEINFORGE) self.slicer = threading.Thread(target=self.slicerThread, args=(cmd,)) self.slicer.daemon = True self.slicer.start() def slicerThread(self, cmd): args = shlex.split(cmd) p = subprocess.Popen(args, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) obuf = "" while not self.slicerCancel: o = p.stdout.read(1) if o == "": break if o == "\r" or o == "\n": self.logger.logMsg(obuf) obuf = "" elif ord(o) < 32: pass else: obuf += o if self.slicerCancel: p.kill() p.wait() self.event_generate(MWM_SLICERCOMPLETE) def sliceComplete(self, *arg): self.slicing = False self.toolbar.clearCancelMode() if self.slicerCancel: self.slicerCancel = False self.logger.logMsg("Slicing was cancelled") return self.logger.logMsg("Slicing has completed successfully") if os.path.exists(self.GCodeFile): self.loadgcode(self.GCodeFile) else: self.logger.logMsg("Unable to find slicer output file: %s" % self.GCodeFile) def allowGEdit(self): self.editmenu.entryconfig(self.editmenu.index(GCODE_MENU_TEXT), state=NORMAL) def allowSliceMenu(self, flag=True): s = NORMAL if not flag: s = DISABLED self.filemenu.entryconfig(self.slicemenuindex, state=s) def allowLoadGCodeMenu(self, flag=True): s = NORMAL if not flag: s = DISABLED self.filemenu.entryconfig(self.loadgcodemenuindex, state=s) def doGEdit(self): GEditor(self, self.gcode, None) def geditMeasureComplete(self, *arg): self.showMetrics() def gEditSave(self, newgcode, fn, editwindow): if fn == None: self.gcode = newgcode self.meas = threading.Thread(target=self.geditMeasureThread) self.meas.daemon = True self.meas.start() return False else: try: f = open(fn, "w") for l in newgcode: f.write(l + "\n") f.close() self.logger.logMsg("Alterations %s successfully saved" % fn) return True except: self.logger.logMsg("Unable to open %s for output" % fn) return False def geditMeasureThread(self): self.logger.logMsg("Processing...") self.gcodeInfo = GCode(self.gcode) self.logger.logMsg("Measuring...") self.gcodeInfo.measure(self.acceleration) self.estEta = self.gcodeInfo.totalduration self.timeLayers = self.gcodeInfo.layerdurations self.event_generate(MWM_GEDITMEASURECOMPLETE) def doSD(self): if not self.sd.isActive(): self.sd.start() def setToolbarSDPrint(self): self.toolbar.setSDPrint() def startUpload(self): self.sduploading = True self.toolbar.doPrint() def printerAvailable(self, silent=False, cmd="xx"): if not self.connected: if not silent: self.logger.logMsg("Unable to comply - printer not on-line") return False if (self.printing or self.sdprinting) and cmd.upper() not in allow_while_printing: if not silent: self.logger.logMsg("Unable to comply - currently printing") return False return True def printerConnected(self, flag): self.sendgcode.activate(flag) self.connected = flag if flag: self.firmware.start(True) def updateScreen(self): if self.printing: self.gc.updatePrintProgress(self.printer.queueindex) def errorcb(self, s): self.logger.logMsg(s.rstrip()) def sendcb(self, s): # self.logger.logMsg("Sent: %s" % s) pass def recvcb(self, s): if self.readingFirmware: if "M92" in s: X = self.parseG(s, "X") Y = self.parseG(s, "Y") Z = self.parseG(s, "Z") E = self.parseG(s, "E") self.firmware.m92(X, Y, Z, E) return elif "M201" in s: X = self.parseG(s, "X") Y = self.parseG(s, "Y") Z = self.parseG(s, "Z") E = self.parseG(s, "E") self.firmware.m201(X, Y, Z, E) return elif "M203" in s: X = self.parseG(s, "X") Y = self.parseG(s, "Y") Z = self.parseG(s, "Z") E = self.parseG(s, "E") self.firmware.m203(X, Y, Z, E) return elif "M204" in s: S = self.parseG(s, "S") T = self.parseG(s, "T") self.firmware.m204(S, T) return elif "M205" in s: S = self.parseG(s, "S") T = self.parseG(s, "T") B = self.parseG(s, "B") X = self.parseG(s, "X") Z = self.parseG(s, "Z") E = self.parseG(s, "E") self.firmware.m205(S, T, B, X, Z, E) return elif "M206" in s: X = self.parseG(s, "X") Y = self.parseG(s, "Y") Z = self.parseG(s, "Z") self.firmware.m206(X, Y, Z) return elif "M301" in s: P = self.parseG(s, "P") I = self.parseG(s, "I") D = self.parseG(s, "D") self.firmware.m301(P, I, D) return elif ( ("Steps per unit" in s) or ("Acceleration:" in s) or ("Maximum Acceleration" in s) or ("Maximum feedrates" in s) or ("Advanced variables" in s) or ("Home offset" in s) or ("PID settings" in s) or ("Stored settings retreived" in s) ): return if self.sdchecking: if "SD card ok" in s: self.sdchecking = False self.sdpresent = True self.sd.sdCheckComplete(True) return elif "SD init fail" in s: self.sdchecking = False self.sdpresent = False self.sd.sdCheckComplete(False) return if self.sdlisting: if "Begin file list" in s: self.insidelisting = True self.sdfiles = [] return elif "End file list" in s: self.sdlisting = False self.insidelisting = False self.sd.sdListComplete(self.sdfiles) return else: if self.insidelisting: self.sdfiles.append(s.strip()) return if "SD printing byte" in s: m = self.sdre.search(s) t = m.groups() if len(t) != 2: return self.sdbytes = int(t[0]) self.sdmaxbytes = int(t[1]) return elif "Done printing file" in s: if self.sdprinting: self.sdprinting = False self.toolbar.clearSDPrint() m = self.speedrptre.search(s) if m: t = m.groups() if len(t) >= 3: if self.settings.forcefanspeed: ns = int(t[0]) if ns != self.FanSpeed: self.logger.logMsg("Asserting fan speed of %d" % self.FanSpeed) self.toolbar.forceFanSpeed(self.FanSpeed) else: self.FanSpeed = int(t[0]) self.FeedMultiply = int(t[1]) self.ExtrudeMultiply = int(t[2]) self.toolbar.syncSpeeds() if self.speedcount > 0: self.speedcount -= 1 return m = self.locrptre.search(s) if m: t = m.groups() if len(t) >= 4: self.location[XAxis] = float(t[0]) self.location[YAxis] = float(t[1]) self.location[ZAxis] = float(t[2]) self.location[EAxis] = float(t[3]) if self.m114count != 0: self.m114count -= 1 if self.m114count < 0: self.m114count = 0 return if s.startswith("ok"): return if s.startswith("echo:"): s = s[5:] m = self.rpt1re.search(s) if m: t = m.groups() if len(t) >= 1: self.exttemp = float(t[0]) if len(t) >= 2: self.bedtemp = float(t[1]) self.temps.updateTempDisplay(self.bedtemp, self.exttemp) m = self.rpt2re.search(s) if m: t = m.groups() if len(t) >= 1: self.exttemp = float(t[0]) self.temps.updateTempDisplay(self.bedtemp, self.exttemp) self.logger.logMsg(s.rstrip()) def parseG(self, s, v): l = s.split() for p in l: if p.startswith(v): try: return float(p[1:]) except: return None return None def editSettings(self): # TO DO pass def slic3rSettings(self): s = self.replace(self.settings.s3config, SLIC3R) args = shlex.split(os.path.expandvars(os.path.expanduser(s))) subprocess.Popen(args, close_fds=True) def skeinforgeSettings(self): s = self.replace(self.settings.sfconfig, SKEINFORGE) args = shlex.split(os.path.expandvars(os.path.expanduser(s))) subprocess.Popen(args, close_fds=True) def chooseS3Profile(self): pl = self.slic3r.getProfileOptions() if len(pl) > 0: l = ListBoxChoice( clist=pl.keys(), master=self, title="Choose Slic3r Profile", message="Choose Slic3r profile" ) pn = l.returnValue() if pn: self.slic3r.setProfile(pn) self.setS3ProfileMenuText() self.toolbar.setSliceText() else: self.logger.logMsg("Unable to retrieve available slic3r profiles") def chooseSFProfile(self): pl = self.skeinforge.getProfileOptions() if len(pl) > 0: l = ListBoxChoice( clist=pl.keys(), master=self, title="Choose Skeinforge Profile", message="Choose Skeinforge profile" ) pn = l.returnValue() if pn: self.skeinforge.setProfile(pn) self.setSFProfileMenuText() self.toolbar.setSliceText() else: self.logger.logMsg("Unable to retrieve available skeinforge profiles") def setS3ProfileMenuText(self): self.slicermenu.entryconfig(self.S3profileindex, label="Choose Profile (%s)" % self.slic3r.getProfile()) def setSFProfileMenuText(self): self.slicermenu.entryconfig(self.SFprofileindex, label="Choose Profile (%s)" % self.skeinforge.getProfile()) def quitApp(self): self.cleanUp() self.master.quit() def cleanUp(self): if self.connected: self.printer.disconnect() if self.slicing: self.slicerCancel = True self.httpServer.close() self.statline.cleanUp() self.settings.cleanUp() def doEditMacro(self): idir = os.path.join(self.settings.cmdFolder, "macros") try: l = os.listdir(idir) except: self.logger.logMsg("Unable to get listing from macros directory: " + idir) return r = [] for f in sorted(l): if f.endswith(".macro"): r.append(f) l = ListBoxChoice(master=self, title="Macro Files", message="Choose a macro to edit", clist=r) fn = l.returnValue() if fn: try: fn = os.path.join(idir, fn) with open(fn) as f: text = f.read() self.macroEdit = MacroEdit(self, self.printer, self.settings, self.logger, fn, text) except: self.logger.logMsg("Unable to open %s for input" % fn) def doEditAlterations(self): idir = os.path.expandvars(os.path.expanduser(self.settings.sfalterationsdir)) try: l = os.listdir(idir) except: self.logger.logMsg("Unable to get listing from alterations directory: " + idir) return r = [] for f in sorted(l): if f.endswith(".gcode"): r.append(f) l = ListBoxChoice(master=self, title="Alteration Files", message="Choose an alteration file to edit", clist=r) fn = l.returnValue() if fn: try: fn = os.path.join(idir, fn) text = [line.strip() for line in open(fn)] GEditor(self, text, fn) except: self.logger.logMsg("Unable to open %s for input" % fn) def doNewMacro(self): self.macroEdit = MacroEdit(self, self.printer, self.settings, self.logger, None, "") def doDelMacro(self): idir = os.path.join(self.settings.cmdFolder, "macros") try: l = os.listdir(idir) except: self.logger.logMsg("Unable to get listing from macros directory: " + idir) return r = [] for f in sorted(l): if f.endswith(".macro"): r.append(f) l = ListBoxChoice(master=self, title="Macro Files", message="Choose a macro to delete", clist=r) fn = l.returnValue() if fn: if askyesno("Delete?", "Are you sure you want to delete this macro?", parent=self): try: os.unlink(os.path.join(idir, fn)) self.adjustMacroMenu(fn, True) if self.settings.getMacroList().delMacroByName(fn): self.settings.setModified() if self.settings.showmacrobuttons: self.macroButtons.close() self.macroButtons = MacroButtons(self, self.printer, self.settings, self.logger) except: self.logger.logMsg("Unable to delete %s" % fn) def macroEditSave(self, fn, text, btn, editwindow): if fn == None: idir = os.path.join(self.settings.cmdFolder, "macros") try: l = os.listdir(idir) except: self.logger.logMsg("Unable to get listing from macros directory: " + idir) return r = [] for f in sorted(l): if f.endswith(".macro"): r.append(f) l = ListBoxChoice( master=self, title="Macro Files", message="Choose a macro to overwrite", clist=r, newmessage="or enter new file name:", ) fn = l.returnValue() if fn: fn = os.path.join(idir, fn) if not fn.endswith(".macro"): fn += ".macro" if fn is None: return False try: f = open(fn, "w") f.write(text) f.close() self.settings.setModified() if btn != None: if not self.settings.getMacroList().addMacro(btn[0], btn[1], os.path.basename(fn), btn[2]): self.settings.getMacroList().setMacroByName(btn[0], btn[1], os.path.basename(fn), btn[2]) self.settings.setModified() if self.settings.showmacrobuttons: self.macroButtons.close() self.macroButtons = MacroButtons(self, self.printer, self.settings, self.logger) self.adjustMacroMenu(fn) self.logger.logMsg("Macro %s successfully saved" % fn) return True except: self.logger.logMsg("Unable to open %s for output" % fn) return False def macroEditExit(self, fn): pass def loadMacros(self): p = os.path.join(".", "macros") if not os.path.exists(p): os.makedirs(p) self.macroList = {} for filename in sorted(os.listdir(p)): if filename.endswith(".macro"): n = os.path.splitext(filename)[0] self.macroList[n] = 1 self.runmacromenu.add_command(label=n, command=lambda m=n: self.doMacro(m)) def adjustMacroMenu(self, fn, delete=False): mn = os.path.splitext(os.path.basename(fn))[0] if not delete: if mn in self.macroList: # nothing to be done here pass else: self.macroList[mn] = 1 self.runmacromenu.add_command(label=mn, command=lambda m=mn: self.doMacro(name=mn)) else: # delete the menu entry if mn in self.macroList: self.runmacromenu.delete(self.runmacromenu.index(mn)) del self.macroList[mn] else: # huh?? pass def doMacro(self, name=None, fname=None, silent=False): if name: if not silent: self.logger.logMsg("Invoking macro: %s" % name) n = os.path.join(self.settings.cmdFolder, "macros", name + ".macro") elif fname: if not silent: self.logger.logMsg("Invoking macro file: %s" % fname) n = os.path.join(self.settings.cmdFolder, "macros", fname) else: self.logger.logMsg("Error - must provide a macro name or filename") return try: l = list(open(n)) for s in l: sl = s.lower() if sl.startswith("@log "): self.logger.logMsg(self.replace(s[5:].strip(), self.settings.slicer)) elif sl.startswith("@sh "): s = self.replace(sl[4:], self.settings.slicer) args = shlex.split(os.path.expandvars(os.path.expanduser(s))) subprocess.Popen(args, close_fds=True) else: verb = s.split()[0] if self.printerAvailable(cmd=verb): self.printer.send_now(s) else: self.logger.logMsg("Printer not available for %s command" % verb) if not silent: self.logger.logMsg("End of macro") except: self.logger.logMsg("Error attempting to invoke macro file %s" % n) def FirmwareSettings(self): if self.connected: if not self.firmware.isActive(): self.firmware.start() else: self.logger.logMsg("Unable to comply - printer not on-line") def doDataLogReport(self): for d in DLLIST: self.logger.logMsg("%s Usage: %s" % (DLNAMES[d], self.dataLoggers[d].getToNowStr())) def doDataLogReset(self): DataLogReset(self)
class CeFrame(Frame): '''\ CeFrame is a frame designed to be a Windows CE compliant window. A CeFrame will track the SIP position and size and will automatically resize itself to always fit the screen. ''' _dispatchers = {"_activate" : (MSGEventDispatcher, WM_ACTIVATE), "_settingchanged" : (MSGEventDispatcher, WM_SETTINGCHANGE), } _dispatchers.update(Frame._dispatchers) def __init__(self, parent=None, title="PocketPyGui", action=None, menu=None, right_action=None, tab_traversal=True, visible=True, enabled=True, has_sip=True, has_toolbar=False): '''\ Arguments : - parent: the parent window of this CeFrame. - title: the title as appearing in the title bar. - action : a tuple ('Label', callback) . - menu : the title of the right menu as a string if not None, the menu can be filled via the cb_menu attribute after CeFrame initialization. ''' Frame.__init__(self, parent, title, tab_traversal=tab_traversal, visible=visible, enabled=enabled) self.bind(_activate=self._on_activate, _settingchanged=self._on_setting_changed, size=self._on_size) if has_toolbar : self.toolbar = ToolBar(self) else: self.toolbar = None self.__create_menubar(action, menu, right_action, has_sip) def _on_size(self, ev): if ev.wParam == 1: self.close() else: self.layout() ev.skip() def layout(self): if self.toolbar is None: return Frame.layout(self) if self._sizer is not None: rc = RECT() GetClientRect(self._w32_hWnd, byref(rc)) self._sizer.size(rc.left, rc.top, rc.right, rc.bottom-24*HIRES_MULT) self.toolbar.move(rc.left, rc.bottom-26*HIRES_MULT, rc.right-rc.left, 26*HIRES_MULT) def __create_menubar(self, action, menu, right_action, has_sip): mbi = SHMENUBARINFO() mbi.cbSize = sizeof(SHMENUBARINFO) mbi.hwndParent = self._w32_hWnd mbi.hInstRes = GetModuleHandle(0) slots = [] empty = True has_action = False has_menu = False has_right_action = False if (action is None) and (menu is None) : mbi.dwFlags = SHCMBF_EMPTYBAR else : empty = False temp_menu = Menu() i = 0 if action is not None: label, cb = action action_item = temp_menu.append(label, callback=cb) #self.action = CommandBarAction(item, 0) else: action_item = temp_menu.append("", enabled=False) if right_action is not None: label, cb = right_action right_action_item = temp_menu.append(label, callback=cb) has_right_action = True elif menu is not None: sub_menu = PopupMenu() temp_menu.append_menu(menu, sub_menu) has_menu = True mbi.dwFlags = SHCMBF_HMENU mbi.nToolBarId = temp_menu._hmenu if not has_sip: mbi.dwFlags |= SHCMBF_HIDESIPBUTTON SHCreateMenuBar(byref(mbi)) self._mb_hWnd = mbi.hwndMB if not empty: self.cb_action = CommandBarAction(mbi.hwndMB, 0, action_item) if has_right_action: self.cb_right_action = CommandBarAction(mbi.hwndMB, 1, right_action_item) elif has_menu: tbbi = TBBUTTONINFO() tbbi.cbSize = sizeof(tbbi) tbbi.dwMask = 0x10 | 0x80000000 SendMessage(mbi.hwndMB, WM_USER+63, 1, byref(tbbi)) hMenu = tbbi.lParam self.cb_menu = CommandBarMenu(mbi.hwndMB, 1, hMenu) rc = RECT() GetWindowRect(self._w32_hWnd, byref(rc)) rcmb = RECT() GetWindowRect(self._mb_hWnd, byref(rcmb)) rc.bottom -= (rcmb.bottom - rcmb.top) self.move(rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top) def _on_activate(self, event): if not hasattr(self, '_shai'): self._shai = InitSHActivateInfo() SHHandleWMActivate(event.hWnd, event.wParam, event.lParam, byref(self._shai), 0) def _on_setting_changed(self, event): if not hasattr(self, '_shai'): self._shai = InitSHActivateInfo() SHHandleWMSettingChange(self._w32_hWnd, event.wParam, event.lParam, byref(self._shai)) def show_sipbutton(self, show=True): if show: SHFullScreen(self._w32_hWnd, SHFS_SHOWSIPBUTTON) else: SHFullScreen(self._w32_hWnd, SHFS_HIDESIPBUTTON) def hide_sipbutton(self): self.show_sipbutton(False)
def build(self): self.root = Tk() self.root.geometry("800x622+200+200") self.root.title("SecureMe") self.root.resizable(width=FALSE, height=FALSE) menubar = Menu(self.root) optionsmenu = Menu(menubar, tearoff=0) optionsmenu.add_command(label="Refresh (Ctrl+r)", command=lambda: self.refresh("NONE")) optionsmenu.add_command(label="Exit", command=lambda: self.quitMenu()) menubar.add_cascade(label="Options", menu=optionsmenu) self.root.config(menu=menubar) self.toolbar = ToolBar(self.root, self) style = Style() style.configure("BW.TLabel", foreground="black", background="slate gray", borderwidth=2) mFrame = Frame(self.root, bg="slate gray", padx=25, pady=25) mFrame.pack(fill=BOTH) self.notebook = ttk.Notebook(mFrame, height=500, style="BW.TLabel") primaryFrame = Frame(self.notebook, padx=25, pady=25) usersFrame = Frame(self.notebook, padx=25, pady=25) firewallFrame = Frame(self.notebook, padx=25, pady=25) servicesFrame = Frame(self.notebook, padx=25, pady=25) processesFrame = Frame(self.notebook, padx=25, pady=25) self.notebook.add(primaryFrame, text='Primary') self.notebook.add(usersFrame, text='Users') self.notebook.add(firewallFrame, text='Firewall') self.notebook.add(servicesFrame, text='Services') self.notebook.add(processesFrame, text='Processes') self.notebook.pack(fill=X) self.updatebar = Frame(self.root) self.updatebar.pack(side=BOTTOM, fill=X) self.left_label = Label(self.updatebar, text="Status: None") self.left_label.pack(side=LEFT, fill=X) # Primary Panel primary_label = Label(primaryFrame, text='Primary Settings', font=self.liberation_font_15) primary_label.grid(row=0, column=0, columnspan=2, sticky=N + S + E + W) actionspanel = LabelFrame(primaryFrame, text='System Actions', padx=10, pady=10) actionspanel.grid(row=1, column=0, sticky=E + N, padx=25, pady=25) openterminal = Button(actionspanel, text='Open Terminal', command=lambda: self.openTerminal()) openterminal.pack(padx=5, pady=5) opencontrol = Button(actionspanel, text='Open Control Panel', command=lambda: self.openControlPanel()) opencontrol.pack(padx=5, pady=5) shutdown = Button(actionspanel, text='Shutdown', command=lambda: self.shutdown()) shutdown.pack(padx=5, pady=5) rebootButton = Button(actionspanel, text='Reboot', command=lambda: self.reboot()) rebootButton.pack(padx=5, pady=5) updatespanel = LabelFrame(primaryFrame, text='System Updates', padx=10, pady=10) updatespanel.grid(row=1, column=1, sticky=W + N, padx=25, pady=25) update_button = Button(updatespanel, text='Basic Update', command=lambda: self.basicUpdate()) update_button.pack(padx=5, pady=5) upgrade_button = Button(updatespanel, text='Basic Upgrade', command=lambda: self.basicUpgrade()) upgrade_button.pack(padx=5, pady=5) packageupdate_button = Button(updatespanel, text='Package Update', command=lambda: self.packageUpdate()) packageupdate_button.pack(padx=5, pady=5) # Users Panel users_label = Label(usersFrame, text='User Security Settings', font=self.liberation_font_15) users_label.pack() editusers = Frame(usersFrame) editusers.pack() addusr = Button(editusers, text='Add User...', command=lambda: self.addUser()) addusr.grid(row=0, column=0, padx=5, pady=5) delusr = Button(editusers, text='Del User...', command=lambda: self.delUser()) delusr.grid(row=0, column=1, padx=5, pady=5) userpanel = LabelFrame(usersFrame, text="Users", padx=10, pady=10) userpanel.pack(side=TOP, fill=BOTH) self.uText = self.getUserText() self.users_listlabel = Label(userpanel, text=self.uText, padx=10, pady=10) self.users_listlabel.pack(side=LEFT) groupspanel = LabelFrame(usersFrame, text="Groups", padx=10, pady=10) groupspanel.pack(side=TOP, fill=BOTH) self.gText = self.getGroupText() self.groups_text = CustomText(groupspanel) self.groups_text.resetText(self.gText) self.groups_text.type(DISABLED) self.groups_text.pack(fill=BOTH) # Firewall Label firewall_label = Label(firewallFrame, text='Firewall Settings', font=self.liberation_font_15) firewall_label.pack() edFrame = Frame(firewallFrame) fwEnable = Button(edFrame, text='Enable', command=lambda: self.enableFirewall()) fwEnable.pack(side=LEFT, padx=10, pady=10, fill=X) fwDisable = Button(edFrame, text='Disable', command=lambda: self.disableFirewall()) fwDisable.pack(side=RIGHT, padx=10, pady=10, fill=X) edFrame.pack() firewallpanel = LabelFrame(firewallFrame, text='Firewall Status', height=100, width=450, padx=10, pady=10) firewallpanel.pack(side=TOP, fill=X) self.fText = self.getFirewallStatus() self.firewall_text = CustomText(firewallpanel) self.firewall_text.resetText(self.fText) self.firewall_text.type(DISABLED) self.firewall_text.pack(fill=X) # Services Pane services_label = Label(servicesFrame, text='System Services', font=self.liberation_font_15) services_label.pack() servicespanel = LabelFrame(servicesFrame, text="Services", padx=10, pady=10) servicespanel.pack(side=TOP, fill=BOTH) self.sText = self.getServicesText() self.services_text = CustomText(servicespanel) self.services_text.resetText(self.sText) self.services_text.type(DISABLED) self.services_text.pack(fill=BOTH) # Processes Pane processes_label = Label(processesFrame, text='System Processes', font=self.liberation_font_15) processes_label.pack() processespanel = LabelFrame(processesFrame, text='Processes', padx=10, pady=10) processespanel.pack(side=TOP, fill=BOTH) self.pText = self.getProcessesText() self.processes_text = CustomText(processespanel) self.processes_text.resetText(self.pText) self.processes_text.type(DISABLED) self.processes_text.pack(fill=BOTH) self.root.bind('<Control-r>', self.refresh) self.root.mainloop()
def create_toolbar(self): self.grid(row=0, sticky='w') self.toolbar = ToolBar(self)
class MainWindow(object): def __init__(self, *args, **kwargs): self._toolbar = None self._menubar = None self._statusbar = None self._rootwidget = None self._centralwidget = None self._dockareas = { DOCKAREA['left']: None, DOCKAREA['right']: None, DOCKAREA['top']: None, DOCKAREA['bottom']: None } self._toolbarareas = { DOCKAREA['left']: None, DOCKAREA['right']: None, DOCKAREA['top']: None, DOCKAREA['bottom']: None } self.dockareamarker = None def initGui(self, screen_width, screen_height): bar_height = 30 self._dockareas[DOCKAREA['left']] = DockArea("left") self._dockareas[DOCKAREA['right']] = DockArea("right") self._dockareas[DOCKAREA['top']] = DockArea("top") self._dockareas[DOCKAREA['bottom']] = DockArea("bottom") self._toolbarareas[DOCKAREA['left']] = pychan.widgets.VBox(margins=(0, 0, 0, 0)) self._toolbarareas[DOCKAREA['right']] = pychan.widgets.VBox( margins=(0, 0, 0, 0)) self._toolbarareas[DOCKAREA['top']] = pychan.widgets.HBox(margins=(0, 0, 0, 0)) self._toolbarareas[DOCKAREA['bottom']] = pychan.widgets.HBox( margins=(0, 0, 0, 0)) self._statusbar = StatusBar(text=u"", panel_size=bar_height) self._toolbar = ToolBar(title=u"Toolbar", button_style=0) self._menubar = MenuBar(min_size=(screen_width, bar_height), position=(0, 0)) # Set up root widget self._rootwidget = pychan.widgets.VBox(padding=0, vexpand=1, hexpand=1) self._rootwidget.min_size = \ self._rootwidget.max_size = (screen_width, screen_height) self._rootwidget.opaque = False # This is where the map will be displayed self._centralwidget = pychan.widgets.VBox(vexpand=1, hexpand=1) self._centralwidget.opaque = False middle = pychan.widgets.HBox(padding=0, vexpand=1, hexpand=1) middle.opaque = False # Pychan bug? Adding a spacer instead of a container creates # a gap after the right dockarea middle.addChild(self._toolbarareas['left']) middle.addChild(self._dockareas['left']) middle.addChild(self._centralwidget) #middle.addSpacer(pychan.widgets.Spacer()) middle.addChild(self._dockareas['right']) middle.addChild(self._toolbarareas['right']) self._rootwidget.addChild(self._menubar) #self._rootwidget.addChild(self._toolbar) self._rootwidget.addChild(self._toolbarareas['top']) self._rootwidget.addChild(self._dockareas['top']) self._rootwidget.addChild(middle) self._rootwidget.addChild(self._dockareas['bottom']) self._rootwidget.addChild(self._toolbarareas['bottom']) self._rootwidget.addChild(self._statusbar) self._toolbar.setDocked(True) self.dockWidgetTo(self._toolbar, "top") self._rootwidget.show() def getCentralWidget(self): return self._centralwidget def getStatusBar(self): return self._statusbar def getMenuBar(self): return self._menubar def getToolBar(self): return self._toolbar def dockWidgetTo(self, widget, dockarea, x=-1, y=-1): """ docks a B{Panel} widget to the given dock area @note: - ToolBar needs special treatment, given x, y coordinates have no effect on this Panel - x, y are cursor coordinates, without giving them the widgets are added beneath the already existing ones nice feature, but also makes problems on editor startup (e.g. if a user docked 2 widgets left, on startup they are added in a col instead of a grouped tab) @todo: turn x,y documentation into something more useful @type widget: Panel @param widget: a panel widget instance @type dockarea: str @param dockarea: id of the target dock area @type x: int @param x: x coordinate @type y: int @param y: y coordinate """ if isinstance(widget, pychan.widgets.Widget) is False: print "Argument is not a valid widget" return if widget.parent: widgetParent = widget.parent widgetParent.removeChild(widget) widgetParent.adaptLayout() # We must hide the widget before adding it to the dockarea, # or we will get a duplicate copy of the widget in the top left corner # of screen. #widget.hide() dockareas = self._dockareas # Panel widgets which provide an implementation for set_orientation() # should check if they need to re-align themselves if hasattr(widget, 'set_orientation'): key = '' if dockarea == DOCKAREA['left'] or dockarea == DOCKAREA['right']: key = 'Vertical' elif dockarea == DOCKAREA['top'] or dockarea == DOCKAREA['bottom']: key = 'Horizontal' widget.set_orientation(key=key) if isinstance(widget, ToolBar): dockareas = self._toolbarareas docked = False if dockarea == DOCKAREA['left']: docked = True dockareas[DOCKAREA['left']].addChild(widget) dockareas[DOCKAREA['left']].adaptLayout() elif dockarea == DOCKAREA['right']: docked = True dockareas[DOCKAREA['right']].addChild(widget) dockareas[DOCKAREA['right']].adaptLayout() elif dockarea == DOCKAREA['top']: docked = True dockareas[DOCKAREA['top']].addChild(widget) dockareas[DOCKAREA['top']].adaptLayout() elif dockarea == DOCKAREA['bottom']: docked = True dockareas[DOCKAREA['bottom']].addChild(widget) dockareas[DOCKAREA['bottom']].adaptLayout() else: print "Invalid dockarea" widget.dockareaname = dockarea widget.setDocked(docked) else: if dockarea == DOCKAREA['left']: dockareas[DOCKAREA['left']].dockChild(widget, x, y) elif dockarea == DOCKAREA['right']: dockareas[DOCKAREA['right']].dockChild(widget, x, y) elif dockarea == DOCKAREA['top']: dockareas[DOCKAREA['top']].dockChild(widget, x, y) elif dockarea == DOCKAREA['bottom']: dockareas[DOCKAREA['bottom']].dockChild(widget, x, y) else: print "Invalid dockarea" def getToolbarAreaAt(self, x, y, mark=False): if self.dockareamarker is None: self.dockareamarker = pychan.widgets.Container() self.dockareamarker.base_color = fifechan.Color(200, 0, 0, 100) if mark is False: self.dockareamarker.hide() # Mouse wasn't over any dockwidgets. See if it is near any edge of the screen instead if x <= self._toolbarareas["left"].getAbsolutePos()[0] + 10: if mark: self.dockareamarker.position = self._toolbarareas[ "left"].getAbsolutePos() self.dockareamarker.size = (10, self._toolbarareas["left"].height) self.dockareamarker.show() return DOCKAREA["left"] elif x >= self._toolbarareas["right"].getAbsolutePos()[0] - 10: if mark: self.dockareamarker.position = self._toolbarareas[ "right"].getAbsolutePos() self.dockareamarker.size = (10, self._toolbarareas["right"].height) self.dockareamarker.x -= 10 self.dockareamarker.show() return DOCKAREA["right"] elif y <= self._toolbarareas["top"].getAbsolutePos()[1] + 10: if mark: self.dockareamarker.position = self._toolbarareas[ "top"].getAbsolutePos() self.dockareamarker.size = (self._toolbarareas["top"].width, 10) self.dockareamarker.show() return DOCKAREA["top"] elif y >= self._toolbarareas["bottom"].getAbsolutePos()[1] - 10: if mark: self.dockareamarker.position = self._toolbarareas[ "bottom"].getAbsolutePos() self.dockareamarker.y -= 10 self.dockareamarker.size = (self._toolbarareas["bottom"].width, 10) self.dockareamarker.show() return DOCKAREA["bottom"] if mark is True: self.dockareamarker.hide() return None def getDockAreaAt(self, x, y, mark=False): """ returns the dock area at the given cursor coordinates (if possible) also used for highlighting the dock area (this method is used on drag mouse events of a B{Panel} widget) @type x: int @param x: cursor x coordinates @type y: int @param y: cursor y coordinates @type mark: bool @param mark: flag to wether show the dock area marker (red area indicator) or not @rtype side: str @return side: dockarea id (e.g. 'right', 'left' ...) """ side = None if self.dockareamarker is None: self.dockareamarker = pychan.widgets.Container() self.dockareamarker.base_color = fifechan.Color(200, 0, 0, 100) if mark is False: self.dockareamarker.hide() for key in DOCKAREA: side = DOCKAREA[key] dockarea = self._dockareas[side] #absX, absY = dockarea.getAbsolutePos() #if absX <= x and absY <= y \ # and absX+dockarea.width >= x and absX+dockarea.height >= y: # return side placeIn, placeBefore, placeAfter = dockarea.getDockLocation(x, y) if placeIn or placeBefore or placeAfter: if mark is True: if placeIn: self.dockareamarker.position = placeIn.getAbsolutePos() self.dockareamarker.size = placeIn.size elif placeBefore: self.dockareamarker.position = placeBefore.getAbsolutePos( ) if side == "left" or side == "right": self.dockareamarker.size = (placeBefore.width, 10) else: self.dockareamarker.size = (10, placeBefore.height) elif placeAfter: self.dockareamarker.position = placeAfter.getAbsolutePos( ) if side == "left" or side == "right": self.dockareamarker.size = (placeAfter.width, 10) self.dockareamarker.y += placeAfter.height - 10 else: self.dockareamarker.size = (10, placeAfter.height) self.dockareamarker.x += placeAfter.width - 10 self.dockareamarker.show() return side # reset side, next attempt to find a new home side = None # Mouse wasn't over any dockwidgets. See if it is near any edge of the screen instead if x <= self._dockareas["left"].getAbsolutePos()[0] + 10: if mark: self.dockareamarker.position = self._dockareas[ "left"].getAbsolutePos() self.dockareamarker.size = (10, self._dockareas["left"].height) self.dockareamarker.show() side = DOCKAREA["left"] return side elif x >= self._dockareas["right"].getAbsolutePos()[0] - 10: if mark: self.dockareamarker.position = self._dockareas[ "right"].getAbsolutePos() self.dockareamarker.size = (10, self._dockareas["right"].height) self.dockareamarker.x -= 10 self.dockareamarker.show() side = DOCKAREA["right"] return side elif y <= self._dockareas["top"].getAbsolutePos()[1] + 10: if mark: self.dockareamarker.position = self._dockareas[ "top"].getAbsolutePos() self.dockareamarker.size = (self._dockareas["top"].width, 10) self.dockareamarker.show() side = DOCKAREA["top"] return side elif y >= self._dockareas["bottom"].getAbsolutePos()[1] - 10: if mark: self.dockareamarker.position = self._dockareas[ "bottom"].getAbsolutePos() self.dockareamarker.y -= 10 self.dockareamarker.size = (self._dockareas["bottom"].width, 10) self.dockareamarker.show() side = DOCKAREA["bottom"] return side if mark is True: self.dockareamarker.hide() return side
class GtkUI(object): def __init__(self, args): self.daemon_bps = (0, 0, 0) # Setup signals try: import gnome.ui import gnome self.gnome_prog = gnome.init("Deluge", deluge.common.get_version()) self.gnome_client = gnome.ui.master_client() def on_die(*args): reactor.stop() self.gnome_client.connect("die", on_die) log.debug("GNOME session 'die' handler registered!") except Exception, e: log.warning( "Unable to register a 'die' handler with the GNOME session manager: %s", e) if deluge.common.windows_check(): from win32api import SetConsoleCtrlHandler from win32con import CTRL_CLOSE_EVENT from win32con import CTRL_SHUTDOWN_EVENT def win_handler(ctrl_type): log.debug("ctrl_type: %s", ctrl_type) if ctrl_type in (CTRL_CLOSE_EVENT, CTRL_SHUTDOWN_EVENT): reactor.stop() return 1 SetConsoleCtrlHandler(win_handler) # Attempt to register a magnet URI handler with gconf, but do not overwrite # if already set by another program. common.associate_magnet_links(False) # Make sure gtkui.conf has at least the defaults set self.config = deluge.configmanager.ConfigManager( "gtkui.conf", DEFAULT_PREFS) # We need to check on exit if it was started in classic mode to ensure we # shutdown the daemon. self.started_in_classic = self.config["classic_mode"] # Start the IPC Interface before anything else.. Just in case we are # already running. self.queuedtorrents = QueuedTorrents() self.ipcinterface = IPCInterface(args) # Initialize gdk threading gtk.gdk.threads_init() # We make sure that the UI components start once we get a core URI client.set_disconnect_callback(self.__on_disconnect) self.trackericons = TrackerIcons() self.sessionproxy = SessionProxy() # Initialize various components of the gtkui self.mainwindow = MainWindow() self.menubar = MenuBar() self.toolbar = ToolBar() self.torrentview = TorrentView() self.torrentdetails = TorrentDetails() self.sidebar = SideBar() self.filtertreeview = FilterTreeView() self.preferences = Preferences() self.systemtray = SystemTray() self.statusbar = StatusBar() self.addtorrentdialog = AddTorrentDialog() # Initalize the plugins self.plugins = PluginManager() # Late import because of setting up translations from connectionmanager import ConnectionManager # Show the connection manager self.connectionmanager = ConnectionManager() from twisted.internet.task import LoopingCall rpc_stats = LoopingCall(self.print_rpc_stats) rpc_stats.start(10) reactor.callWhenRunning(self._on_reactor_start) # Initialize gdk threading gtk.gdk.threads_enter() reactor.run() self.shutdown() gtk.gdk.threads_leave()
def __init__(self, master=None): self.master = master Frame.__init__(self, master, relief=SUNKEN, bd=2) self.gcode = [] self.slicing = False self.printing = False self.connected = False self.monitorTemp = False self.paused = False self.sdpresent = False self.sdlisting = False self.sdchecking = False self.sdprinting = False self.sdpaused = False self.sduploading = False self.sdbytes = 0 self.sdmaxbytes = 0 self.insidelisting = False self.readingFirmware = False self.sdfiles = [] self.bedtemp = float(0) self.bedtarget = float(0) self.exttemp = float(0) self.exttarget = float(0) self.acceleration = 0 self.m114count = 0 self.speedcount = 0 self.location = [0, 0, 0, 0] self.pausePoint = [0, 0, 0, 0] self.percent = 0.0 self.ets = "??" self.gcodeInfo = None self.GCodeFile = None self.StlFile = None self.Profile = None self.printStartLine = 0 self.startTime = 0 self.endTime = 0 self.elapsedTime = 0 self.FanSpeed = 0 self.FeedMultiply = 100 self.ExtrudeMultiply = 100 self.timingReport = None self.filamentReport = None self.measurementsReport = None self.macroButtons = None self.rpt1re = re.compile(" *T:([0-9\.]+) *E:[0-9\.]+ *B:([0-9\.]+)") self.rpt2re = re.compile(" *T:([0-9\.]+) *E:[0-9\.]+ *W:.*") self.locrptre = re.compile("^X:([0-9\.\-]+)Y:([0-9\.\-]+)Z:([0-9\.\-]+)E:([0-9\.\-]+) *Count") self.speedrptre = re.compile("Fan speed:([0-9]+) Feed Multiply:([0-9]+) Extrude Multiply:([0-9]+)") self.sdre = re.compile("SD printing byte *([0-9]+) *\/ *([0-9]+)") self.printer = printcore() self.settings = Settings() self.settings.cmdFolder = cmd_folder self.logger = Logger(self) if self.settings.speedcommand is not None: allow_while_printing.append(self.settings.speedcommand) self.acceleration = self.settings.acceleration self.dataLoggers = {} for d in DLLIST: self.dataLoggers[d] = DataLogger(self, d) self.skeinforge = Skeinforge(self.settings) self.slic3r = Slic3r(self.settings) self.httpServer = RepRapServer(self, self.printer, self.settings, self.logger, self.settings.port) self.menubar = Menu(self) self.filemenu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="File", menu=self.filemenu) self.filemenu.add_command(label="Slice", command=self.openSTLFile) self.filemenu.add_command(label="Load GCode", command=self.openGCodeFile) self.slicemenuindex = self.filemenu.index("Slice") self.loadgcodemenuindex = self.filemenu.index("Load GCode") self.filemenu.add_separator() self.filemenu.add_command(label="Exit", command=self.quitApp) self.editmenu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="Edit", menu=self.editmenu) self.editmenu.add_command(label="Settings", command=self.editSettings) self.editmenu.add_command(label="Firmware Settings", command=self.FirmwareSettings) self.editmenu.add_separator() self.editmenu.add_command(label=GCODE_MENU_TEXT, command=self.doGEdit, state=DISABLED) self.slicermenu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="Slicer", menu=self.slicermenu) self.rbSlicer = StringVar() self.slicermenu.add_radiobutton( label="Skeinforge", command=self.selSlicer, value=SKEINFORGE, variable=self.rbSlicer ) self.slicermenu.add_command(label="Settings", command=self.skeinforgeSettings) self.slicermenu.add_command(label="Choose Profile", command=self.chooseSFProfile) self.SFprofileindex = self.slicermenu.index("Choose Profile") self.setSFProfileMenuText() self.slicermenu.add_command(label="Alterations", command=self.doEditAlterations) self.slicermenu.add_separator() self.slicermenu.add_radiobutton(label="Slic3r", command=self.selSlicer, value=SLIC3R, variable=self.rbSlicer) self.slicermenu.add_command(label="Settings", command=self.slic3rSettings) self.slicermenu.add_command(label="Choose Profile", command=self.chooseS3Profile) self.S3profileindex = self.slicermenu.index("Choose Profile") self.setS3ProfileMenuText() self.rbSlicer.set(self.settings.slicer) self.macromenu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="Macros", menu=self.macromenu) self.macromenu.add_command(label="New", command=self.doNewMacro) self.macromenu.add_command(label="Edit", command=self.doEditMacro) self.macromenu.add_command(label="Delete", command=self.doDelMacro) self.macromenu.add_separator() self.cbShowMacroButtons = BooleanVar() self.cbShowMacroButtons.set(self.settings.showmacrobuttons) self.macromenu.add_checkbutton( label="Show Macro Buttons", command=self.doShowButtons, onvalue=True, offvalue=False, variable=self.cbShowMacroButtons, ) self.macromenu.add_separator() self.runmacromenu = Menu(self.macromenu, tearoff=0) self.loadMacros() self.macromenu.add_cascade(label="Run", menu=self.runmacromenu) self.reportmenu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="View", menu=self.reportmenu) self.cbShowPrevious = BooleanVar() self.cbShowPrevious.set(self.settings.showprevious) self.reportmenu.add_checkbutton( label="Show Previous Layer", command=self.toggleShowPrevious, onvalue=True, offvalue=False, variable=self.cbShowPrevious, ) self.cbShowMoves = BooleanVar() self.cbShowMoves.set(self.settings.showmoves) self.reportmenu.add_checkbutton( label="Show Non-extrusion Moves", command=self.toggleShowMoves, onvalue=True, offvalue=False, variable=self.cbShowMoves, ) self.reportmenu.add_separator() self.reportmenu.add_command(label="Show Hours of Usage", command=self.doDataLogReport) self.reportmenu.add_command(label="Reset Hours of Usage", command=self.doDataLogReset) self.reportmenu.add_separator() self.reportmenu.add_command(label="Layer by Layer Timing", command=self.doTimingReport) self.reportmenu.add_command(label="Layer by Layer Filament Usage", command=self.doFilamentReport) self.reportmenu.add_command(label="GCode Measurements", command=self.doMeasurementsReport) self.toolsmenu = Menu(self.menubar, tearoff=0) n = 0 if self.settings.platercmd is not None: n += 1 self.toolsmenu.add_command(label="Plater", command=self.doPlater) if self.settings.gcodeviewcmd is not None: n += 1 self.toolsmenu.add_command(label="GCode Viewer", command=self.doGCodeView) if self.settings.stlviewcmd is not None: n += 1 self.toolsmenu.add_command(label="STL Viewer", command=self.doSTLView) if self.settings.openscadcmd is not None: n += 1 self.toolsmenu.add_command(label="OpenSCAD", command=self.doOpenSCAD) if n > 0: self.menubar.add_cascade(label="Tools", menu=self.toolsmenu) try: self.master.config(menu=self.menubar) except AttributeError: self.master.tk.call(master, "config", "-menu", self.menubar) self.toolbar = ToolBar(self, self.printer, self.settings, self.logger) self.toolbar.grid(row=1, column=1, columnspan=4, sticky=W) self.ctl = MoveControl(self, self.printer, self.settings, self.logger) self.ctl.grid(row=2, column=1, rowspan=3, sticky=N) self.extr = Extruder(self, self.printer, self.settings, self.logger) self.extr.grid(row=2, column=2, rowspan=1, sticky=N + E + W) self.temps = Temperatures(self, self.printer, self.settings, self.logger) self.temps.grid(row=3, column=2, rowspan=2, sticky=N + E + W) self.gc = GcFrame(self, None, [], self.settings, self.logger) self.gc.grid(row=2, column=3, rowspan=3, sticky=N) self.statline = Status(self, self.printer, self.settings, self.logger) self.statline.grid(row=5, column=1, columnspan=4, sticky=E + W) self.logger.grid(row=2, column=4, rowspan=2, sticky=N + E + W) self.sendgcode = SendGCode(self, self.printer, self.settings, self.logger) self.sendgcode.grid(row=4, column=4, sticky=N + E + W) self.printer.errorcb = self.errorcb self.printer.sendcb = self.sendcb self.printer.recvcb = self.recvcb self.sd = SDCard(self, self.printer, self.settings, self.logger) self.firmware = FirmwareParms(self, self.printer, self.settings, self.logger) self.bind(MWM_FIRMWARECOMPLETE, self.firmwareReportComplete) self.bind(MWM_SLICERCOMPLETE, self.sliceComplete) self.bind(MWM_GCODELOADCOMPLETE, self.loadgcodeFinished) self.bind(MWM_GEDITMEASURECOMPLETE, self.geditMeasureComplete) self.bind(MWM_REQUESTPOSITIONREPORT, self.requestPosition) self.doShowButtons()
class CalendarZone(Frame): """ Classe contenant la barre d'outil et la zone d'affichage. """ def __init__(self, master=None, periodeManager=None, **kwargs): """ Constructeur de CalendarZone. @param master: master du tkinter.Frame() que cet objet est. @param periodeManager: le PeriodeManager pour la barre d'outil des périodes, connue dans cet objet. @param **kwargs: Les options d'affichages pour le tkinter.Frame() que cet objet est. """ Frame.__init__(self, master, **kwargs) # Note : self.master est référence vers l'Application. self.__isBarrePeriode = False # Barre du haut self.outilBar = ToolBar(self) # frame avec tous les boutons outils self.outilBar.pack(side=TOP, fill=X, expand=NO) # Barre du haut pour les périodes self.outilBarPeriode = PeriodToolBar( self, periodeManager) # frame avec tous les boutons outils # Zone calendrier self.zoneDynamicCalendarFrame = ZoneAffichage( self ) # frame avec la zone d'affichage des paramètre et la zone avec les données self.zoneDynamicCalendarFrame.pack(side=BOTTOM, fill=BOTH, expand=YES) "" # Pour le repli de code je rappelle ############# # Getters : # ############# "" def getApplication(self): """ Getter pour l'application. @return l'application. """ return self.master def getBarreOutilActive(self): """ Getter pour la barre d'outil des périodes active. @return la barre d'outil des périodes active. """ if self.__isBarrePeriode: return self.outilBarPeriode else: return self.outilBar def getDonneeCalendrier(self): """ Getter pour le DonneeCalendrier. @return le DonneeCalendrier. """ return self.getZoneAffichage().getDonneeCalendrier() def getFirstAndLast(self): """ Getter parmi les tâches sélectionnés Permet de déterminer la tache qui fini le plus tôt et la tache qui commence le plus tard @return first : (Task) tache qui fini le plus tôt @return last : (Task) tache qui commence le plus tard """ # Manière la plus simple avec min() et max() comme ceci, le critère se faisant suivant la lambda : first = min(self.getDonneeCalendrier().getSelectedSchedulable(), key=lambda t: t.getFin()) last = max(self.getDonneeCalendrier().getSelectedSchedulable(), key=lambda t: t.getDebut()) return first, last def getPanneauActif(self): """ Getter pour le panneau actif dans DonneeCalendrier. @return le panneau actif dans DonneeCalendrier. """ return self.getZoneAffichage().getPanneauActif() def getParametreAffichage(self): """ Getter pour les ParametreAffichage. @return le ParametreAffichage. """ return self.getZoneAffichage().getParametreAffichage() def getPeriodeActive(self): """ Getter de la periode active. @return la période active. """ return self.getDonneeCalendrier().getPeriodeActive() def getZoneAffichage(self): """ Getter pour la ZoneAffichage. @return la ZoneAffichage. """ return self.zoneDynamicCalendarFrame "" ############# # Setters : # ############# "" def setBarreOutilPeriode(self, value): """ Permet de switcher entre la barre d'outil normale et la barre d'outil des périodes. @param value: True si c'est la barre d'outil des périodes, False sinon. """ self.__isBarrePeriode = value if value: self.outilBarPeriode.pack(side=TOP, fill=X, expand=NO) self.outilBar.pack_forget() else: self.outilBarPeriode.pack_forget() self.outilBar.pack(side=TOP, fill=X, expand=NO) "" ##################################################### # Pour la barre d'outil des calendriers standards : # ##################################################### "" def afficherMasquerJour(self): """ Permet d'afficher ou masquer un jour... """ self.getBarreOutilActive().changeAfficherMasquerMode( askAfficherMasquer(self.getApplication().getPeriodManager())) # On se met à jour self.getDonneeCalendrier().updateAffichage() def ajouterHeure(self): """ Méthode exécutée par la barre d'outil des périodes quand l'utilisateur appuie sur le bouton pour rajouter des heures. """ min = self.getDonneeCalendrier().getHeureDebut() max = datetime.timedelta(hours=23) - datetime.timedelta( hours=self.getDonneeCalendrier().getHeureFin().hour) max2 = self.getDonneeCalendrier().getHeureFin() nbHeure = max2.hour - min.hour nb, pos = askAjouterHeure(min, max, nbHeure) self.gestionHeure(nb, pos) self.getDonneeCalendrier().updateAffichage(force=True) def ajouterJour(self): """ Méthode exécutée par la barre d'outil des périodes quand l'utilisateur appuie sur le bouton pour rajouter des jours. """ totalJour = self.getDonneeCalendrier().getLongueurPeriode().days - 1 nb, pos = askAjouterJour(totalJour) self.gestionJour(nb, pos) def avancementMannuel(self): """ Permet de valider les tâches sélectionnées. """ schedulables = [] for schedulable in self.getPeriodeActive().getInstanciatedSchedulables( ): # On peut prendre Instanciated car on ne valide pas les taches conteneurs if schedulable.isSelected(): schedulables.extend(schedulable.setDone(True)) self.getApplication().getTaskEditor().redessiner() if schedulables != []: UndoRedoTasksValidations(schedulables) def avancementNormal(self): """ Valide TOUTES les tâches qui sont avant maintenant. """ schedulables = [] now = datetime.datetime.now() for schedulable in self.getDonneeCalendrier().getPeriodeActive( ).getInstanciatedSchedulables(): if schedulable.getFin() <= now: schedulables.extend(schedulable.setDone(True)) #schedulable.updateStatut() fait dans la methode setDone() self.getApplication().getTaskEditor().redessiner() if schedulables != []: UndoRedoTasksValidations(schedulables) def avancementJourFini(self): """ Valide toutes les tâches qui sont terminées aujourd'hui. """ schedulables = [] now = datetime.date.today() for tache in self.getDonneeCalendrier().getPeriodeActive( ).getInstanciatedSchedulables(): if tache.getFin().date() == now: schedulables.extend(tache.setDone(True)) self.getApplication().getTaskEditor().redessiner() if schedulables != []: UndoRedoTasksValidations(schedulables) def decalerHeure(self): """ Permet de décaler les tâches sélectionnées par l'utilisateur, d'un certain nombre d'heures, suivant ce que l'utilisateur souhaite. Un message lui sera demandé si jamais cela dépasse de la journée. """ # Si la liste est vide on évite la question if len(list(self.getDonneeCalendrier().getSelectedSchedulable())) == 0: return # On détermine le nombre d'heure min et max first, last = self.getFirstAndLast() periode = self.getPeriodeActive() heureDebut = self.getDonneeCalendrier().getHeureDebut() heureFin = self.getDonneeCalendrier().getHeureFin() lastDiffJour = ( last.getDebut().date() - periode.getDebut()).days # .days pour int-ifier le tout firstDiffJour = (periode.getFin() - first.getFin().date()).days heureRetirerMax = last.getDebut().hour + lastDiffJour * 24 heureAjoutMax = heureFin.hour - first.getFin( ).hour + 1 + firstDiffJour * 24 nb, pos, param = askDecalHeure(heureRetirerMax, heureAjoutMax, heureDebut, heureFin, last.getDebut().hour - heureDebut.hour, heureFin.hour - first.getFin().hour + 1) if nb is None or pos is None or param is None or nb == 0: return # Ajustement des heures horsChamp = False # map des undo-redo-s : mapIDBeginTaskBefore = {} mapIDBeginTaskAfter = {} for tache in self.getDonneeCalendrier().getSelectedSchedulable(): if isinstance(tache, Task): # map d'avant le déplacement : mapIDBeginTaskBefore[tache.getUniqueID()] = tache.getDebut() # Si tout va bien if (tache.getDebut()+datetime.timedelta(hours=nb)).date() == (tache.getFin()+datetime.timedelta(hours=nb)).date()\ and heureDebut <= (tache.getDebut()+datetime.timedelta(hours=nb)).time()\ and heureFin >= (tache.getFin()+datetime.timedelta(hours=nb)).time(): tache.setDebut(tache.getDebut() + datetime.timedelta(hours=nb)) # Si on dépasse, on cadre selon les limites et mode bloquer elif param == "bloquer": # Si on retire des heures au début if nb < 0: # On peut pas mettre un tache.setDebut( datetime.datetime.combine(tache.getDebut().date(), heureDebut)) # Si on ajoute pour mettre à la fin else: heureFin = heureFin # Time time = datetime.datetime.combine( tache.getFin().date(), heureFin) - tache.getDuree( ) # datetime - timedelta tache.setDebut(time) # Si on dépasse et que l'on ne bloque pas elif param == "duree": tache.setDebut(tache.getDebut() + datetime.timedelta(hours=nb)) horsChamp = True # Si au final il y a des tâches hors champs on demande si on affiche les heures pour voir le.s tache.s if horsChamp and askChangerHeure(): timeAvant = heureDebut timeApres = heureFin tacheAvant = None tacheApres = None for tache in self.getDonneeCalendrier().getSelectedTask(): # Si le début est avant la fin (hors date) ET qu'il est avant le referent if tache.getDebut().time() < tache.getFin().time( ) and tache.getDebut().time() < timeAvant: tacheAvant = tache timeAvant = tache.getDebut().time() # Si la fin est avant le début (hors date) ET qu'il est avant le referent elif tache.getDebut().time() > tache.getFin().time( ) and tache.getFin().time() < timeAvant: tacheAvant = tache timeAvant = tache.getFin().time() # Si la fin est après le début (hors date) ET qu'il est après le referent if tache.getDebut().time() < tache.getFin().time( ) and tache.getFin().time() > timeApres: tacheApres = tache timeApres = tache.getFin().time() # Si le début est après la fin (hors date) ET qu'il est après le referent elif tache.getDebut().time() > tache.getFin().time( ) and tache.getDebut().time() > timeApres: tacheApres = tache timeApres = tache.getDebut().time() # Maintenant on applique les changements if tacheAvant is not None: addAvant = heureDebut.hour - timeAvant.hour self.gestionHeure(addAvant, "Avant") if tacheApres is not None: addApres = timeApres.hour - heureFin.hour self.gestionHeure(addApres, "Apres") # map d'après le déplacement : mapIDBeginTaskAfter[tache.getUniqueID()] = tache.getDebut() # Undo-redo : UndoRedoDecaler(self.getPeriodeActive(), mapIDBeginTaskBefore, mapIDBeginTaskAfter) # Update affichage : self.getDonneeCalendrier().updateAffichage(True) def decalerJour(self): """ Permet de décaler les tâches sélectionnées par l'utilisateur, d'un certain nombre de jours, suivant ce que l'utilisateur souhaite. Un message lui sera demandé si jamais cela dépasse de la période. """ # Si la liste est vide on évite la question if len(list(self.getDonneeCalendrier().getSelectedSchedulable())) == 0: return # On détermine le nombre de jour min et max first, last = self.getFirstAndLast() debut = self.getPeriodeActive().getDebut() # Date de début fin = self.getPeriodeActive().getFin() # Date de fin # Les variables ci-dessous calculent le nombre max de jours pour le décalage # si il y a un bloquage dans un sens ou dans l'autre. Cependant, quand on # bloque, on peut bouger jusqu'à ce que la fin de la tâche la plus tôt # atteigne la fin de la période ; ou que le début de la tâche la plus tard # atteigne le début de la période. jourRetireBloque = (last.getDebut().date() - debut).days jourAjoutBloque = (fin - first.getFin().date()).days # Appel du dialogue à l'utilisateur : nb, pos, param = askDecalJour(debut, fin, jourRetireBloque, jourAjoutBloque) if nb is None or pos is None or param is None or nb == 0: return # Ajustement des jours horsChamp = False duree = datetime.timedelta(days=nb) # map des undo-redo-s : mapIDBeginTaskBefore = {} mapIDBeginTaskAfter = {} for tache in self.getDonneeCalendrier().getSelectedSchedulable(): if isinstance(tache, Task): # TODO avec groupe. # map d'avant le déplacement : mapIDBeginTaskBefore[tache.getUniqueID()] = tache.getDebut() # Si tout va bien if debut <= (tache.getDebut()+duree).date()\ and fin >= (tache.getFin()+duree).date(): tache.setDebut(tache.getDebut() + duree) # Si on dépasse, on cadre selon les limites et mode bloquer elif param == "bloquer": # Si on retire des heures au début if nb < 0: # On peut pas mettre un tache.setDebut( datetime.datetime.combine(debut, tache.getDebut().time())) # Si on ajoute pour mettre à la fin else: time = datetime.datetime.combine( fin, tache.getFin().time()) - tache.getDuree( ) # datetime - timedelta tache.setDebut(time) # Si on dépasse et que l'on ne bloque pas elif param == "duree": tache.setDebut(tache.getDebut() + datetime.timedelta(days=nb)) horsChamp = True # Si au final il y a des tâches hors champs on demande si on affiche les heures pour voir le.s tache.s if horsChamp: horsChamp = False choix, periode = askComplicationjour( tache, self.getApplication().getPeriodManager()) # On annule les changements if choix is None: tache.setDebut(tache.getDebut() - datetime.timedelta(days=nb)) continue # On agrandit la période elif choix == "agrandir": if tache.getDebut().date() < debut: addAvant = (debut - tache.getDebut().date()).days self.gestionJour(addAvant, "Avant") else: addApres = (last.getFin().date() - fin).days self.gestionJour(addApres, "Apres") elif choix == "supprimer": # TODO supprimer la tache pass elif choix == "independante": # TODO rendre la tache indépendante pass elif choix == "changer": tache.setPeriode(periode) # map d'après le déplacement : mapIDBeginTaskAfter[tache.getUniqueID()] = tache.getDebut() # Undo-redo : UndoRedoDecaler(self.getPeriodeActive(), mapIDBeginTaskBefore, mapIDBeginTaskAfter) self.getDonneeCalendrier().updateAffichage(True) def degrouper(self): """ Permet de dégrouper un groupe. """ # Obtention de la période et des schedulables instanciés sélectionnés : periode = self.getDonneeCalendrier().getPeriodeActive() schedulables = set(self.getDonneeCalendrier().getSelectedSchedulable()) schedPerGroup = {} # dictionnaire des tâches à dégrouper, par groupe. # Calcul des tâches à enlever par groupes : for schedulable in set(schedulables): if isinstance(schedulable, Groupe): if schedulable not in schedPerGroup: schedPerGroup[schedulable] = set() else: # Task groupe = schedulable.getGroupe() if groupe is None: showerror( "Erreur de sélection", "Vous ne pouvez pas dégrouper des tâches qui ne sont pas dans un groupe." ) return if groupe not in schedPerGroup: schedPerGroup[groupe] = set() schedPerGroup[groupe].add(schedulable) # Pour chaque groupes sélectionnés : for groupe in schedPerGroup: # Ré-ajout au calendrier des tâches qui étaient dans le groupe : for t in schedPerGroup[groupe] if schedPerGroup[ groupe] else groupe.getListTasks(): groupe.removeTask(t, testDelete=True) # Demande de suppression du groupe, s'il n'y a plus qu'une tâche : if len(groupe.getListTasks()) == 1: if askyesnowarning( title="Édition du groupe", message= 'Le groupe "%s" ne possède plus qu\'une tache :\n\t- %s\nVoulez-vous supprimer le groupe ?' % (groupe.getNom(), list( groupe.getListTasks())[0].getNom())): groupe.removeTask(list(groupe.getListTasks())[0], testDelete=True) # Le groupe va s'auto-delete avec le testDelete. # Mise à jour de l'affichage qu'à la fin : self.getApplication().getTaskEditor().redessiner() self.getDonneeCalendrier().updateAffichage( True) # True = on force la total, car suppression d'objet. def deplacerIntervertir(self): """ Permet d'intervertir 2 jours exactement. Ce sont ceux sélectionnés par l'utilisateur. """ self.getDonneeCalendrier().intervertir() def gestionHeure(self, nombreHeure, position): """ Fonction qui s'occupe de rajouter des heures visibles. En dehors de la fonction ajouterHeure lié au bouton car on pourrait avoir à ajouter des heures autrement que par le bouton @param nombreHeure : int relatif, permet d'ajouter ou retirer des heures @param position : string "Avant" / "Apres" pour savoir ou appliquer les changements """ if nombreHeure is not None and position is not None: if position == "Avant": timeHeure = datetime.time( self.getDonneeCalendrier().getHeureDebut().hour - nombreHeure) self.getDonneeCalendrier().setHeureDebut(timeHeure) elif position == "Apres": timeHeure = datetime.time( self.getDonneeCalendrier().getHeureFin().hour + nombreHeure, self.getDonneeCalendrier().getHeureFin().minute) self.getDonneeCalendrier().setHeureFin(timeHeure) def gestionJour(self, nombreDeJour, position): """ Fonction qui s'occupe d'ajouter ou de supprimer des jours En dehors de la fonction ajouterJour lié au bouton car on pourrait avoir à ajouter des jours autrement que par le bouton @param nombreDeJour : int relatif, permet d'ajouter ou retirer des jours @param position : string "Avant" / "Apres" pour savoir ou appliquer les changements """ if nombreDeJour is not None and position is not None: periode = self.getPeriodeActive() if position == "Avant": self.getDonneeCalendrier().setPeriodeActiveDebut( periode.getDebut() - datetime.timedelta(days=nombreDeJour)) elif position == "Apres": self.getDonneeCalendrier().setPeriodeActiveFin( periode.getFin() + datetime.timedelta(days=nombreDeJour)) # Mise à jour du Combobox self.getParametreAffichage().updateComboboxNbJour() def grouper(self): """ Permet de grouper les tâches. """ periode = self.getPeriodeActive() schedulables = list( self.getDonneeCalendrier().getSelectedSchedulable()) # Petite vérification : if len(schedulables) < 2: return showerror( "Sélection invalide", "Vous devez avoir au moins 2 éléments sélectionner pour pouvoir les grouper." ) groupe = None taches = [] for obj in schedulables: if isinstance(obj, Groupe): if groupe is None: groupe = obj elif groupe != obj: return showerror( "Sélection invalide", "Vous ne pouvez pas grouper des tâches dans plusieurs groupes." ) elif not isinstance(obj, Task): return showerror("Sélection invalide", "Vous ne pouvez grouper que des tâches.") else: taches.append(obj) # Création du groupe : ajout = True if groupe: ajout = False groupe = groupe or askGroup(periode) if groupe is None: return for t in taches: groupe.addTask(t) if ajout: periode.addPrimitiveSchedulable(groupe) self.getApplication().getTaskEditor().redessiner() groupe.instantiate() self.getDonneeCalendrier().updateAffichage() def selectionnerJour(self): """ Méthode pour demander un jour à sélectionner à l'utilisateur, pour le sélectionner ensuite où qu'il soit. """ jour = askdate() if jour is not None: donneeCalendrier = self.getDonneeCalendrier() if jour >= donneeCalendrier.getDebutPeriode( ) and jour <= donneeCalendrier.getFinPeriode(): donneeCalendrier.deselectJours() donneeCalendrier.selectJour(jour) dureeJours = donneeCalendrier.getDureeJour() if donneeCalendrier.getJourDebut() > jour: donneeCalendrier.setJourDebut(jour) donneeCalendrier.setDureeJour(dureeJours) donneeCalendrier.updateAffichage() elif donneeCalendrier.getJourFin() < jour: donneeCalendrier.setJourFin(jour) donneeCalendrier.setJourDebut(jour - dureeJours + datetime.timedelta(days=1)) donneeCalendrier.updateAffichage() else: # TODO : mettre dans le dialogue lui-même showerror( "Date invalide", "La date que vous avez choisie est en dehors des limites de la période." ) "" ######################################## # Pour la barre d'outil des périodes : # ######################################## "" def voirTacheDansVue(self): """ Permet de voir une tâche dans une autre vue, via demande à l'utilisateur dans une boîte de dialogue usuelle. TODO """ pass def supprimerTache(self): """ Permet de supprimer une tâche indépendante. Fera-t-on des groupes indépendants ? Si oui -> renommer en supprimerSchedulable()... TODO """ pass
def interactive(self): """ interactive shell""" self.op = ShellOperations() self.bindings = KeyBindings() cat_Storage = [] line = "" self.toolBar = ToolBar() input_History = InMemoryHistory() operators = ["+", "-", "*", '**', '<', ">"] returnShellMethods = {"tod": self.op.do_tod()} listofprintMethods = [ "meow", "help", "bll", "h", "cur", "bdir", "bl", "sh", 'wc', 'get', 'cwl', 'cdir', 'man' ] linux_Commands = WordCompleter(listofprintMethods) while (True): #excute while True enter_commands = prompt( ">>", history=input_History, key_bindings_registry=self.bindings.register, completer=linux_Commands, mouse_support=True, get_title=self.get_title, get_bottom_toolbar_tokens=self.toolBar. get_bottom_toolbar_tokens, style=self.toolBar.toolBarStyle) store = enter_commands store = store.split(" ") if (enter_commands in returnShellMethods.keys()): print(returnShellMethods[enter_commands]) if (enter_commands not in returnShellMethods.keys()) and ( enter_commands not in listofprintMethods) and (store[0] not in listofprintMethods): try: exec(enter_commands) except Exception as Err: print(Err) if (enter_commands == 'cl'): self.op.do_cl() if ( enter_commands == "exit" ): #if enter_commands equal to exit then exit interactive shell os.system("exit") if (len(enter_commands) > 1) and (enter_commands[1] in operators): try: print(eval(enter_commands)) except Exception as err: print(err) if (enter_commands in listofprintMethods) and (enter_commands == "bll"): self.op.do_bll() if (enter_commands == "h") and (enter_commands in listofprintMethods): self.op.do_h(line) if (enter_commands == "cur") and (enter_commands in listofprintMethods): self.op.do_cur(line) if (enter_commands == "bdir") and (enter_commands in listofprintMethods): self.op.do_bdir(line) if (enter_commands == 'bl') and (enter_commands in listofprintMethods): self.op.do_bl(line) if (store[0] == "sh") and (store[0] in listofprintMethods): try: self.op.do_show(store[1]) except Exception as err: self.op.do_show(line) if (store[0] == "wc") and (store[0] in listofprintMethods): try: self.op.do_cw(store[1]) except Exception as err: self.op.do_cw(line) if (store[0] == 'get') and (store[0] in listofprintMethods): try: self.op.do_get(store[1]) except Exception as err: self.op.do_get(line) if (store[0] == "cwl") and (store[0] in listofprintMethods): try: self.op.do_cwl(store[1]) except Exception as err: self.op.do_cwl(line) if (store[0] == "cdir") and (store[0] in listofprintMethods): try: self.op.do_cdir(store[1]) except Exception as err: self.op.do_cdir(line) if (store[0] == "help") and (store[0] in listofprintMethods): try: self.op.do_help(store[1]) except Exception as err: self.op.do_help(line) if (store[0] == "meow") and (store[0] in listofprintMethods): if (len(store) == 1): self.op.do_cat(line) if (len(store) == 2): if (do_cat_return[0] in dir()): for cat_evaluation in eval(do_cat_return[0]): print(cat_evaluation) if (store[0] == "meow") and (store[0] in listofprintMethods) and (len(store) == 3): do_cat_return = self.op.do_cat(store) exec(str(do_cat_return))
class GeoLogic(Gtk.Window): def __init__(self): super(GeoLogic, self).__init__() self.imported_tools = load_tools("macros.gl") self.env = GraphicalEnv(self.imported_tools) self.vis = self.env.vis self.general_tools = GToolDict(self.imported_tools.tool_dict) self.keyboard_capture = None menu_items = ( ("Undo", self.undo, "<Control>z"), ("Redo", self.redo, "<Control><Shift>z"), ("Reset", self.restart, "<Control>n"), ("Open...", self.load, "<Control>o"), ("Save", self.save, "<Control>s"), ("Save as...", self.save_as, "<Control><Shift>s"), ("Export SVG...", self.export_svg, "<Control><Shift>e"), ("Quit", self.on_exit, "<Control>q"), ) gtools = ( ComboPoint(), ComboLine(), ComboPerpLine(), ComboCircle(), ComboCircumCircle(), GToolMove(), GToolHide(), GToolLabel(), GToolReason(), ) self.key_to_gtool = dict( (gtool.get_key_shortcut(), gtool) for gtool in gtools) vbox = Gtk.VBox() self.add(vbox) self.toolbar = ToolBar(menu_items, gtools, self.general_tools) vbox.pack_start(self.toolbar, False, False, 0) hpaned = Gtk.HPaned() vbox.add(hpaned) self.step_list = StepList(self.env) hpaned.pack1(self.step_list, False, True) self.viewport = Viewport(self.env, self) self.viewport.set_tool(ComboPoint()) hpaned.pack2(self.viewport.darea, True, False) hpaned.set_position(250) self.viewport.click_hook = self.toolbar.entry.unselect self.toolbar.set_entry_unselect(self.viewport.darea.grab_focus) self.toolbar.change_tool_hook = self.viewport.set_tool self.add_accel_group(self.toolbar.accelerators) def update_progress_bar(done, size): if size == 0: self.progress_bar.set_fraction(0) else: self.progress_bar.set_fraction(done / size) return False def update_progress_bar_idle(done, size): GLib.idle_add(update_progress_bar, done, size) proof_checker.paralelize(progress_hook=update_progress_bar_idle) self.progress_bar = Gtk.ProgressBar(show_text=False) vbox.pack_end(self.progress_bar, False, False, 0) self.connect("key-press-event", self.on_key_press) self.connect("key-release-event", self.on_key_release) self.connect("delete-event", self.on_exit) self.resize(1000, 600) self.set_position(Gtk.WindowPosition.CENTER) self.set_events(Gdk.EventMask.KEY_PRESS_MASK | Gdk.EventMask.KEY_RELEASE_MASK) self.show_all() self.update_title(None) # changes the default filename for saving and the title of the window def update_title(self, fname): self.default_fname = fname title = "GeoLogic" if fname is not None: title = "{} -- {}".format(title, fname.split('/')[-1]) self.set_title(title) def reset_view(self): if self.vis.view_changed: self.viewport.gtool.reset() self.viewport.darea.queue_draw() def undo(self): proof_checker.disable() self.env.pop_step() self.reset_view() proof_checker.enable() def redo(self): self.env.redo() self.reset_view() def restart(self): #print("RESTART") self.update_title(None) self.viewport.reset_tool() self.env.set_steps((), ()) self.viewport.reset_zoom() self.reset_view() def load(self): fname = select_file_open(self) self.load_file(fname) def save(self): fname = self.default_fname if fname is None: fname = select_file_save(self) self.save_file(fname) def save_as(self): fname = select_file_save(self) self.save_file(fname) def export_svg(self): fname = select_file_save( self, "Export SVG", folder="pictures", add_filters=add_svg_filters, ) if fname is not None: self.viewport.export_svg(fname) def on_exit(self, *args): print_times() Gtk.main_quit() def load_file(self, fname): self.viewport.reset_tool() if fname is None: return self.update_title(fname) parser = Parser(self.imported_tools.tool_dict) parser.parse_file(fname, axioms=True) loaded_tool = parser.tool_dict['_', ()] steps = loaded_tool.assumptions names = [ loaded_tool.var_to_name_proof[x] for x in range(len(loaded_tool.var_to_name_proof)) ] if loaded_tool.implications: goals, proof = loaded_tool.implications, loaded_tool.proof else: goals, proof = None, None self.env.set_steps(steps, names=names, goals=goals, proof=proof) # hide objects visible = set(loaded_tool.result) # old format if visible: for gi in range(len(self.vis.gi_to_hidden)): self.vis.gi_to_hidden[gi] = gi not in visible for gi, name in enumerate(names): # new format if ("hide__{}".format(name), ()) in parser.tool_dict: self.vis.gi_to_hidden[gi] = True # set labels for gi, name in enumerate(names): # new format label_pos_tool = parser.tool_dict.get( ("label__{}".format(name), ()), None) if label_pos_tool is not None: self.vis.gi_label_show[gi] = True logic = LogicalCore(basic_tools=self.imported_tools) pos_l = label_pos_tool.run((), (), logic, 0) pos_n = [logic.num_model[x] for x in pos_l] t = self.vis.gi_to_type(gi) if t == Point: point, = pos_n position = point.a print(position) elif t == Line: position = tuple(d.x for d in pos_n) elif t == Circle: ang, offset = pos_n position = ang.data * 2, offset.x else: print( "Warning: save label: unexpected type {} of {}".format( t, name)) continue self.vis.gi_label_position[gi] = position self.vis.refresh() # viewport zoom and position view_data_tool = parser.tool_dict.get(('view__data', ()), None) if view_data_tool is None: self.viewport.set_zoom((375, 277), 1) else: logic = LogicalCore(basic_tools=self.imported_tools) anchor_l, zoom_l = view_data_tool.run((), (), logic, 0) anchor = logic.num_model[anchor_l].a zoom = logic.num_model[zoom_l].x self.viewport.set_zoom(anchor, zoom) self.reset_view() def save_file(self, fname): if fname is None: return print("saving to '{}'".format(fname)) self.update_title(fname) with open(fname, 'w') as f: #visible = [ # "{}:{}".format( # self.env.gi_to_name[gi], # type_to_c[self.vis.gi_to_type(gi)] # ) # for gi,hidden in enumerate(self.vis.gi_to_hidden) # if not hidden #] #f.write('_ -> {}\n'.format(' '.join(sorted(visible)))) f.write('_ ->\n') def write_step(step): tokens = [self.env.gi_to_name[x] for x in step.local_outputs] tokens.append('<-') tokens.append(step.tool.name) tokens.extend(map(str, step.hyper_params)) tokens.extend(self.env.gi_to_name[x] for x in step.local_args) f.write(' ' + ' '.join(tokens) + '\n') if self.env.goals is None: for step in self.env.steps: write_step(step) else: for step in self.env.steps[:self.env.min_steps]: write_step(step) f.write(' THEN\n') for step in self.env.goals: write_step(step) f.write(' PROOF\n') for step in self.env.steps[self.env.min_steps:]: write_step(step) # hidden objects and labels f.write("\n") for gi, (name, hidden, label_show, label_pos) in enumerate( zip(self.env.gi_to_name, self.vis.gi_to_hidden, self.vis.gi_label_show, self.vis.gi_label_position)): if hidden: f.write("hide__{} ->\n".format(name)) if label_show: t = self.vis.gi_to_type(gi) if t == Point: label_attrs = [('pos', 'P', 'free_point', tuple(map(float, label_pos)))] elif t == Line: pos, offset = label_pos label_attrs = [ ('pos', 'D', 'custom_ratio', (float(pos), 0.)), ('offset', 'D', 'custom_ratio', (float(offset), 0.)), ] elif t == Circle: direction, offset = label_pos label_attrs = [ ('direction', 'A', 'custom_angle', (float(direction / 2), )), ('offset', 'D', 'custom_ratio', (float(offset), 0.)), ] else: print("Warning: save label: unexpected type {} of {}". format(t, name)) continue label_attr_names = [ "{}:{}".format(attr_name, t) for attr_name, t, _, _ in label_attrs ] f.write("label__{} -> {}\n".format( name, ' '.join(label_attr_names))) for attr_name, _, attr_constructor, attr_values in label_attrs: f.write(" {} <- {} {}\n".format( attr_name, attr_constructor, ' '.join(map(str, attr_values)))) # writing current zoom and position f.write("\n") f.write("view__data -> anchor:P zoom:D\n") f.write(" anchor <- free_point {} {}\n".format( *self.viewport.view_center)) f.write(" zoom <- custom_ratio {} 0.\n".format( self.viewport.scale)) self.reset_view() def on_key_press(self, w, e): if self.keyboard_capture is not None: return self.keyboard_capture(e) keyval = e.keyval keyval_name = Gdk.keyval_name(keyval) modifier = Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK if e.state & modifier: return False if self.toolbar.entry.is_focus(): return if keyval_name == "Return": self.toolbar.entry.select() return True elif keyval_name == "Escape": self.viewport.gtool.reset() if self.viewport.vis.view_changed: self.viewport.darea.queue_draw() return True elif keyval_name in self.key_to_gtool: gtool = self.key_to_gtool[keyval_name] self.toolbar.select_tool_button(gtool) self.reset_view() return True elif keyval_name.startswith("Shift"): self.viewport.update_shift_pressed(True) self.viewport.darea.queue_draw() return False else: #print(keyval_name) return False def on_key_release(self, w, e): keyval_name = Gdk.keyval_name(e.keyval) if keyval_name.startswith("Shift"): self.viewport.update_shift_pressed(False) self.viewport.darea.queue_draw()
def __init__(self): super(GeoLogic, self).__init__() self.imported_tools = load_tools("macros.gl") self.env = GraphicalEnv(self.imported_tools) self.vis = self.env.vis self.general_tools = GToolDict(self.imported_tools.tool_dict) self.keyboard_capture = None menu_items = ( ("Undo", self.undo, "<Control>z"), ("Redo", self.redo, "<Control><Shift>z"), ("Reset", self.restart, "<Control>n"), ("Open...", self.load, "<Control>o"), ("Save", self.save, "<Control>s"), ("Save as...", self.save_as, "<Control><Shift>s"), ("Export SVG...", self.export_svg, "<Control><Shift>e"), ("Quit", self.on_exit, "<Control>q"), ) gtools = ( ComboPoint(), ComboLine(), ComboPerpLine(), ComboCircle(), ComboCircumCircle(), GToolMove(), GToolHide(), GToolLabel(), GToolReason(), ) self.key_to_gtool = dict( (gtool.get_key_shortcut(), gtool) for gtool in gtools) vbox = Gtk.VBox() self.add(vbox) self.toolbar = ToolBar(menu_items, gtools, self.general_tools) vbox.pack_start(self.toolbar, False, False, 0) hpaned = Gtk.HPaned() vbox.add(hpaned) self.step_list = StepList(self.env) hpaned.pack1(self.step_list, False, True) self.viewport = Viewport(self.env, self) self.viewport.set_tool(ComboPoint()) hpaned.pack2(self.viewport.darea, True, False) hpaned.set_position(250) self.viewport.click_hook = self.toolbar.entry.unselect self.toolbar.set_entry_unselect(self.viewport.darea.grab_focus) self.toolbar.change_tool_hook = self.viewport.set_tool self.add_accel_group(self.toolbar.accelerators) def update_progress_bar(done, size): if size == 0: self.progress_bar.set_fraction(0) else: self.progress_bar.set_fraction(done / size) return False def update_progress_bar_idle(done, size): GLib.idle_add(update_progress_bar, done, size) proof_checker.paralelize(progress_hook=update_progress_bar_idle) self.progress_bar = Gtk.ProgressBar(show_text=False) vbox.pack_end(self.progress_bar, False, False, 0) self.connect("key-press-event", self.on_key_press) self.connect("key-release-event", self.on_key_release) self.connect("delete-event", self.on_exit) self.resize(1000, 600) self.set_position(Gtk.WindowPosition.CENTER) self.set_events(Gdk.EventMask.KEY_PRESS_MASK | Gdk.EventMask.KEY_RELEASE_MASK) self.show_all() self.update_title(None)
def create_toolbar(self): toolbar = ToolBar(self, 'Toolbar') self.addToolBar(toolbar)
class CeFrame(Frame): '''\ CeFrame is a frame designed to be a Windows CE compliant window. A CeFrame will track the SIP position and size and will automatically resize itself to always fit the screen. ''' _dispatchers = { "_activate": (MSGEventDispatcher, WM_ACTIVATE), "_settingchanged": (MSGEventDispatcher, WM_SETTINGCHANGE), } _dispatchers.update(Frame._dispatchers) def __init__(self, parent=None, title="PocketPyGui", action=None, menu=None, tab_traversal=True, visible=True, enabled=True, has_sip=True, has_toolbar=False): '''\ Arguments : - parent: the parent window of this CeFrame. - title: the title as appearing in the title bar. - action : a tuple ('Label', callback) . - menu : the title of the right menu as a string if not None, the menu can be filled via the cb_menu attribute after CeFrame initialization. ''' Frame.__init__(self, parent, title, tab_traversal=tab_traversal, visible=visible, enabled=enabled) self.bind(_activate=self._on_activate, _settingchanged=self._on_setting_changed) if has_toolbar: self.toolbar = ToolBar(self) else: self.toolbar = None self.__create_menubar(action, menu, has_sip) def layout(self): if self.toolbar is None: return Frame.layout(self) if self._sizer is not None: rc = RECT() GetClientRect(self._w32_hWnd, byref(rc)) self._sizer.size(rc.left, rc.top, rc.right, rc.bottom - 24 * HIRES_MULT) self.toolbar.move(rc.left, rc.bottom - 26 * HIRES_MULT, rc.right - rc.left, 26 * HIRES_MULT) def __create_menubar(self, action, menu, has_sip): mbi = SHMENUBARINFO() mbi.cbSize = sizeof(SHMENUBARINFO) mbi.hwndParent = self._w32_hWnd mbi.hInstRes = GetModuleHandle(0) slots = [] empty = True has_action = False has_menu = False if (action is None) and (menu is None): mbi.dwFlags = SHCMBF_EMPTYBAR else: empty = False temp_menu = Menu() i = 0 if action is not None: label, cb = action action_item = temp_menu.append(label, callback=cb) #self.action = CommandBarAction(item, 0) else: action_item = temp_menu.append("", enabled=False) if menu is not None: sub_menu = PopupMenu() temp_menu.append_menu(menu, sub_menu) has_menu = True mbi.dwFlags = SHCMBF_HMENU mbi.nToolBarId = temp_menu._hmenu if not has_sip: mbi.dwFlags |= SHCMBF_HIDESIPBUTTON SHCreateMenuBar(byref(mbi)) self._mb_hWnd = mbi.hwndMB if not empty: self.cb_action = CommandBarAction(mbi.hwndMB, 0, action_item) if has_menu: tbbi = TBBUTTONINFO() tbbi.cbSize = sizeof(tbbi) tbbi.dwMask = 0x10 | 0x80000000 SendMessage(mbi.hwndMB, WM_USER + 63, 1, byref(tbbi)) hMenu = tbbi.lParam self.cb_menu = CommandBarMenu(mbi.hwndMB, 0, hMenu) rc = RECT() GetWindowRect(self._w32_hWnd, byref(rc)) rcmb = RECT() GetWindowRect(self._mb_hWnd, byref(rcmb)) rc.bottom -= (rcmb.bottom - rcmb.top) self.move(rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top) def _on_activate(self, event): if not hasattr(self, '_shai'): self._shai = InitSHActivateInfo() SHHandleWMActivate(event.hWnd, event.wParam, event.lParam, byref(self._shai), 0) def _on_setting_changed(self, event): SHHandleWMSettingChange(self._w32_hWnd, event.wParam, event.lParam, byref(self._shai)) def show_sipbutton(self, show=True): if show: SHFullScreen(self._w32_hWnd, SHFS_SHOWSIPBUTTON) else: SHFullScreen(self._w32_hWnd, SHFS_HIDESIPBUTTON) def hide_sipbutton(self): self.show_sipbutton(False)
class MainWindow(object): def __init__(self, *args, **kwargs): self._toolbar = None self._menubar = None self._statusbar = None self._rootwidget = None self._centralwidget = None self._dockareas = { DOCKAREA['left']:None, DOCKAREA['right']:None, DOCKAREA['top']:None, DOCKAREA['bottom']:None } self._toolbarareas = { DOCKAREA['left']:None, DOCKAREA['right']:None, DOCKAREA['top']:None, DOCKAREA['bottom']:None } self.dockareamarker = None def initGui(self, screen_width, screen_height): bar_height = 30 self._dockareas[DOCKAREA['left']] = DockArea("left") self._dockareas[DOCKAREA['right']] = DockArea("right") self._dockareas[DOCKAREA['top']] = DockArea("top") self._dockareas[DOCKAREA['bottom']] = DockArea("bottom") self._toolbarareas[DOCKAREA['left']] = pychan.widgets.VBox(margins=(0,0,0,0)) self._toolbarareas[DOCKAREA['right']] = pychan.widgets.VBox(margins=(0,0,0,0)) self._toolbarareas[DOCKAREA['top']] = pychan.widgets.HBox(margins=(0,0,0,0)) self._toolbarareas[DOCKAREA['bottom']] = pychan.widgets.HBox(margins=(0,0,0,0)) self._statusbar = StatusBar(text=u"", panel_size=bar_height) self._toolbar = ToolBar(title=u"Toolbar", button_style=0) self._menubar = MenuBar(min_size=(screen_width, bar_height), position=(0, 0)) # Set up root widget self._rootwidget = pychan.widgets.VBox(padding=0, vexpand=1, hexpand=1) self._rootwidget.min_size = \ self._rootwidget.max_size = (screen_width, screen_height) self._rootwidget.opaque = False # This is where the map will be displayed self._centralwidget = pychan.widgets.VBox(vexpand=1, hexpand=1) self._centralwidget.opaque = False middle = pychan.widgets.HBox(padding=0, vexpand=1, hexpand=1) middle.opaque = False # Pychan bug? Adding a spacer instead of a container creates # a gap after the right dockarea middle.addChild(self._toolbarareas['left']) middle.addChild(self._dockareas['left']) middle.addChild(self._centralwidget) #middle.addSpacer(pychan.widgets.Spacer()) middle.addChild(self._dockareas['right']) middle.addChild(self._toolbarareas['right']) self._rootwidget.addChild(self._menubar) #self._rootwidget.addChild(self._toolbar) self._rootwidget.addChild(self._toolbarareas['top']) self._rootwidget.addChild(self._dockareas['top']) self._rootwidget.addChild(middle) self._rootwidget.addChild(self._dockareas['bottom']) self._rootwidget.addChild(self._toolbarareas['bottom']) self._rootwidget.addChild(self._statusbar) self._toolbar.setDocked(True) self.dockWidgetTo(self._toolbar, "top") self._rootwidget.show() def getCentralWidget(self): return self._centralwidget def getStatusBar(self): return self._statusbar def getMenuBar(self): return self._menubar def getToolBar(self): return self._toolbar def dockWidgetTo(self, widget, dockarea, x=-1, y=-1): """ docks a B{Panel} widget to the given dock area @note: - ToolBar needs special treatment, given x, y coordinates have no effect on this Panel - x, y are cursor coordinates, without giving them the widgets are added beneath the already existing ones nice feature, but also makes problems on editor startup (e.g. if a user docked 2 widgets left, on startup they are added in a col instead of a grouped tab) @todo: turn x,y documentation into something more useful @type widget: Panel @param widget: a panel widget instance @type dockarea: str @param dockarea: id of the target dock area @type x: int @param x: x coordinate @type y: int @param y: y coordinate """ if isinstance(widget, pychan.widgets.Widget) is False: print "Argument is not a valid widget" return if widget.parent: widgetParent = widget.parent widgetParent.removeChild(widget) widgetParent.adaptLayout() # We must hide the widget before adding it to the dockarea, # or we will get a duplicate copy of the widget in the top left corner # of screen. widget.hide() dockareas = self._dockareas # Panel widgets which provide an implementation for set_orientation() # should check if they need to re-align themselves if hasattr(widget, 'set_orientation'): key = '' if dockarea == DOCKAREA['left'] or dockarea == DOCKAREA['right']: key = 'Vertical' elif dockarea == DOCKAREA['top'] or dockarea == DOCKAREA['bottom']: key = 'Horizontal' widget.set_orientation(key=key) if isinstance(widget, ToolBar): dockareas = self._toolbarareas docked = False if dockarea == DOCKAREA['left']: docked = True dockareas[DOCKAREA['left']].addChild(widget) dockareas[DOCKAREA['left']].adaptLayout() elif dockarea == DOCKAREA['right']: docked = True dockareas[DOCKAREA['right']].addChild(widget) dockareas[DOCKAREA['right']].adaptLayout() elif dockarea == DOCKAREA['top']: docked = True dockareas[DOCKAREA['top']].addChild(widget) dockareas[DOCKAREA['top']].adaptLayout() elif dockarea == DOCKAREA['bottom']: docked = True dockareas[DOCKAREA['bottom']].addChild(widget) dockareas[DOCKAREA['bottom']].adaptLayout() else: print "Invalid dockarea" widget.dockareaname = dockarea widget.setDocked(docked) else: if dockarea == DOCKAREA['left']: dockareas[DOCKAREA['left']].dockChild(widget, x, y) elif dockarea == DOCKAREA['right']: dockareas[DOCKAREA['right']].dockChild(widget, x, y) elif dockarea == DOCKAREA['top']: dockareas[DOCKAREA['top']].dockChild(widget, x, y) elif dockarea == DOCKAREA['bottom']: dockareas[DOCKAREA['bottom']].dockChild(widget, x, y) else: print "Invalid dockarea" def getToolbarAreaAt(self, x, y, mark=False): if self.dockareamarker is None: self.dockareamarker = pychan.widgets.Container() self.dockareamarker.base_color = fifechan.Color(200, 0, 0, 100) if mark is False: self.dockareamarker.hide() # Mouse wasn't over any dockwidgets. See if it is near any edge of the screen instead if x <= self._toolbarareas["left"].getAbsolutePos()[0]+10: if mark: self.dockareamarker.position = self._toolbarareas["left"].getAbsolutePos() self.dockareamarker.size = (10, self._toolbarareas["left"].height) self.dockareamarker.show() return DOCKAREA["left"] elif x >= self._toolbarareas["right"].getAbsolutePos()[0]-10: if mark: self.dockareamarker.position = self._toolbarareas["right"].getAbsolutePos() self.dockareamarker.size = (10, self._toolbarareas["right"].height) self.dockareamarker.x -= 10 self.dockareamarker.show() return DOCKAREA["right"] elif y <= self._toolbarareas["top"].getAbsolutePos()[1]+10: if mark: self.dockareamarker.position = self._toolbarareas["top"].getAbsolutePos() self.dockareamarker.size = (self._toolbarareas["top"].width, 10) self.dockareamarker.show() return DOCKAREA["top"] elif y >= self._toolbarareas["bottom"].getAbsolutePos()[1]-10: if mark: self.dockareamarker.position = self._toolbarareas["bottom"].getAbsolutePos() self.dockareamarker.y -= 10 self.dockareamarker.size = (self._toolbarareas["bottom"].width, 10) self.dockareamarker.show() return DOCKAREA["bottom"] if mark is True: self.dockareamarker.hide() return None def getDockAreaAt(self, x, y, mark=False): """ returns the dock area at the given cursor coordinates (if possible) also used for highlighting the dock area (this method is used on drag mouse events of a B{Panel} widget) @type x: int @param x: cursor x coordinates @type y: int @param y: cursor y coordinates @type mark: bool @param mark: flag to wether show the dock area marker (red area indicator) or not @rtype side: str @return side: dockarea id (e.g. 'right', 'left' ...) """ side = None if self.dockareamarker is None: self.dockareamarker = pychan.widgets.Container() self.dockareamarker.base_color = fifechan.Color(200, 0, 0, 100) if mark is False: self.dockareamarker.hide() for key in DOCKAREA: side = DOCKAREA[key] dockarea = self._dockareas[side] #absX, absY = dockarea.getAbsolutePos() #if absX <= x and absY <= y \ # and absX+dockarea.width >= x and absX+dockarea.height >= y: # return side placeIn, placeBefore, placeAfter = dockarea.getDockLocation(x, y) if placeIn or placeBefore or placeAfter: if mark is True: if placeIn: self.dockareamarker.position = placeIn.getAbsolutePos() self.dockareamarker.size = placeIn.size elif placeBefore: self.dockareamarker.position = placeBefore.getAbsolutePos() if side == "left" or side == "right": self.dockareamarker.size = (placeBefore.width, 10) else: self.dockareamarker.size = (10, placeBefore.height) elif placeAfter: self.dockareamarker.position = placeAfter.getAbsolutePos() if side == "left" or side == "right": self.dockareamarker.size = (placeAfter.width, 10) self.dockareamarker.y += placeAfter.height-10 else: self.dockareamarker.size = (10, placeAfter.height) self.dockareamarker.x += placeAfter.width-10 self.dockareamarker.show() return side # reset side, next attempt to find a new home side = None # Mouse wasn't over any dockwidgets. See if it is near any edge of the screen instead if x <= self._dockareas["left"].getAbsolutePos()[0]+10: if mark: self.dockareamarker.position = self._dockareas["left"].getAbsolutePos() self.dockareamarker.size = (10, self._dockareas["left"].height) self.dockareamarker.show() side = DOCKAREA["left"] return side elif x >= self._dockareas["right"].getAbsolutePos()[0]-10: if mark: self.dockareamarker.position = self._dockareas["right"].getAbsolutePos() self.dockareamarker.size = (10, self._dockareas["right"].height) self.dockareamarker.x -= 10 self.dockareamarker.show() side = DOCKAREA["right"] return side elif y <= self._dockareas["top"].getAbsolutePos()[1]+10: if mark: self.dockareamarker.position = self._dockareas["top"].getAbsolutePos() self.dockareamarker.size = (self._dockareas["top"].width, 10) self.dockareamarker.show() side = DOCKAREA["top"] return side elif y >= self._dockareas["bottom"].getAbsolutePos()[1]-10: if mark: self.dockareamarker.position = self._dockareas["bottom"].getAbsolutePos() self.dockareamarker.y -= 10 self.dockareamarker.size = (self._dockareas["bottom"].width, 10) self.dockareamarker.show() side = DOCKAREA["bottom"] return side if mark is True: self.dockareamarker.hide() return side
class MainWindow(object): def __init__(self, *args, **kwargs): self._toolbar = None self._menubar = None self._statusbar = None self._rootwidget = None self._centralwidget = None self._dockareas = { DOCKAREA['left']:None, DOCKAREA['right']:None, DOCKAREA['top']:None, DOCKAREA['bottom']:None } self._toolbarareas = { DOCKAREA['left']:None, DOCKAREA['right']:None, DOCKAREA['top']:None, DOCKAREA['bottom']:None } self.dockareamarker = None def initGui(self, screen_width, screen_height): bar_height = 30 self._statusbar = StatusBar(text=u"", panel_size=bar_height) self._toolbar = ToolBar(title=u"Toolbar", button_style=0) self._menubar = MenuBar(min_size=(screen_width, bar_height), position=(0, 0)) # Set up root widget self._rootwidget = pychan.widgets.VBox(padding=0, vexpand=1, hexpand=1) self._rootwidget.min_size = \ self._rootwidget.max_size = (screen_width, screen_height) self._rootwidget.opaque = False self._dockareas[DOCKAREA['left']] = DockArea("left") self._dockareas[DOCKAREA['right']] = DockArea("right") self._dockareas[DOCKAREA['top']] = DockArea("top") self._dockareas[DOCKAREA['bottom']] = DockArea("bottom") self._toolbarareas[DOCKAREA['left']] = pychan.widgets.VBox(margins=(0,0,0,0)) self._toolbarareas[DOCKAREA['right']] = pychan.widgets.VBox(margins=(0,0,0,0)) self._toolbarareas[DOCKAREA['top']] = pychan.widgets.HBox(margins=(0,0,0,0)) self._toolbarareas[DOCKAREA['bottom']] = pychan.widgets.HBox(margins=(0,0,0,0)) # This is where the map will be displayed self._centralwidget = pychan.widgets.VBox(vexpand=1, hexpand=1) self._centralwidget.opaque = False middle = pychan.widgets.HBox(padding=0, vexpand=1, hexpand=1) middle.opaque = False # Pychan bug? Adding a spacer instead of a container creates # a gap after the right dockarea middle.addChild(self._toolbarareas['left']) middle.addChild(self._dockareas['left']) middle.addChild(self._centralwidget) #middle.addSpacer(pychan.widgets.Spacer()) middle.addChild(self._dockareas['right']) middle.addChild(self._toolbarareas['right']) self._rootwidget.addChild(self._menubar) #self._rootwidget.addChild(self._toolbar) self._rootwidget.addChild(self._toolbarareas['top']) self._rootwidget.addChild(self._dockareas['top']) self._rootwidget.addChild(middle) self._rootwidget.addChild(self._dockareas['bottom']) self._rootwidget.addChild(self._toolbarareas['bottom']) self._rootwidget.addChild(self._statusbar) self._toolbar.setDocked(True) self.dockWidgetTo(self._toolbar, "top") self._rootwidget.show() def getCentralWidget(self): return self._centralwidget def getStatusBar(self): return self._statusbar def getMenuBar(self): return self._menubar def getToolBar(self): return self._toolbar def dockWidgetTo(self, widget, dockarea, x=-1, y=-1): if isinstance(widget, pychan.widgets.Widget) is False: print "Argument is not a valid widget" return if widget.parent: widgetParent = widget.parent widgetParent.removeChild(widget) widgetParent.adaptLayout() # We must hide the widget before adding it to the dockarea, # or we will get a duplicate copy of the widget in the top left corner # of screen. widget.hide() dockareas = self._dockareas if isinstance(widget, ToolBar): dockareas = self._toolbarareas if dockarea == DOCKAREA['left'] or dockarea == DOCKAREA['right']: widget.setOrientation(ToolBar.ORIENTATION["Vertical"]) elif dockarea == DOCKAREA['top'] or dockarea == DOCKAREA['bottom']: widget.setOrientation(ToolBar.ORIENTATION["Horizontal"]) if isinstance(widget, ToolBar): if dockarea == DOCKAREA['left']: widget.setDocked(True) dockareas[DOCKAREA['left']].addChild(widget) dockareas[DOCKAREA['left']].adaptLayout() elif dockarea == DOCKAREA['right']: widget.setDocked(True) dockareas[DOCKAREA['right']].addChild(widget) dockareas[DOCKAREA['right']].adaptLayout() elif dockarea == DOCKAREA['top']: widget.setDocked(True) dockareas[DOCKAREA['top']].addChild(widget) dockareas[DOCKAREA['top']].adaptLayout() elif dockarea == DOCKAREA['bottom']: widget.setDocked(True) dockareas[DOCKAREA['bottom']].addChild(widget) dockareas[DOCKAREA['bottom']].adaptLayout() else: print "Invalid dockarea" else: if dockarea == DOCKAREA['left']: dockareas[DOCKAREA['left']].dockChild(widget, x, y) elif dockarea == DOCKAREA['right']: dockareas[DOCKAREA['right']].dockChild(widget, x, y) elif dockarea == DOCKAREA['top']: dockareas[DOCKAREA['top']].dockChild(widget, x, y) elif dockarea == DOCKAREA['bottom']: dockareas[DOCKAREA['bottom']].dockChild(widget, x, y) else: print "Invalid dockarea" def getToolbarAreaAt(self, x, y, mark=False): if self.dockareamarker is None: self.dockareamarker = pychan.widgets.Container() self.dockareamarker.base_color = fife.Color(200, 0, 0, 100) if mark is False: self.dockareamarker.hide() # Mouse wasn't over any dockwidgets. See if it is near any edge of the screen instead if x <= self._toolbarareas["left"].getAbsolutePos()[0]+10: if mark: self.dockareamarker.position = self._toolbarareas["left"].getAbsolutePos() self.dockareamarker.size = (10, self._toolbarareas["left"].height) self.dockareamarker.show() return DOCKAREA["left"] elif x >= self._toolbarareas["right"].getAbsolutePos()[0]-10: if mark: self.dockareamarker.position = self._toolbarareas["right"].getAbsolutePos() self.dockareamarker.size = (10, self._toolbarareas["right"].height) self.dockareamarker.x -= 10 self.dockareamarker.show() return DOCKAREA["right"] elif y <= self._toolbarareas["top"].getAbsolutePos()[1]+10: if mark: self.dockareamarker.position = self._toolbarareas["top"].getAbsolutePos() self.dockareamarker.size = (self._toolbarareas["top"].width, 10) self.dockareamarker.show() return DOCKAREA["top"] elif y >= self._toolbarareas["bottom"].getAbsolutePos()[1]-10: if mark: self.dockareamarker.position = self._toolbarareas["bottom"].getAbsolutePos() self.dockareamarker.y -= 10 self.dockareamarker.size = (self._toolbarareas["bottom"].width, 10) self.dockareamarker.show() return DOCKAREA["bottom"] if mark is True: self.dockareamarker.hide() return None def getDockAreaAt(self, x, y, mark=False): if self.dockareamarker is None: self.dockareamarker = pychan.widgets.Container() self.dockareamarker.base_color = fife.Color(200, 0, 0, 100) if mark is False: self.dockareamarker.hide() for key in DOCKAREA: side = DOCKAREA[key] dockarea = self._dockareas[side] #absX, absY = dockarea.getAbsolutePos() #if absX <= x and absY <= y \ # and absX+dockarea.width >= x and absX+dockarea.height >= y: # return side placeIn, placeBefore, placeAfter = dockarea.getDockLocation(x, y) if placeIn or placeBefore or placeAfter: if mark is True: if placeIn: self.dockareamarker.position = placeIn.getAbsolutePos() self.dockareamarker.size = placeIn.size elif placeBefore: self.dockareamarker.position = placeBefore.getAbsolutePos() if side == "left" or side == "right": self.dockareamarker.size = (placeBefore.width, 10) else: self.dockareamarker.size = (10, placeBefore.height) elif placeAfter: self.dockareamarker.position = placeAfter.getAbsolutePos() if side == "left" or side == "right": self.dockareamarker.size = (placeAfter.width, 10) self.dockareamarker.y += placeAfter.height-10 else: self.dockareamarker.size = (10, placeAfter.height) self.dockareamarker.x += placeAfter.width-10 self.dockareamarker.show() return side # Mouse wasn't over any dockwidgets. See if it is near any edge of the screen instead if x <= self._dockareas["left"].getAbsolutePos()[0]+10: if mark: self.dockareamarker.position = self._dockareas["left"].getAbsolutePos() self.dockareamarker.size = (10, self._dockareas["left"].height) self.dockareamarker.show() return DOCKAREA["left"] elif x >= self._dockareas["right"].getAbsolutePos()[0]-10: if mark: self.dockareamarker.position = self._dockareas["right"].getAbsolutePos() self.dockareamarker.size = (10, self._dockareas["right"].height) self.dockareamarker.x -= 10 self.dockareamarker.show() return DOCKAREA["right"] elif y <= self._dockareas["top"].getAbsolutePos()[1]+10: if mark: self.dockareamarker.position = self._dockareas["top"].getAbsolutePos() self.dockareamarker.size = (self._dockareas["top"].width, 10) self.dockareamarker.show() return DOCKAREA["top"] elif y >= self._dockareas["bottom"].getAbsolutePos()[1]-10: if mark: self.dockareamarker.position = self._dockareas["bottom"].getAbsolutePos() self.dockareamarker.y -= 10 self.dockareamarker.size = (self._dockareas["bottom"].width, 10) self.dockareamarker.show() return DOCKAREA["bottom"] if mark is True: self.dockareamarker.hide() return None
class GtkUI(object): def __init__(self, args): self.daemon_bps = (0, 0, 0) # Setup signals try: import gnome.ui import gnome #Suppress: Warning: Attempt to add property GnomeProgram::*** after class was initialised original_filters = warnings.filters[:] warnings.simplefilter("ignore") try: self.gnome_prog = gnome.init("Deluge", deluge.common.get_version()) finally: warnings.filters = original_filters self.gnome_client = gnome.ui.master_client() def on_die(*args): reactor.stop() self.gnome_client.connect("die", on_die) log.debug("GNOME session 'die' handler registered!") except Exception, e: log.warning( "Unable to register a 'die' handler with the GNOME session manager: %s", e) if deluge.common.windows_check(): from win32api import SetConsoleCtrlHandler from win32con import CTRL_CLOSE_EVENT from win32con import CTRL_SHUTDOWN_EVENT def win_handler(ctrl_type): log.debug("ctrl_type: %s", ctrl_type) if ctrl_type in (CTRL_CLOSE_EVENT, CTRL_SHUTDOWN_EVENT): reactor.stop() return 1 SetConsoleCtrlHandler(win_handler) if deluge.common.osx_check() and Gdk.WINDOWING == "quartz": import gtkosx_application self.osxapp = gtkosx_application.gtkosx_application_get() def on_die(*args): reactor.stop() self.osxapp.connect("NSApplicationWillTerminate", on_die) # Set process name again to fix gtk issue setproctitle(getproctitle()) # Attempt to register a magnet URI handler with gconf, but do not overwrite # if already set by another program. common.associate_magnet_links(False) # Make sure gtkui.conf has at least the defaults set self.config = deluge.configmanager.ConfigManager( "gtkui.conf", DEFAULT_PREFS) # We need to check on exit if it was started in classic mode to ensure we # shutdown the daemon. self.started_in_classic = self.config["classic_mode"] # Start the IPC Interface before anything else.. Just in case we are # already running. self.queuedtorrents = QueuedTorrents() self.ipcinterface = IPCInterface(args) # Initialize gdk threading Gdk.threads_init() GObject.threads_init() # We make sure that the UI components start once we get a core URI client.set_disconnect_callback(self.__on_disconnect) self.trackericons = TrackerIcons() self.sessionproxy = SessionProxy() # Initialize various components of the gtkui self.mainwindow = MainWindow() self.menubar = MenuBar() self.toolbar = ToolBar() self.torrentview = TorrentView() self.torrentdetails = TorrentDetails() self.sidebar = SideBar() self.filtertreeview = FilterTreeView() self.preferences = Preferences() self.systemtray = SystemTray() self.statusbar = StatusBar() self.addtorrentdialog = AddTorrentDialog() if deluge.common.osx_check() and Gdk.WINDOWING == "quartz": def nsapp_open_file(osxapp, filename): # Will be raised at app launch (python opening main script) if filename.endswith('Deluge-bin'): return True from deluge.ui.gtkui.ipcinterface import process_args process_args([filename]) self.osxapp.connect("NSApplicationOpenFile", nsapp_open_file) from menubar_osx import menubar_osx menubar_osx(self, self.osxapp) self.osxapp.ready() # Initalize the plugins self.plugins = PluginManager() # Show the connection manager self.connectionmanager = ConnectionManager() from twisted.internet.task import LoopingCall rpc_stats = LoopingCall(self.print_rpc_stats) rpc_stats.start(10) reactor.callWhenRunning(self._on_reactor_start) # Start the gtk main loop Gdk.threads_enter() reactor.run() self.shutdown() Gdk.threads_leave()
class AfelApp(QMainWindow): def __init__(self, parent=None): super(AfelApp, self).__init__(parent) self.setGeometry(10, 10, 1000, 1200) # self.setStyleSheet(""" # # font-size: 200; # # """) # Flags self.modes = { 'outer_window': True, 'live_mode': False } self.result_box_group = None self.result_box = None self.module_btns = [] mainWindow = QWidget(self) self.setCentralWidget(mainWindow) mainlay = QHBoxLayout() mainWindow.setLayout(mainlay) # load area btns_group = QGroupBox() btns_lay = QVBoxLayout() btns_group.setLayout(btns_lay) btns_lay.addStretch(1) self.btns_lay = btns_lay self.load_modules_btns() startbtn = QPushButton('start process') startbtn.clicked.connect(self.start_process) btns_lay.addWidget(startbtn) # sandbox area self.sandbox = SandBox() self.sandboxlay = QVBoxLayout() # self.sandboxlay.addStretch(209) self.sandbox.setLayout(self.sandboxlay) mainlay.addWidget(btns_group,1) mainlay.addWidget(self.sandbox,10) # toolbar # toolbar.setIconSize(QSize(16, 16)) self.toolbar = ToolBar(self) self.addToolBar(self.toolbar) def load_modules_btns(self): self.clear_modules_btns() all_modules, errors = Module.get_all_modules() for btn in [ModuleBtn(m) for m in all_modules]: self.btns_lay.insertWidget(0, btn) self.module_btns.append(btn) self.pop_errors(errors) def pop_errors(self, errors): for e in errors: w = QMainWindow(self) w.setCentralWidget(AMsgBox(self,e)) w.show() def clear_modules_btns(self): [b.deleteLater() for b in self.module_btns] self.module_btns = [] def reload(self): # reload all - sandbox and modules btn temp_path = 'm/temp/temporaryModules' # sandbox cash self.sandbox.dump_sandbox(temp_path) self.clear_modules_btns() self.load_modules_btns() self.sandbox.clear_sandbox(force=True) self.sandbox.load_file_modules(temp_path) def start_process(self): if self.result_box_group: # Qgroup to include the results window when not poped self.result_box_group.deleteLater() # improve memory self.result_box_group = None self.old_box = self.result_box starter = self.sandbox.starter if starter: try: extras = starter.module.run() self.result_box = ResultView(self, extras) if self.modes['outer_window']: w = QMainWindow(self) w.setCentralWidget(self.result_box) w.show() else: g = QGroupBox() gl = QHBoxLayout() g.setLayout(gl) gl.addWidget(self.result_box) self.result_box_group = g self.layout().addWidget(g, 5) except: self.pop_errors([format_exc()]) else: self.statusBar().showMessage('please define starter', 2000) self.sandbox.force_stater() self.start_process() def keyPressEvent(self, event): self.toolbar.shortcut(event.key())