def __init__(self, context):
        super(NodeManager, self).__init__(context)
        # Give QObjects reasonable names
        self.setObjectName('NodeManagerFKIE')

        # Process standalone plugin command-line arguments
        from argparse import ArgumentParser
        parser = ArgumentParser()
        # Add argument(s) to the parser.
        parser.add_argument("-q", "--quiet", action="store_true",
                            dest="quiet",
                            help="Put plugin in silent mode")
        args, unknowns = parser.parse_known_args(context.argv())
        if not args.quiet:
            print 'arguments: ', args
            print 'unknowns: ', unknowns
        node_manager_fkie.init_settings()
        masteruri = node_manager_fkie.settings().masteruri()
        node_manager_fkie.init_globals(masteruri)
        # Create QWidget
        try:
            self._widget = MainWindow()
#          self._widget.read_view_history()
        except Exception, e:
            MessageBox.critical(self, "Node Manager", utf8(e))
            raise
 def focusInEvent(self, event):
     # check for file changes
     try:
         if self.filename and self.file_info:
             if self.file_info.lastModified() != QFileInfo(
                     self.filename).lastModified():
                 self.file_info = QFileInfo(self.filename)
                 result = MessageBox.question(self,
                                              "File changed",
                                              "File was changed, reload?",
                                              buttons=MessageBox.Yes
                                              | MessageBox.No)
                 if result == MessageBox.Yes:
                     f = QFile(self.filename)
                     if f.open(QIODevice.ReadOnly | QIODevice.Text):
                         self.setText(unicode(f.readAll(), "utf-8"))
                         self.document().setModified(False)
                         self.textChanged.emit()
                     else:
                         MessageBox.critical(
                             self, "Error",
                             "Cannot open launch file%s" % self.filename)
     except:
         pass
     QTextEdit.focusInEvent(self, event)
    def __init__(self, context):
        super(NodeManager, self).__init__(context)
        # Give QObjects reasonable names
        self.setObjectName('NodeManagerFKIE')

        # Process standalone plugin command-line arguments
        from argparse import ArgumentParser
        parser = ArgumentParser()
        # Add argument(s) to the parser.
        parser.add_argument("-q",
                            "--quiet",
                            action="store_true",
                            dest="quiet",
                            help="Put plugin in silent mode")
        args, unknowns = parser.parse_known_args(context.argv())
        if not args.quiet:
            print 'arguments: ', args
            print 'unknowns: ', unknowns
        node_manager_fkie.init_settings()
        masteruri = node_manager_fkie.settings().masteruri()
        node_manager_fkie.init_globals(masteruri)
        # Create QWidget
        try:
            self._widget = MainWindow()
