Beispiel #1
0
	def handleMainWindowEmits(self, param):
		#print(param)
		if param == "SCAN":
			self._theMainWindow.theScan.clear()
			self._theMainWindow.theScan.theSelect.clear()
			self._theMainWindow.theScan.show()
		elif param == "UPDATE":
			self._theMainWindow.theUpdate.show()
		elif param == "HISTORY":
			self._theMainWindow.theHistory.show()
			# populating combo boxes
			availMal = utilities.populateMalware()
			modelMalware = utilities.malwareModel(availMal)
			self._theMainWindow.theHistory.comMalware.setModel(modelMalware)
			availDBs = utilities.populateVirusDBs()
			modelDBs = utilities.virusDBModel(availDBs)
			
			#populating date fields
			self.curDateList = date.today().isoformat().split('-')
			self.curQDate = QDate(int(self.curDateList[0]), int(self.curDateList[1]), int(self.curDateList[2]))
			self._theMainWindow.theHistory.comStartDate.setDate(self.curQDate )
			self._theMainWindow.theHistory.comEndDate.setDate(self.curQDate )
			
			self._theMainWindow.theHistory.comDatabase.setModel(modelDBs)
			
		else:
			QMessageBox.critical(None, langmodule.attention, langmodule.applicationError, 
								 QMessageBox.Ok | QMessageBox.Default, QMessageBox.NoButton)
Beispiel #2
0
def create_window(window_class, **kwargs):
    """Create a QT window in Python, or interactively in IPython with QT GUI
    event loop integration.
    """
    global app

    app = get_app_qt4(sys.argv)
    app.references = set()

    net = None
    fname = None
    if len(sys.argv) > 1:
        fname = sys.argv[1]
        if os.path.exists(fname):
            net = read_pickle(fname)
        else:
            QMessageBox.critical(
                        None, "Error opening file %s", fname,
                        QMessageBox.Ok, QMessageBox.NoButton)

    window = window_class(net, fname)
    app.references.add(window)
    window.show()

    start_event_loop_qt4(app)
    return window
Beispiel #3
0
	def extractToText(self):
		try:
			now = datetime.now().isoformat().split('T')
			filename='scanLog_' + now[0][0:10] + '_' + now[1][0:8] + '.txt'
			flags = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly
			folder = QFileDialog.getExistingDirectory(self._theMainWindow.theHistory.theResults, langmodule.chooseFolderToStoreText, homeDir, flags)
			print(filename)
			print(manager._resultsToPrint)
			path = folder + '/' + filename
			with open(path, 'w') as file:
				file.write(langmodule.userTitle + '\t\t\t' + langmodule.noOfResultsTitle  + '\t\t' + langmodule.scanDateTimeTitle + '\n') # linux specific newline - not portable!
				file.write("----------------------------------------------------------------------------------" + '\n') # linux specific newline - not portable!
				for inlist in manager._resultsToPrint:
					file.write(inlist[0] + '\t\t\t')
					file.write(inlist[1] + '\t\t\t\t\t')
					file.write(inlist[2] + '\n') # linux specific newline - not portable!
				file.close()	
		except IOError as error:
			print(str(error)[0:13])
			if "Permission denied" in str(error):
				QMessageBox.critical(None, langmodule.attention, langmodule.noAccessRightsInFolder, 
								 QMessageBox.Ok | QMessageBox.Default, QMessageBox.NoButton)
		except Exception:
			QMessageBox.critical(None, langmodule.attention, langmodule.errorStoringFile, 
								 QMessageBox.Ok | QMessageBox.Default, QMessageBox.NoButton)
Beispiel #4
0
    def fetched_usages(self, reply):
        self.updateButton.setEnabled(True)
        self.progressBar.setHidden(True)

        if reply.error() == QNetworkReply.NoError:
            if not self.usage_model.parse(str(reply.readAll())):
                title = "Parsing error"
                message = self.usage_model.error
            else:
                title = None
                self.tree_model.deleteLater()
                self.tree_model = TreeModel(self.usage_model.usage)
                self.treeView.setModel(self.tree_model)
                self.show_lastupdate()
                self.write_usage()
        elif reply.error() in [QNetworkReply.AuthenticationRequiredError,
                               QNetworkReply.ContentAccessDenied]:
            title = "Authentication error"
            message = "Please check your account credentials."
        else:
            title = "An error occured"
            message = reply.errorString() \
                    + ".\nPlease check your internet connection."

        if title:
            QMessageBox.critical(self, title, message)
        reply.deleteLater()
Beispiel #5
0
    def accept(self):
        self.model.name = self.accountNameEdit.text()
        username = self.usernameEdit.text()
        password = self.passwordEdit.text()
        if not all([username, password]):
            QMessageBox.critical(self, "Username & Password",
                                "Both the username and password are required.")
            if not username:
                self.usernameEdit.setFocus()
            else:
                self.passwordEdit.setFocus()
            return
        self.model.username = username
        self.model.password = password

        try:
            self.model.capKB = int(self.capEdit.text() or 0)
        except ValueError:
            QMessageBox.critical(self, "Invalid value",
                                 "Please enter a number in KB for the capacity.")
            self.capEdit.setFocus()
            return

        self.model.start = self.fromDate.date()
        self.model.end = self.toDate.date()

        super(AccountDialog, self).accept()
Beispiel #6
0
 def setup_model(self):
     db = Db_Instance("edit_associate").get_instance()
     if not db.open():
         self.log.error(db.lastError().text())
         message = unicode("Erro de conexão\n\n""Banco de dados indisponível".decode('utf-8'))
         QMessageBox.critical(self, unicode("Seareiros - Edição de Associado".decode('utf-8')), message)
     else:
         self._model = QSqlRelationalTableModel(self, db=db)
         self._model.setTable("associate")
         self._act_model = QSqlRelationalTableModel(self, db=db)
         self._act_model.setTable("associate_in_activity")
         # TODO: Maybe I should validate these
         # associate
         self._model.setFilter("id = " + str(self._record_id))
         self._model.select()
         self._record = self._model.record(0)
         # activities
         self._activity_records = []
         sql_statement = """SELECT id, description, room, weekday, weektime FROM activity a,
                            associate_in_activity a_a WHERE
                            a.id = a_a.id_activity AND a_a.id_associate = %s
                         """ % str(self._record_id)
         model_activities = QSqlQueryModel()
         model_activities.setQuery(sql_statement, db)
         # checking query validity
         if not model_activities.lastError().isValid():
             self._activity_records = iterate_model(model_activities)
Beispiel #7
0
    def doActionSageServer(self):
        server_list_dialog = ServerListDlg(self)

        #Get a reference to the WorksheetController associated to this window.
        wsc = self.webViewController().worksheet_controller

        #Select the server associated to this window, if there is one.
        if wsc and wsc.server_configuration:
            server_list_dialog.selectServer(wsc.server_configuration)

        #Show the dialog.
        server_list_dialog.exec_()

        #It's possible that the user will delete all of the servers. It's not clear how to cleanly handle this case.
        #We choose to give the user a choice to fix the situation.
        while not ServerConfigurations.server_list:
            #No servers?
            message_text = "Guru needs a Sage server configured in order to evaluate cells. " \
                            "Add a Sage server configuration in the server configuration dialog?"
            response = QMessageBox.question(self, "Sage Not Configured", message_text, QMessageBox.Yes, QMessageBox.No)
            if response == QMessageBox.No:
                return
            server_list_dialog.exec_()

        #Execution only reaches this point if there exists a server.
        server_name = server_list_dialog.ServerListView.currentItem().text()
        if wsc:
            new_config = ServerConfigurations.getServerByName(server_name)
            try:
                wsc.useServerConfiguration(new_config)
            except Exception as e:
                QMessageBox.critical(self, "Error Switching Servers", "Could not switch servers:\n%s" % e.message)
Beispiel #8
0
    def promptInputPrevNext(self, prev):
        """
        TOWRITE

        :param `prev`: TOWRITE
        :type `prev`: bool
        """
        if self.promptInputList:  # if(promptInputList.isEmpty())
            if prev:
                QMessageBox.critical(self, self.tr("Prompt Previous Error"), self.tr("The prompt input is empty! Please report this as a bug!"))
            else:
                QMessageBox.critical(self, self.tr("Prompt Next Error"), self.tr("The prompt input is empty! Please report this as a bug!"))
            qDebug("The prompt input is empty! Please report this as a bug!")

        else:
            if prev:
                self.promptInputNum -= 1  # promptInputNum--;
            else:
                self.promptInputNum += 1  # promptInputNum++;
            maxNum = len(self.promptInputList)  # int maxNum = promptInputList.size();
            if self.promptInputNum < 0:
                self.promptInputNum = 0
                self.mainWin.prompt.setCurrentText("")
            elif self.promptInputNum >= maxNum:
                self.promptInputNum = maxNum
                self.mainWin.prompt.setCurrentText("")
            else:
                self.mainWin.prompt.setCurrentText(self.promptInputList[self.promptInputNum])
Beispiel #9
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)

        self.setWindowIcon(QIcon(':/ifmon.png'))

        try:
            self.model = BandwidthTableModel(self)
        except dberrors.OperationalError as e:
            QMessageBox.critical(self, 'Database Error',
                    'Could not access database.\nERROR: %s' % e)
            sys.exit(QApplication.exit())

        self.tableView.setModel(self.model)
        self.tableView.horizontalHeader().setResizeMode(QHeaderView.Stretch)
        self.tableView.horizontalHeader().setResizeMode(0, QHeaderView.ResizeToContents)
        self.tableView.setAlternatingRowColors(True)

        self.dateFrom.setDate(self.model.settings.start)
        self.dateTo.setDate(self.model.settings.start + timedelta(days=29))
        self.updateTotal()

        self.actionAbout.triggered.connect(self.about)

        self.timer = QTimer()
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.updateUsage)
        self.timer.start()
    def preSupprVerification(self, index):
        u"""Vérification à effectuer avant d'autoriser à supprimer un item
        
        Renvoit False si la suppression est interdite
        
        """
        sql = """
          SELECT COUNT(*)
          FROM absence
          WHERE id_intervenant=""" + str(index.sibling(index.row(), 0).data())
        req = QSqlQuery()
        if req.exec_(sql):
            req.next()
            nbAbsences = req.record().value(0)
            if nbAbsences != 0:
                pl = ""
                if nbAbsences != 1:
                    pl = "s"
                QMessageBox.critical(self, "Impossible de suppprimer",
                    u"L'intervenant a encore " + str(nbAbsences) +
                    u" absence" + pl + u" enregistrée" + pl + "<br />" +
                    u"Il faut les supprimer avant")
                # TODO trouver un moyen de setter l'onglet de l'application
                # self._ui.tabWidget.setCurrentIndex(1)
                return False
        # TODO gérer le else, au moins logger quelque chose

        return True
Beispiel #11
0
    def submit_data(self):
        self._model.insertRow(0)
        data = self.extract_input()
        for key,val in data.items():
            self._model.setData(self._model.index(0, self.column[key]), val)
        # try to commit a record
        if not self._model.submitAll():
            self.log.error(self._model.lastError().text())
            message = unicode("Erro de transação\n\n""Não foi possível salvar no banco de dados".decode('utf-8'))
            QMessageBox.critical(self, "Seareiros - Cadastro de Atividade", message)
            return False
        else:
            # successfully added an associate, adding it's activities
            activities = self.extract_activities_input()
            error = False
            if len(activities) > 0:
                associate_id = self.get_added_record().value("id")
                for id in activities:
                    self._act_model.insertRow(0)
                    self._act_model.setData(self._act_model.index(0, 0), associate_id)
                    self._act_model.setData(self._act_model.index(0, 1), id)
                    ok = self._act_model.submitAll()
                    if not ok:
                        error = True
                        self.log.error(self._act_model.lastError().text())
            if not error:
                message = unicode("Sucesso!\n\n""O associado foi salvo com êxito no banco de dados".decode('utf-8'))
                QMessageBox.information(self, "Seareiros - Cadastro de Associado", message)
            else:
                message = unicode("Erro\n\n""Associado cadastrado, "
                                  "porém ocorreu um problema ao salvar suas atividades".decode('utf-8'))
                QMessageBox.warning(self, "Seareiros - Cadastro de Associado", message)

            return True
Beispiel #12
0
 def setup_model(self):
     db = Db_Instance("form_book").get_instance()
     if not db.open():
         self.log.error(db.lastError().text())
         message = unicode("Erro de conexão\n\n" "Banco de dados indisponível".decode("utf-8"))
         QMessageBox.critical(self, "Seareiros - Cadastro de Livro", message)
     else:
         # book
         self._model = QSqlTableModel(self, db=db)
         self._model.setTable("book")
         # subject
         self._subject_model = QSqlTableModel(self, db=db)
         self._subject_model.setTable("subject")
         self._subject_model.select()
         # author
         self._author_model = QSqlTableModel(self, db=db)
         self._author_model.setTable("author")
         self._author_model.select()
         # sauthor
         self._s_author_model = QSqlTableModel(self, db=db)
         self._s_author_model.setTable("s_author")
         self._s_author_model.select()
         # publisher
         self._publisher_model = QSqlTableModel(self, db=db)
         self._publisher_model.setTable("publisher")
         self._publisher_model.select()
         # book subjects
         self._book_in_subj_model = QSqlTableModel(self, db=db)
         self._book_in_subj_model.setTable("book_in_subject")