#          self._widget.read_view_history()
        except Exception, e:
            MessageBox.critical(self, "Node Manager", utf8(e))
            raise
 def mouseReleaseEvent(self, event):
     '''
     Opens the new editor, if the user clicked on the included file and sets the
     default cursor.
     '''
     if event.modifiers() == Qt.ControlModifier or event.modifiers() == Qt.ShiftModifier:
         cursor = self.cursorForPosition(event.pos())
         inc_files = LaunchConfig.included_files(cursor.block().text(), recursive=False)
         if inc_files:
             try:
                 qf = QFile(inc_files[0])
                 if not qf.exists():
                     # create a new file, if it does not exists
                     result = MessageBox.question(self, "File not found", '\n\n'.join(["Create a new file?", qf.fileName()]), buttons=MessageBox.Yes | MessageBox.No)
                     if result == MessageBox.Yes:
                         d = os.path.dirname(qf.fileName())
                         if not os.path.exists(d):
                             os.makedirs(d)
                         with open(qf.fileName(), 'w') as f:
                             if qf.fileName().endswith('.launch'):
                                 f.write('<launch>\n\n</launch>')
                         event.setAccepted(True)
                         self.load_request_signal.emit(qf.fileName())
                 else:
                     event.setAccepted(True)
                     self.load_request_signal.emit(qf.fileName())
             except Exception, e:
                 MessageBox.critical(self, "Error", "File not found %s" % inc_files[0], detailed_text=utf8(e))
 def setData(self, value, role=Qt.EditRole):
     if role == Qt.EditRole:
         self._value = value
         if hasattr(self._settings, self._attrname):
             setattr(self._settings, self._attrname, value)
             if self._need_restart:
                 MessageBox.information(None, "restart Node Manager", "This parameter change is only valid after restart!")
     return QStandardItem.setData(self, value, role)
 def on_saveButton_clicked(self):
     '''
     Saves the current document. This method is called if the C{save button}
     was clicked.
     '''
     saved, errors, msg = self.tabWidget.currentWidget().save(True)
     if errors:
         MessageBox.critical(self, "Error", msg)
         self.tabWidget.setTabIcon(self.tabWidget.currentIndex(), self._error_icon)
         self.tabWidget.setTabToolTip(self.tabWidget.currentIndex(), msg)
     elif saved:
         self.tabWidget.setTabIcon(self.tabWidget.currentIndex(), self._empty_icon)
         self.tabWidget.setTabToolTip(self.tabWidget.currentIndex(), '')
         self.graph_view.clear_cache()
 def on_close_tab(self, tab_index):
     '''
     Signal handling to close single tabs.
     @param tab_index: tab index to close
     @type tab_index: C{int}
     '''
     try:
         doremove = True
         w = self.tabWidget.widget(tab_index)
         if w.document().isModified():
             name = self.__getTabName(w.filename)
             result = MessageBox.question(
                 self, "Unsaved Changes",
                 '\n\n'.join(["Save the file before closing?", name]))
             if result == MessageBox.Yes:
                 self.tabWidget.currentWidget().save()
             elif result == MessageBox.No:
                 pass
             else:
                 doremove = False
         if doremove:
             # remove the indexed files
             if w.filename in self.files:
                 self.files.remove(w.filename)
             # close tab
             self.tabWidget.removeTab(tab_index)
             # close editor, if no tabs are open
             if not self.tabWidget.count():
                 self.close()
     except Exception:
         import traceback
         rospy.logwarn("Error while close tab %s: %s", str(tab_index),
                       traceback.format_exc(1))
     self.upperButton.setEnabled(self.tabWidget.count() > 1)
 def closeEvent(self, event):
     '''
     Test the open files for changes and save this if needed.
     '''
     changed = []
     # get the names of all changed files
     for i in range(self.tabWidget.count()):
         w = self.tabWidget.widget(i)
         if w.document().isModified():
             changed.append(self.__getTabName(w.filename))
     if changed:
         # ask the user for save changes
         if self.isHidden():
             buttons = MessageBox.Yes | MessageBox.No
         else:
             buttons = MessageBox.Yes | MessageBox.No | MessageBox.Cancel
         result = MessageBox.question(self, "Unsaved Changes", '\n\n'.join(["Save the file before closing?", '\n'.join(changed)]), buttons=buttons)
         if result == MessageBox.Yes:
             for i in range(self.tabWidget.count()):
                 w = self.tabWidget.widget(i).save()
             self.graph_view.clear_cache()
             event.accept()
         elif result == MessageBox.No:
             event.accept()
         else:
             event.ignore()
     else:
         event.accept()
     if event.isAccepted():
         self.storeSetting()
         self.finished_signal.emit(self.init_filenames)
 def on_close_tab(self, tab_index):
     '''
     Signal handling to close single tabs.
     @param tab_index: tab index to close
     @type tab_index: C{int}
     '''
     try:
         doremove = True
         w = self.tabWidget.widget(tab_index)
         if w.document().isModified():
             name = self.__getTabName(w.filename)
             result = MessageBox.question(self, "Unsaved Changes", '\n\n'.join(["Save the file before closing?", name]))
             if result == MessageBox.Yes:
                 self.tabWidget.currentWidget().save()
             elif result == MessageBox.No:
                 pass
             else:
                 doremove = False
         if doremove:
             # remove the indexed files
             if w.filename in self.files:
                 self.files.remove(w.filename)
             # close tab
             self.tabWidget.removeTab(tab_index)
             # close editor, if no tabs are open
             if not self.tabWidget.count():
                 self.close()
     except Exception:
         import traceback
         rospy.logwarn("Error while close tab %s: %s", str(tab_index), traceback.format_exc(1))
     self.upperButton.setEnabled(self.tabWidget.count() > 1)
 def killScreens(cls, node, host, auto_ok_request=True, user=None, pw=None):
     '''
     Searches for the screen associated with the given node and kill this screens.
     @param node: the name of the node those screen output to show
     @type node: C{str}
     @param host: the host name or ip where the screen is running
     @type host: C{str}
     '''
     if node is None or len(node) == 0:
         return False
     try:
         # get the available screens
         screens = cls._getActiveScreens(host, cls.createSessionName(node), auto_ok_request, user=user, pwd=pw)  # user=user, pwd=pwd
         if screens:
             do_kill = True
             if auto_ok_request:
                 from node_manager_fkie.detailed_msg_box import MessageBox
                 result = MessageBox.question(None, "Kill SCREENs?", '\n'.join(screens), buttons=MessageBox.Ok | MessageBox.Cancel)
                 if result == MessageBox.Ok:
                     do_kill = True
             if do_kill:
                 for s in screens:
                     pid, _, _ = s.partition('.')
                     if pid:
                         try:
                             nm.starter()._kill_wo(host, int(pid), auto_ok_request, user, pw)
                         except:
                             import traceback
                             rospy.logwarn("Error while kill screen (PID: %s) on host '%s': %s", utf8(pid), utf8(host), traceback.format_exc(1))
                 if nm.is_local(host):
                     SupervisedPopen([cls.SCREEN, '-wipe'], object_id='screen -wipe', description="screen: clean up the socket with -wipe")
                 else:
                     nm.ssh().ssh_exec(host, [cls.SCREEN, '-wipe'], close_stdin=True, close_stdout=True, close_stderr=True)
     except nm.AuthenticationRequest as e:
         raise nm.InteractionNeededError(e, cls.killScreens, (node, host, auto_ok_request))
 def on_saveButton_clicked(self):
     '''
     Saves the current document. This method is called if the C{save button}
     was clicked.
     '''
     saved, errors, msg = self.tabWidget.currentWidget().save(True)
     if errors:
         MessageBox.critical(self, "Error", msg)
         self.tabWidget.setTabIcon(self.tabWidget.currentIndex(),
                                   self._error_icon)
         self.tabWidget.setTabToolTip(self.tabWidget.currentIndex(), msg)
     elif saved:
         self.tabWidget.setTabIcon(self.tabWidget.currentIndex(),
                                   self._empty_icon)
         self.tabWidget.setTabToolTip(self.tabWidget.currentIndex(), '')
         self.graph_view.clear_cache()
 def _on_edit_interface_clicked(self):
     self._new_iface = False
     self.interface_field.setVisible(False)
     self.toolButton_CreateInterface.setVisible(False)
     self.toolButton_EditInterface.setVisible(False)
     self.textedit.setVisible(True)
     if self.interface_field.currentText() in self._interfaces_files:
         try:
             with open(self._interfaces_files[self.interface_field.currentText()], 'rw') as f:
                 iface = f.read()
                 self.textedit.setText(iface)
         except Exception as e:
             MessageBox.warning(self, "Edit sync interface",
                                "Error while open interface",
                                utf8(e))
     self.resize(350, 300)
 def _on_edit_interface_clicked(self):
     self._new_iface = False
     self.interface_field.setVisible(False)
     self.toolButton_CreateInterface.setVisible(False)
     self.toolButton_EditInterface.setVisible(False)
     self.textedit.setVisible(True)
     if self.interface_field.currentText() in self._interfaces_files:
         try:
             with open(
                     self._interfaces_files[
                         self.interface_field.currentText()], 'rw') as f:
                 iface = f.read()
                 self.textedit.setText(iface)
         except Exception as e:
             MessageBox.warning(self, "Edit sync interface",
                                "Error while open interface", utf8(e))
     self.resize(350, 300)
 def focusInEvent(self, event):
     # check for file changes
     try:
         if self.filename and self.file_info:
             if self.file_info.lastModified() != QFileInfo(self.filename).lastModified():
                 self.file_info = QFileInfo(self.filename)
                 result = MessageBox.question(self, "File changed", "File was changed, reload?", buttons=MessageBox.Yes | MessageBox.No)
                 if result == MessageBox.Yes:
                     f = QFile(self.filename)
                     if f.open(QIODevice.ReadOnly | QIODevice.Text):
                         self.setText(unicode(f.readAll(), "utf-8"))
                         self.document().setModified(False)
                         self.textChanged.emit()
                     else:
                         MessageBox.critical(self, "Error", "Cannot open launch file%s" % self.filename)
     except:
         pass
     QTextEdit.focusInEvent(self, event)
    def accept(self):
        if self.textedit.isVisible():
            try:
                tmp_file = os.path.join(nm.screen().LOG_PATH,
                                        'tmp_sync_interface.sync')
                with open(tmp_file, 'w+') as f:
                    f.write(self.textedit.toPlainText())
                from master_discovery_fkie.common import read_interface
                read_interface(tmp_file)
                if not self._new_iface and self.interface_field.currentText(
                ) in self._interfaces_files:
                    fileName = self._interfaces_files[
                        self.interface_field.currentText()]
                else:
                    fileName, _ = QFileDialog.getSaveFileName(
                        self, 'Save sync interface', '/home',
                        "Sync Files (*.sync)")
                if fileName:
                    with open(fileName, 'w+') as f:
                        self._interface_filename = fileName
                        f.write(self.textedit.toPlainText())
                        if self._new_iface:
                            self.interface_field.clear()
                            self._interfaces_files = None
                        self._on_select_interface_clicked()