Beispiel #13
0
    def confirmSubs(self, playersIn, playersOut, datetime):
        week = gameinfo.weekNum(datetime) + 1
        date = gameinfo.weekToDate(week).date()

        html = render_to_string('subs_email.html', {'team': self.team,
                                                    'players_in': playersIn,
                                                    'players_out': playersOut,
                                                    'week': week,
                                                    'date': date}
                                )

        settings = QSettings()
        if settings.contains('SMTP/Server'):
            smtp_server = settings.value('SMTP/Server')
        else:
            smtp_server = None
        
        if not smtp_server:
            QMessageBox.critical(self, "Email Error", "Please add an SMTP server in settings.")
        else:
            email = HTMLEmail([self.team.email],
                              "*****@*****.**",
                              "Fantasy Football League",
                              bcc='*****@*****.**')
            email.sendMail("Sub Confirmation", html, smtp_server)
Beispiel #14
0
    def accept(self):
        players = self.playerSelections()
        self.team.team_name = self.teamNameEdit.text()
        self.team.email = unicode(self.emailEdit.text()).lower()

        if self.validTeam(players):
            playersOut = [player for player in self.team_players if player not in players]
            subs_made = len(playersOut)
            if subs_made > 0:
                if self.team.subs_used + subs_made > config.MAX_SUBS:
                    QMessageBox.critical(self, "Substitution Error",
                                         "This manager has insufficient substitutions remaining")
                    self.setCurrentPlayers()
                else:
                    playersIn = [player for player in players if player not in self.team_players]
                    form = confirmSubsDialog(playersOut, playersIn, self)
                    if form.exec_():
                        self.team.subs_used += subs_made
                        self.team.total_cost = self.total_cost
                        self.team.formation = self.formation
                        self.team.squad.substitute(playersIn, playersOut, form.datetime)
                        self.confirmSubs(playersIn, playersOut, form.datetime)
                        QDialog.accept(self)
                    else:
                        self.setCurrentPlayers()
            else:
                QDialog.accept(self)

        self.team.save()
Beispiel #15
0
def merge_pdf(destination=None, pdf_files=None):
	try:
		output = PdfFileWriter()
		inputs = []
		for pdf_file in pdf_files:
			reader_pdf_file = PdfFileReader(open(pdf_file, 'rb'))
			inputs.append(reader_pdf_file)

		for input_pdf in inputs:
			for page in input_pdf.pages:
				output.addPage(page)

		output_stream = open(destination, 'wb')
		output.write(output_stream)
		output_stream.close

		# merger = PdfFileMerger()
		# for pdf_file in pdf_files:
		# 	merger.append(open(pdf_file, 'rb'))
		
		# merger.write(open(destination), 'wb')

		QMessageBox.information(main, 'Success!', 'PDFs have been merged to ' + destination )
	except:
		QMessageBox.critical(main, 'Error!', 'Critical error occured.\n\n%s' % traceback.format_exc())
Beispiel #16
0
 def on_addTagsButton_clicked(self):
     if len(self.tagsInput.text()) == 0:
         QMessageBox.critical(self, u'错误', u'请至少输入一个类别')
     else:
         tags = set(self.tagsInput.text().split())
         self.selectedTag.addItems(list(tags-set(self.tags)))
         self.tags.extend(tags)
Beispiel #17
0
    def addServer(self):
        dialog = EditSageServerDlg(self)

        name_collision = True #The while loop needs to run at least once.
        while name_collision:
            if not dialog.exec_():
                #The user clicked cancel.
                return

            #Fetch the data.
            new_server = dialog.getServerConfiguration()

            #Check to see if the name is in use.
            name_collision = ServerConfigurations.getServerByName(new_server["name"])
            #If the user set the name to a new name that is already in use, name_collision will
            #not be None. The loop will continue and the dialog reopened.
            if name_collision:
                #The name is already in use.
                QMessageBox.critical(self, "Name already exists", "A server configuration already exists with that name. Choose a different name.")
                dialog.txtName.selectAll()
                dialog.txtName.setFocus()

        #Add the server configuration to the list.
        ServerConfigurations.addServer(new_server)
        item = QListWidgetItem(new_server["name"], self.ServerListView)
        self.ServerListView.setCurrentItem(item)
        if new_server["default"]:
            self.updateListViewDefault()
Beispiel #18
0
 def startApplication(self):
     self.m_server = QLocalServer()
     if self.m_server.listen(self.applicationName()):
         self.m_server.newConnection.connect(self.getNewConnection)
         self.mainWindow.show()
     else:
         QMessageBox.critical(None, self.tr("Error"), self.tr("Error listening the socket."))
Beispiel #19
0
    def loadFile(self, file_name):
        #Which MainWindow object we create the new worksheet in depends on if loadFile()
        #is fired on a welcome page or not. Returns True on success.

        if self.isWelcome:
            #Use the current MainWindow object to create the worksheet.
            self.hideWelcome()
            #Set the working filename
            self.file_name = file_name
            #We set the window title.
            self.setUniqueWindowTitle()
            #Open the worksheet in the webView.
            try:
                self.webViewController().openWorksheetFile(file_name)
            except Exception as e:
                QMessageBox.critical(self, "File Open Error", "Could not open the file:\n%s" % e.message)
                self.showWelcome()
                return False

            #Set the dirty flag handler.
            self.dirty(False)
            self.connectWorksheetSignals()
            self.updateRecentFilesMenu()
        else:
            #Create a new MainWindow object to use for the new worksheet.
            main_window = MainWindow(file_name=file_name)
            main_window.show()

            main_window.activateWindow()
            main_window.raise_()

        return True
Beispiel #20
0
 def check_barcode(self, txt):
     if len(txt) == self.edBarcode.maxLength():
         db = Db_Instance("obook_barcode_search").get_instance()
         try:
             if db.open():
                 query = QSqlQuery(db)
                 query.prepare("SELECT * FROM book WHERE barcode = :barcode")
                 query.bindValue(":barcode", txt)
                 query.exec_()
                 if query.next():
                     self.add_book_from_record(query.record())
                     self.edBarcode.clear()
                 else:
                     raise RecordNotFoundException
             else:
                 raise DbUnavailableException
         except RecordNotFoundException:
             message = unicode("Código de barra inválido!\n\n"""
                           "O código informado não corresponde a nenhum livro cadastrado".decode('utf-8'))
             QMessageBox.critical(self, "Seareiros - Livraria", message)
         except DbUnavailableException:
             self.log.error(db.lastError().text())
             message = unicode("Erro de conexão\n\n""Banco de dados indisponível".decode('utf-8'))
             QMessageBox.critical(self, "Seareiros - Livraria", message)
         self.edBarcode.setFocus()
  def importNominalPositions(self):
    fn, filt = QFileDialog.getOpenFileName(self, "Open Excel File", "",
        "Excel Files(*.xls)")
    if not fn:
      return
    try:
      wb = xlrd.open_workbook(fn)
    except:
      QMessageBox.critical(self, "Invalid Excel file", "Pyrite could not "
          "parse the selected Excel file. Make sure it is the .xls not "
          ".xlsx format.")
      return

    dlg = ExcelRegionSelector(self, wb.sheet_names())
    dlg.exec_()
    if dlg.result() != QDialog.Accepted:
      return
    xRow = dlg.xRow
    xCol = dlg.xCol
    yRow = dlg.yRow
    yCol = dlg.yCol
    count = dlg.count
    sheetName = dlg.sheetName

    sheet = wb.sheet_by_name(sheetName)
    # load the nominal positions
    for i in range(count):
      pos = (float(sheet.cell(xRow + i, xCol).value),
          float(sheet.cell(yRow + i, yCol).value))
      self._nominalData.append(pos)
    self._nominalDataLoaded = True
    self.updateNominalPositionPreview()
    self.updateGenerateEnabled()
Beispiel #22
0
 def submit_data(self):
     # I should block empty orders I guess
     if len(self._product_list) == 0:
         message = unicode(
             "Venda vazia!\n\n" "" "É necessário adicionar um produto antes de concluir uma venda".decode("utf-8")
         )
         QMessageBox.critical(self, "Seareiros - Vendas do Bazar", message)
         self.edProductName.setFocus()
         return False
     data = self.extract_input()
     # filling a product order
     self._model.insertRow(0)
     for key, val in data.items():
         self._model.setData(self._model.index(0, self.column[key]), val)
     order_id = submit_and_get_id(self, self._model, self.log)
     if order_id:
         # order creation success, placing items
         error = False
         for item in self._product_list:
             product_name = item[0]
             product_price = item[1]
             product_quantity = item[2]
             self._items_model.insertRow(0)
             self._items_model.setData(self._items_model.index(0, 1), order_id)
             self._items_model.setData(self._items_model.index(0, 2), product_name)
             self._items_model.setData(self._items_model.index(0, 3), product_price)
             self._items_model.setData(self._items_model.index(0, 4), product_quantity)
             ok = self._items_model.submitAll()
             if not ok:
                 error = True
                 break
         if error:
             self.log.error(self._items_model.lastError().text())
             message = unicode(
                 "Erro\n\n"
                 "Venda registrada e contabilizada, porém ocorreu um problema e"
                 " não será possível visualizar seus itens.".decode("utf-8")
             )
             QMessageBox.warning(self, "Seareiros - Vendas do Bazar", message)
             return False
         else:
             # all went fine
             # retrieving some brief info of the order to display at the main window
             if "associate" in data:
                 desc = "Venda do bazar no valor de R$ %s para %s" % (
                     self._locale.toString(data["total"], "f", 2).replace(".", ""),
                     self.lblNickname.text(),
                 )
             else:
                 desc = "Venda do bazar no valor de R$ %s" % self._locale.toString(data["total"], "f", 2).replace(
                     ".", ""
                 )
             if not log_to_history(self._model.database(), "venda_bazar", order_id, desc):
                 self.log.error(self._model.lastError().text())
             message = unicode("Sucesso!\n\n" "Venda concluída.".decode("utf-8"))
             QMessageBox.information(self, "Seareiros - Vendas do Bazar", message)
             return True
     # failed to insert a row
     return False
 def wrapper(self, *args, **kwargs):
     try:
         return f(self, *args, **kwargs)
     except Exception as e:
         parent = self if isinstance(self, QWidget) else None
         QMessageBox.critical(parent, u'An error occurred',
             u'An error occurred:\n{0}'.format(e))
         raise
Beispiel #24
0
 def _onStart(self):
     outputdir = self._txt_outputdir.path()
     if not outputdir:
         QMessageBox.critical(self, 'Start', 'Missing output directory')
         return
     max_workers = self._spn_workers.value()
     overwrite = self._chk_overwrite.isChecked()
     self.start(outputdir, overwrite, max_workers)
Beispiel #25
0
 def authenticate(self):
     password = self.pwd.text()
     uid = self.email.text()
     savecreds = self.savecreds.isChecked()
     if QCoreApplication.instance().authenticate(uid, password, savecreds):
         self.accept()
     else:
         QMessageBox.critical(self, "Wrong Password",
             "The user ID and password entered do not match.")
Beispiel #26
0
 def openDocumentFile(self, filePath):
     
     try:
         # TODO: Improve error messages, e.g. to include line numbers.
         doc = DocumentFileFormat.readDocument(filePath)
         
     except Exception, e:
         message = 'File open failed.\n\n' + str(e)
         QMessageBox.critical(self, '', message)
 def doubleClicked(self, vobj):
     doc = FreeCADGui.getDocument(vobj.Object.Document)
     if not doc.getInEdit():
         doc.setEdit(vobj.Object.Name)
     else:
         from PySide.QtGui import QMessageBox
         message = 'Active Task Dialog found! Please close this one before opening  a new one!'
         QMessageBox.critical(None, "Error in tree view", message)
         FreeCAD.Console.PrintError(message + '\n')
     return True
Beispiel #28
0
 def save(self):
     file_name = QFileDialog.getSaveFileName(self)[0]
     if file_name != '':
         try:
             with open(file_name, mode='wt') as out_file:
                 text = self._text_edit.toPlainText()
                 out_file.write(text)
         except:
             QMessageBox.critical(self, self.tr('Error'),
                                        self.tr('Could not save file'))
Beispiel #29
0
 def open(self):
     file_name = QFileDialog.getOpenFileName(self)[0]
     if file_name != '':
         try:
             with open(file_name, mode='rt') as in_file:
                 text = in_file.read()
                 self._text_edit.setText(text)
         except:
             QMessageBox.critical(self, self.tr('Error'),
                                        self.tr('Could not open file'))
Beispiel #30
0
 def setup_model(self):
     db = Db_Instance("form_associate").get_instance()
     if not db.open():
         self.log.error(db.lastError().text())
         message = unicode("Erro de conexão\n\n""Banco de dados indisponível".decode('utf-8'))
         QMessageBox.critical(self, "Seareiros - Cadastro de Associado", message)
     else:
         self._model = QSqlRelationalTableModel(self, db=db)
         self._model.setTable("associate")
         self._act_model = QSqlRelationalTableModel(self, db=db)
         self._act_model.setTable("associate_in_activity")