#        QDialog.accept(self)
#        self.resetView()
            except Exception as e:
                MessageBox.warning(self, "Create sync interface",
                                   "Error while create interface", utf8(e))
        elif self.interface_field.isVisible():
            interface = self.interface_field.currentText()
            if self._interfaces_files and interface in self._interfaces_files:
                self._interface_filename = self._interfaces_files[interface]
                self._sync_args = []
                self._sync_args.append(''.join(['_interface_url:=',
                                                interface]))
                QDialog.accept(self)
                self.resetView()
        else:
            QDialog.accept(self)
            self.resetView()
 def killScreens(cls, node, host, auto_ok_request=True, user=None, pw=None):
     '''
     Searches for the screen associated with the given node and kill this screens.
     @param node: the name of the node those screen output to show
     @type node: C{str}
     @param host: the host name or ip where the screen is running
     @type host: C{str}
     '''
     if node is None or len(node) == 0:
         return False
     try:
         # get the available screens
         screens = cls._getActiveScreens(host,
                                         cls.createSessionName(node),
                                         auto_ok_request,
                                         user=user,
                                         pwd=pw)  # user=user, pwd=pwd
         if screens:
             do_kill = True
             if auto_ok_request:
                 from node_manager_fkie.detailed_msg_box import MessageBox
                 result = MessageBox.question(None,
                                              "Kill SCREENs?",
                                              '\n'.join(screens),
                                              buttons=MessageBox.Ok
                                              | MessageBox.Cancel)
                 if result == MessageBox.Ok:
                     do_kill = True
             if do_kill:
                 for s in screens:
                     pid, _, _ = s.partition('.')
                     if pid:
                         try:
                             nm.starter()._kill_wo(host, int(pid),
                                                   auto_ok_request, user,
                                                   pw)
                         except:
                             import traceback
                             rospy.logwarn(
                                 "Error while kill screen (PID: %s) on host '%s': %s",
                                 utf8(pid), utf8(host),
                                 traceback.format_exc(1))
                 if nm.is_local(host):
                     SupervisedPopen(
                         [cls.SCREEN, '-wipe'],
                         object_id='screen -wipe',
                         description="screen: clean up the socket with -wipe"
                     )
                 else:
                     nm.ssh().ssh_exec(host, [cls.SCREEN, '-wipe'],
                                       close_stdin=True,
                                       close_stdout=True,
                                       close_stderr=True)
     except nm.AuthenticationRequest as e:
         raise nm.InteractionNeededError(e, cls.killScreens,
                                         (node, host, auto_ok_request))