Beispiel #31
0
    def toggleSniffing(self):
        """
        This starts and stops sniffing for a specific sniffer tab.
        Instances of :class:`~src.ItemAdderThread.ItemAdderThread` and :class:`~src.SnifferProcess.SnifferProcess` are
        used to gather and display data.
        """

        if self.CANData is None:
            QMessageBox.critical(
                Globals.ui.tabWidgetMain,
                Strings.snifferTabElementInterfaceMissingMessageBoxTitle,
                Strings.snifferTabElementInterfaceMissingMessageBoxText,
                QMessageBox.Ok)
            return

        # Stop the thread and process
        if self.active:
            self.terminateThreads()

            # If too much data was received process it now
            if self.tooMuchData:
                progressDialog = Toolbox.Toolbox.getWorkingDialog(
                    Strings.snifferTabElementDialogProcessing)
                progressDialog.open()
                try:
                    self.packetTableModel.clear()
                    for listIdx in range(len(self.valueListsToProcess)):
                        if listIdx % 1500 == 0:
                            QtCore.QCoreApplication.processEvents()
                        self.addPacket(self.valueListsToProcess[listIdx],
                                       ignorePacketRate=True)
                finally:
                    progressDialog.close()
                    self.packetTableView.setEnabled(True)
                    self.tooMuchData = False

        # Start sniffer process, item generator process and item adder thread
        else:

            # Reset the flag
            self.sharedSnifferEnabledFlag = Value("i", 1)

            snifferReceivePipe, snifferSendPipe = Pipe()

            # First start the ItemAdderThread...
            self.itemAdderThread = ItemAdderThread.ItemAdderThread(
                snifferReceivePipe,
                self.packetTableModel,
                self.rawData,
                useTimestamp=True)

            self.itemAdderThread.appendRow.connect(self.addPacket)
            self.itemAdderThread.start()

            # ... then start the SnifferProcess
            self.snifferProcess = SnifferProcess.SnifferProcess(
                snifferSendPipe,
                self.sharedSnifferEnabledFlag,
                self.tabName,
                CANData=self.CANData)
            self.snifferProcess.start()

            SnifferTabElement.amountThreadsRunning += 1
            self.updateStatusBar()
            self.tabWidget.buttonSniff.setText(
                Strings.snifferTabElementSniffingButtonEnabled)

            self.active = True
            self.CANData.active = True
            self.toggleActive()
            self.logger.info(Strings.snifferTabElementSniffingStarted)
Beispiel #32
0
        print("Too many arguments - Exiting")
        sys.exit(1)
    elif len(sys.argv) == 2:
        if sys.argv[1] != "--debug":
            print("Unknown argument - Exiting")
            sys.exit(1)
        else:
            config.init_config(True)
    else:
        config.init_config()

    langmodule.setuplang()

    if not utilities.isAVGDRunning():
        QMessageBox.critical(None, langmodule.attention,
                             langmodule.avgnotrunning,
                             QMessageBox.Ok | QMessageBox.Default,
                             QMessageBox.NoButton)
        #print(langmodule.avgnotrunning)
        exit(1)

    signal.signal(signal.SIGALRM, avgstopped_handler)
    mainpid = os.getpid()

    theApp = theApplication()
    theApp.theWindow.show()
    gc.enable()

    try:
        subprocess.call([config.daemonMonitor, "--start", str(mainpid)])
    except Exception as exc:
        QMessageBox.critical(None, langmodule.attention,
Beispiel #33
0
def avgstopped_handler(signum, frame):
    QMessageBox.critical(None, langmodule.attention, langmodule.avgStopped,
                         QMessageBox.Ok | QMessageBox.Default,
                         QMessageBox.NoButton)
    app.exit(1)
Beispiel #34
0
 def errorMsg(self, msg="Something went wrong !"):
     QMessageBox.critical(self, "Error", msg)
     return True
Beispiel #35
0
    def send_tx(self, amount, address, payment_id, priority, mixin, tx_desc,
                save_address, sweep_all):
        if not payment_id and not address.startswith("Sumi"):
            result = QMessageBox.question(self.ui, "Sending Coins Without Payment ID?", \
                                      "Are you sure to send coins without Payment ID?", \
                                       QMessageBox.Yes | QMessageBox.No, defaultButton=QMessageBox.No)
            if result == QMessageBox.No:
                return

        if sweep_all:
            result = QMessageBox.question(self.ui, "Sending all your coins?", \
                                      "This will send all your coins to target address.<br><br>Are you sure you want to proceed?", \
                                      QMessageBox.Yes | QMessageBox.No, defaultButton=QMessageBox.No)
            if result == QMessageBox.No:
                return

        wallet_password, result = self._custom_input_dialog(self.ui, \
                        "Wallet Password", "Please enter wallet password:"******"Incorrect Wallet Password",
                                "Wallet password is not correct!")
            return

        self.on_wallet_send_tx_start_event.emit()
        amount = int(amount * COIN)

        if sweep_all:
            _, _, per_subaddress = self.ui.wallet_rpc_manager.rpc_request.get_balance(
            )
            subaddr_indices = []
            for s in per_subaddress:
                if s['unlocked_balance'] > 0:
                    subaddr_indices.append(s['address_index'])
            ret = self.ui.wallet_rpc_manager.rpc_request.transfer_all(
                address, payment_id, priority, mixin, 0, subaddr_indices)
        else:
            ret = self.ui.wallet_rpc_manager.rpc_request.transfer_split(amount, \
                                                address, payment_id, priority, mixin)

        if ret['status'] == "ERROR":
            self.on_wallet_send_tx_completed_event.emit(json.dumps(ret))
            self.app_process_events()
            if ret['message'] == "tx not possible":
                msg = "Not possible to send coins. Probably, there is not enough money left for fee."
            else:
                msg = ret['message']

            QMessageBox.critical(self.ui, \
                            'Error Sending Coins',\
                            "<b>ERROR</b><br><br>" + msg)

        if ret['status'] == "OK":
            if tx_desc:
                # set the same note for all txs:
                notes = []
                for i in range(len(ret['tx_hash_list'])):
                    notes.append(tx_desc)
                self.ui.wallet_rpc_manager.rpc_request.set_tx_notes(
                    ret['tx_hash_list'], notes)

            self.on_wallet_send_tx_completed_event.emit(json.dumps(ret))
            self.app_process_events()

            msg = "<b>Coins successfully sent in the following transaction(s):</b><br><br>"
            for i in range(len(ret['tx_hash_list'])):
                if sweep_all:
                    msg += "- Transaction ID: %s <br>" % (
                        ret['tx_hash_list'][i])
                else:
                    msg += "- Transaction ID: %s <br>  - Amount: %s <br>  - Fee: %s <br><br>" % (ret['tx_hash_list'][i], \
                                                        print_money2(ret['amount_list'][i]), \
                                                        print_money2(ret['fee_list'][i]))
            QMessageBox.information(self.ui, 'Coins Sent', msg)
            self.ui.update_wallet_info()

            if save_address:
                desc, _ = self._custom_input_dialog(self.ui, \
                        'Saving Address...', \
                        "Address description/note (optional):")
                ret = self.ui.wallet_rpc_manager.rpc_request.add_address_book(address, \
                                                                              payment_id, desc)
                if ret['status'] == "OK":
                    if self.ui.wallet_info.wallet_address_book:
                        address_entry = {
                            "address": address,
                            "payment_id": payment_id,
                            "description": desc[0:200],
                            "index": ret["index"]
                        }
                        self.ui.wallet_info.wallet_address_book.append(
                            address_entry)

                    QMessageBox.information(self.ui, "Address Saved", \
                                            "Address (and payment ID) saved to address book.")
Beispiel #36
0
class Hub(QObject):
    current_block_height = 0

    def __init__(self, app):
        super(Hub, self).__init__()
        self.app = app

    def setUI(self, ui):
        self.ui = ui

    def setNewWalletUI(self, new_wallet_ui):
        self.new_wallet_ui = new_wallet_ui

    @Slot()
    def import_wallet(self):
        dlg = QFileDialog(self.new_wallet_ui, "Select Import Wallet File")
        dlg.setFileMode(QFileDialog.ExistingFile)
        wallet_filename = None
        if dlg.exec_():
            wallet_filename = dlg.selectedFiles()[0]
        else:
            return

        new_wallet_file = os.path.join(wallet_dir_path,
                                       self.get_new_wallet_file_name())
        if wallet_filename:
            wallet_key_filename = wallet_filename + '.keys'

            if not os.path.exists(wallet_key_filename):
                QMessageBox.warning(self.new_wallet_ui, \
                    'Import Wallet',\
                     """Error: Key file does not exist!<br>
                     Are you sure to select correct wallet file?<br><br>
                     Hint: Wallet file often ends with .bin""")
                return False
            try:
                copy2(wallet_filename,
                      os.path.join(wallet_dir_path, new_wallet_file))
                copy2(wallet_key_filename, os.path.join(wallet_dir_path, \
                                                           new_wallet_file + '.keys'))
            except IOError, err:
                self._detail_error_msg("Importing Wallet",
                                       "Error importing wallet!", str(err))
                self.ui.reset_wallet()
                return False

        if not os.path.exists(new_wallet_file):
            return False

        wallet_password = None
        while True:
            wallet_password, result = self._custom_input_dialog(self.new_wallet_ui, \
                "Wallet Password", "Enter password of the imported wallet:", QLineEdit.Password)
            if result:
                if not wallet_password:
                    QMessageBox.warning(self.new_wallet_ui, \
                            'Wallet Password',\
                             "You must provide password to open the imported wallet")
                else:
                    break
            else:
                return False

        self.on_new_wallet_show_progress_event.emit('Importing wallet...')
        self.app_process_events()

        ret = self.ui.wallet_rpc_manager.rpc_request.open_wallet(
            os.path.basename(new_wallet_file), wallet_password)

        if ret['status'] == "ERROR":
            error_message = ret['message']
            QMessageBox.critical(self.new_wallet_ui, \
                    'Error Importing Wallet',\
                    "Error: %s" % error_message)
            self.ui.reset_wallet()
            return False

        self.current_block_height = 0  # reset current wallet block height

        self.ui.wallet_info.wallet_password = hashlib.sha256(
            wallet_password).hexdigest()
        self.ui.wallet_info.wallet_filepath = new_wallet_file
        self.ui.wallet_info.is_loaded = True
        self.ui.wallet_info.save()

        self.show_wallet_info()
        return True
Beispiel #37
0
    def open_existing_wallet(self):
        current_wallet_password, result = self._custom_input_dialog(self.ui, \
                        "Wallet Password", "Current wallet password:"******"Incorrect Wallet Password",
                                "Wallet password is not correct!")
            return

        dlg = QFileDialog(self.ui, "Open Wallet File", wallet_dir_path,
                          "Wallet files (*.bin)")
        dlg.setFileMode(QFileDialog.ExistingFile)
        wallet_filename = None
        if dlg.exec_():
            wallet_filename = dlg.selectedFiles()[0]
        else:
            self.on_open_existing_wallet_complete_event.emit()
            return
        if not wallet_filename:
            return

        wallet_key_filename = wallet_filename + '.keys'
        if not os.path.exists(wallet_key_filename):
            QMessageBox.warning(self.ui, \
                'Open Wallet File',\
                 """Error: Key file does not exist!<br>
                 Please make sure to select correct wallet file""")
            return

        if os.path.normpath(os.path.dirname(
                wallet_filename)) != os.path.normpath(wallet_dir_path):
            QMessageBox.warning(self.ui, \
                'Open Wallet File',\
                 """Error: Only wallet files at default location are available for opening.<br>
                 You can import wallet via 'New... > Import' feature instead.""")
            return

        if os.path.basename(wallet_filename) == os.path.basename(
                self.ui.wallet_info.wallet_filepath):
            QMessageBox.warning(self.ui, \
                'Open Wallet File',\
                 """Error: Cannot open the same wallet!""")
            return

        while True:
            wallet_password, result = self._custom_input_dialog(self.ui, \
                "Wallet Password", "Enter wallet password for opening:", QLineEdit.Password)
            if result:
                if not wallet_password:
                    QMessageBox.warning(self.ui, \
                            'Wallet Password',\
                             "You must provide password to open wallet")
                    continue
                else:
                    break
            else:
                return

        self.ui.stop_update_wallet_info_timer()
        self.on_open_existing_wallet_start_event.emit()
        current_wallet_filename = self.ui.wallet_info.wallet_filepath
        try:
            ret = self.ui.wallet_rpc_manager.rpc_request.stop_wallet()
            if ret['status'] == "ERROR":
                error_message = ret['message']
                QMessageBox.critical(self.ui, \
                        'Error Closing Current Wallet',\
                        "Error: %s" % error_message)
                raise Exception(error_message)

            self.ui.wallet_rpc_manager.set_ready(False)
            self.ui.run_wallet_rpc()
            while not self.ui.wallet_rpc_manager.is_ready():
                self.app_process_events(0.1)

            ret = self.ui.wallet_rpc_manager.rpc_request.open_wallet(
                os.path.basename(wallet_filename), wallet_password)
            if ret['status'] == "ERROR":
                error_message = ret['message']
                QMessageBox.critical(self.ui, 'Error Opening Wallet',
                                     error_message)
                raise Exception(error_message)

            self.ui.reset_wallet(False)
            self.ui.wallet_info.wallet_password = hashlib.sha256(
                wallet_password).hexdigest()
            self.ui.wallet_info.wallet_filepath = wallet_filename
            self.ui.wallet_info.is_loaded = True
            self.ui.wallet_info.save()

            while not self.ui.wallet_rpc_manager.is_ready():
                self.app_process_events(0.1)
        except Exception, err:
            log(str(err), LEVEL_ERROR)
            ret = self.ui.wallet_rpc_manager.rpc_request.open_wallet(
                os.path.basename(current_wallet_filename),
                current_wallet_password)
            self.ui.wallet_info.wallet_password = hashlib.sha256(
                current_wallet_password).hexdigest()
            self.ui.wallet_info.wallet_filepath = current_wallet_filename
            self.ui.wallet_info.is_loaded = True
            self.ui.wallet_info.save()
            self.on_open_existing_wallet_complete_event.emit()
Beispiel #38
0
    def change_wallet_password(self):
        old_password, result = self._custom_input_dialog(self.ui, \
                        "Wallet Password", "Enter current wallet password:"******"", "")
            QMessageBox.warning(self.ui, "Incorrect Wallet Password",
                                "Wallet password is not correct!")
            return

        new_password = None
        while True:
            new_password, result = self._custom_input_dialog(self.ui, \
                    "Wallet New Password", "Set new wallet password:"******"Password must contain at least 1 character [a-zA-Z] or number [0-9]\
                                    <br>or special character like !@#$%^&* and not contain spaces"                                                                                                  )
                    continue

                confirm_password, result = self._custom_input_dialog(self.ui, \
                    'Wallet New Password', \
                    "Confirm new wallet password:"******"Confirm password does not match new password!\
                                             <br>Please re-enter password"                                                                          )
                        continue
                    else:
                        break
                else:
                    return
            else:
                return

        if new_password is not None:
            if new_password == old_password:
                QMessageBox.information(
                    self.ui, "Wallet Password",
                    "New wallet password is the same as old one. Nothing changed!"
                )
                return

            ret = self.ui.wallet_rpc_manager.rpc_request.change_wallet_password(
                old_password, new_password)
            if ret['status'] == "ERROR":
                error_message = ret['message']
                QMessageBox.critical(self.ui, \
                        'Error Changing Wallet Password',\
                        "Error: %s" % error_message)
                return

            self.ui.wallet_info.wallet_password = hashlib.sha256(
                new_password).hexdigest()
            self.ui.wallet_info.save()

            QMessageBox.information(
                self.ui, "Wallet Password Changed",
                "Wallet password successfully changed!<br>Please make sure you never lose it."
            )
Beispiel #39
0
    def restore_deterministic_wallet(self,
                                     mnemonic_seed,
                                     restore_height=0,
                                     seed_offset_passphrase=u''):
        from settings.electrum_words import find_seed_language
        language_name, english_seed = find_seed_language(mnemonic_seed)
        if language_name is None:
            QMessageBox.critical(self.new_wallet_ui, \
                    'Error Restoring Wallet',\
                    """ERROR: Invalid mnemonic seed!<br>
                    Seed words missing, incorrect or not match any language<br><br>
                    NOTE: Sumokoin mnemonic seed must be a list of 26 (valid) words""")
            return

        if restore_height > 0:
            ret = QMessageBox.warning(self.new_wallet_ui, \
                    'Restore Wallet',\
                     """Are you sure to restore wallet from blockchain height# %d?<br><br>
                     WARNING: Incorrect height# will lead to incorrect balance and failed transactions!""" % restore_height, \
                     QMessageBox.Yes|QMessageBox.No, defaultButton = QMessageBox.No)
            if ret == QMessageBox.No:
                return

        wallet_password = None
        try:
            has_password = False
            while True:
                wallet_password, result = self._custom_input_dialog(self.new_wallet_ui, \
                        "Wallet Password", "Set new wallet password:"******"Password must contain at least 1 character [a-zA-Z] or number [0-9]\
                                        <br>or special character like !@#$%^&* and not contain spaces"                                                                                                      )
                        continue

                    confirm_password, result = self._custom_input_dialog(self.new_wallet_ui, \
                        'Wallet Password', \
                        "Confirm wallet password:"******"Confirm password does not match password!\
                                                 <br>Please re-enter password"                                                                              )
                        else:
                            has_password = True
                            break
                    else:
                        break
                else:
                    break

            if has_password:
                self.on_new_wallet_show_progress_event.emit(
                    "Restoring wallet...")
                self.app_process_events(0.1)
                wallet_filename = self.get_new_wallet_file_name()
                wallet_filepath = os.path.join(wallet_dir_path,
                                               wallet_filename)

                while not self.ui.wallet_rpc_manager.is_ready():
                    self.app_process_events(0.1)
                ret = self.ui.wallet_rpc_manager.rpc_request.restore_deterministic_wallet(
                    english_seed, restore_height, wallet_filename,
                    seed_offset_passphrase, wallet_password, "English")
                if ret['status'] == "ERROR":
                    error_message = ret['message']
                    QMessageBox.critical(self.new_wallet_ui, \
                            'Error Restoring Wallet',\
                            "Error: %s" % error_message)
                    raise Exception("Error restoring wallet: %s" %
                                    error_message)

                ret = self.ui.wallet_rpc_manager.rpc_request.set_wallet_seed_language(
                    language_name)
                if ret['status'] == "ERROR":
                    error_message = ret['message']
                    QMessageBox.critical(self.new_wallet_ui, \
                            'Error Restoring Wallet',\
                            "Error setting seed language: %s" % error_message)
                    raise Exception("Error restoring wallet: %s" %
                                    error_message)

                self.ui.wallet_info.wallet_filepath = wallet_filepath
                self.ui.wallet_info.wallet_password = hashlib.sha256(
                    wallet_password).hexdigest()
                self.ui.wallet_info.is_loaded = True
                self.ui.wallet_info.save()

                self.current_block_height = 0  # reset current wallet block height
                self.ui.wallet_rpc_manager.set_ready(False)
                while not self.ui.wallet_rpc_manager.is_ready():
                    self.app_process_events(1)
                    h = self.ui.wallet_rpc_manager.get_block_height()
                    if h > 0:
                        block_hash = self.ui.wallet_rpc_manager.get_block_hash(
                        )
                        self.on_new_wallet_update_processed_block_height_event.emit(
                            h, self.ui.current_height, block_hash)

                self.show_wallet_info()
        except Exception, err:
            log(str(err), LEVEL_ERROR)
            self.ui.reset_wallet(delete_files=False)
            return
Beispiel #40
0
    def create_new_wallet(self):
        wallet_password = None
        wallet_filepath = ""
        try:
            has_password = False
            while True:
                wallet_password, result = self._custom_input_dialog(self.new_wallet_ui, \
                        "Wallet Password", "Set new wallet password:"******"Password must contain at least 1 character [a-zA-Z] or number [0-9]\
                                        <br>or special character like !@#$%^&* and not contain spaces"                                                                                                      )
                        continue

                    confirm_password, result = self._custom_input_dialog(self.new_wallet_ui, \
                        'Wallet Password', \
                        "Confirm wallet password:"******"Confirm password does not match password!\
                                                 <br>Please re-enter password"                                                                              )
                        else:
                            has_password = True
                            break
                    else:
                        break
                else:
                    break

            if has_password:
                mnemonic_seed_language = "English"
                seed_language_list = [sl[1] for sl in seed_languages]
                list_select_index = 1
                lang, ok = QInputDialog.getItem(
                    self.new_wallet_ui, "Mnemonic Seed Language",
                    "Select a language for wallet mnemonic seed:",
                    seed_language_list, list_select_index, False)
                if ok and lang:
                    for sl in seed_languages:
                        if sl[1] == lang:
                            mnemonic_seed_language = sl[0]
                            break
                else:
                    return

                self.on_new_wallet_show_progress_event.emit(
                    "Creating wallet...")
                self.app_process_events(0.1)
                wallet_filename = self.get_new_wallet_file_name()
                wallet_filepath = os.path.join(wallet_dir_path,
                                               wallet_filename)

                while not self.ui.wallet_rpc_manager.is_ready():
                    self.app_process_events(0.1)
                ret = self.ui.wallet_rpc_manager.rpc_request.create_wallet(
                    wallet_filename, wallet_password, mnemonic_seed_language)
                if ret['status'] == "ERROR":
                    error_message = ret['message']
                    QMessageBox.critical(self.new_wallet_ui, \
                            'Error Creating Wallet',\
                            "Error: %s" % error_message)
                    raise Exception("Error creating wallet: %s" %
                                    error_message)

                self.current_block_height = 0  # reset current wallet block height

                self.ui.wallet_info.wallet_filepath = wallet_filepath
                self.ui.wallet_info.wallet_password = hashlib.sha256(
                    wallet_password).hexdigest()
                self.ui.wallet_info.is_loaded = True
                self.ui.wallet_info.save()

                self.show_wallet_info()
        except Exception, err:
            log(str(err), LEVEL_ERROR)
            self.ui.reset_wallet(delete_files=False)
            self.on_new_wallet_ui_reset_event.emit()
            return
Beispiel #41
0
 def show_error(self, text):
     """
     :return: pops up an error
     """
     QMessageBox.critical(QMessageBox(), "Fail!!",
                          "Please Enter %s properly" % text, QMessageBox.Ok)
 def doubleClicked(self, vobj):
     # Group meshing is only active on active analysis
     # we should make sure the analysis the mesh belongs too is active
     gui_doc = FreeCADGui.getDocument(vobj.Object.Document)
     if not gui_doc.getInEdit():
         # may be go the other way around and just activate the
         # analysis the user has doubleClicked on ?!
         # not a fast one, we need to iterate over all member of all
         # analysis to know to which analysis the object belongs too!!!
         # first check if there is an analysis in the active document
         found_an_analysis = False
         for o in gui_doc.Document.Objects:
             if o.isDerivedFrom("Fem::FemAnalysisPython"):
                 found_an_analysis = True
                 break
         if found_an_analysis:
             if FemGui.getActiveAnalysis() is not None:
                 if FemGui.getActiveAnalysis(
                 ).Document is FreeCAD.ActiveDocument:
                     if self.Object in FemGui.getActiveAnalysis().Group:
                         if not gui_doc.getInEdit():
                             gui_doc.setEdit(vobj.Object.Name)
                         else:
                             FreeCAD.Console.PrintError(
                                 "Activate the analysis this Gmsh FEM "
                                 "mesh object belongs too!\n")
                     else:
                         print(
                             "Gmsh FEM mesh object does not belong to the active analysis."
                         )
                         found_mesh_analysis = False
                         for o in gui_doc.Document.Objects:
                             if o.isDerivedFrom("Fem::FemAnalysisPython"):
                                 for m in o.Group:
                                     if m == self.Object:
                                         found_mesh_analysis = True
                                         FemGui.setActiveAnalysis(o)
                                         print(
                                             "The analysis the Gmsh FEM mesh object "
                                             "belongs to was found and activated: {}"
                                             .format(o.Name))
                                         gui_doc.setEdit(vobj.Object.Name)
                                         break
                         if not found_mesh_analysis:
                             print(
                                 "Gmsh FEM mesh object does not belong to an analysis. "
                                 "Analysis group meshing will be deactivated."
                             )
                             gui_doc.setEdit(vobj.Object.Name)
                 else:
                     FreeCAD.Console.PrintError(
                         "Active analysis is not in active document.")
             else:
                 print(
                     "No active analysis in active document, "
                     "we are going to have a look if the Gmsh FEM mesh object "
                     "belongs to a non active analysis.")
                 found_mesh_analysis = False
                 for o in gui_doc.Document.Objects:
                     if o.isDerivedFrom("Fem::FemAnalysisPython"):
                         for m in o.Group:
                             if m == self.Object:
                                 found_mesh_analysis = True
                                 FemGui.setActiveAnalysis(o)
                                 print(
                                     "The analysis the Gmsh FEM mesh object "
                                     "belongs to was found and activated: {}"
                                     .format(o.Name))
                                 gui_doc.setEdit(vobj.Object.Name)
                                 break
                 if not found_mesh_analysis:
                     print(
                         "Gmsh FEM mesh object does not belong to an analysis. "
                         "Analysis group meshing will be deactivated.")
                     gui_doc.setEdit(vobj.Object.Name)
         else:
             print("No analysis in the active document.")
             gui_doc.setEdit(vobj.Object.Name)
     else:
         from PySide.QtGui import QMessageBox
         message = "Active Task Dialog found! Please close this one before opening  a new one!"
         QMessageBox.critical(None, "Error in tree view", message)
         FreeCAD.Console.PrintError(message + "\n")
     return True