Exemple #17
0
 def _progress_thread_error(self, ident, title, msg, detailed_msg):
     btns = (MessageBox.Ignore | MessageBox.Avoid)
     if len(self.__progress_queue) > 1:
         btns = (btns | MessageBox.Abort)
     res = MessageBox(MessageBox.Critical, title, msg, detailed_msg, buttons=btns).exec_()
     if res == MessageBox.Abort:
         self.__progress_queue = []
         self._progress_frame.setVisible(False)
         self.__running = False
     else:
         self._progress_thread_finished(ident)
 def mouseReleaseEvent(self, event):
     '''
     Opens the new editor, if the user clicked on the included file and sets the
     default cursor.
     '''
     if event.modifiers() == Qt.ControlModifier or event.modifiers(
     ) == Qt.ShiftModifier:
         cursor = self.cursorForPosition(event.pos())
         inc_files = LaunchConfig.included_files(cursor.block().text(),
                                                 recursive=False)
         if inc_files:
             try:
                 qf = QFile(inc_files[0])
                 if not qf.exists():
                     # create a new file, if it does not exists
                     result = MessageBox.question(
                         self,
                         "File not found",
                         '\n\n'.join(["Create a new file?",
                                      qf.fileName()]),
                         buttons=MessageBox.Yes | MessageBox.No)
                     if result == MessageBox.Yes:
                         d = os.path.dirname(qf.fileName())
                         if not os.path.exists(d):
                             os.makedirs(d)
                         with open(qf.fileName(), 'w') as f:
                             if qf.fileName().endswith('.launch'):
                                 f.write('<launch>\n\n</launch>')
                         event.setAccepted(True)
                         self.load_request_signal.emit(qf.fileName())
                 else:
                     event.setAccepted(True)
                     self.load_request_signal.emit(qf.fileName())
             except Exception, e:
                 MessageBox.critical(self,
                                     "Error",
                                     "File not found %s" % inc_files[0],
                                     detailed_text=utf8(e))
    def accept(self):
        if self.textedit.isVisible():
            try:
                tmp_file = os.path.join(nm.screen().LOG_PATH, 'tmp_sync_interface.sync')
                with open(tmp_file, 'w+') as f:
                    f.write(self.textedit.toPlainText())
                from master_discovery_fkie.common import read_interface
                read_interface(tmp_file)
                if not self._new_iface and self.interface_field.currentText() in self._interfaces_files:
                    fileName = self._interfaces_files[self.interface_field.currentText()]
                else:
                    fileName, _ = QFileDialog.getSaveFileName(self, 'Save sync interface', '/home', "Sync Files (*.sync)")
                if fileName:
                    with open(fileName, 'w+') as f:
                        self._interface_filename = fileName
                        f.write(self.textedit.toPlainText())
                        if self._new_iface:
                            self.interface_field.clear()
                            self._interfaces_files = None
                        self._on_select_interface_clicked()
#        QDialog.accept(self)
#        self.resetView()
            except Exception as e:
                MessageBox.warning(self, "Create sync interface",
                                   "Error while create interface",
                                   utf8(e))
        elif self.interface_field.isVisible():
            interface = self.interface_field.currentText()
            if self._interfaces_files and interface in self._interfaces_files:
                self._interface_filename = self._interfaces_files[interface]
                self._sync_args = []
                self._sync_args.append(''.join(['_interface_url:=', interface]))
                QDialog.accept(self)
                self.resetView()
        else:
            QDialog.accept(self)
            self.resetView()
 def closeEvent(self, event):
     '''
     Test the open files for changes and save this if needed.
     '''
     changed = []
     # get the names of all changed files
     for i in range(self.tabWidget.count()):
         w = self.tabWidget.widget(i)
         if w.document().isModified():
             changed.append(self.__getTabName(w.filename))
     if changed:
         # ask the user for save changes
         if self.isHidden():
             buttons = MessageBox.Yes | MessageBox.No
         else:
             buttons = MessageBox.Yes | MessageBox.No | MessageBox.Cancel
         result = MessageBox.question(self,
                                      "Unsaved Changes",
                                      '\n\n'.join([
                                          "Save the file before closing?",
                                          '\n'.join(changed)
                                      ]),
                                      buttons=buttons)
         if result == MessageBox.Yes:
             for i in range(self.tabWidget.count()):
                 w = self.tabWidget.widget(i).save()
             self.graph_view.clear_cache()
             event.accept()
         elif result == MessageBox.No:
             event.accept()
         else:
             event.ignore()
     else:
         event.accept()
     if event.isAccepted():
         self.storeSetting()
         self.finished_signal.emit(self.init_filenames)