Ejemplo n.º 1
0
def main():
    pyqtRemoveInputHook()
    QDir(QDir.homePath()).mkdir(".ricodebug")

    app = QApplication(sys.argv)
    app.setApplicationName("ricodebug")

    Icons()

    # We use all kinds of loggers here:
    # * a CriticalLogHandler that will abort the program whenever a critical error is received
    # * a FileHandler writing to a log in the home directory (all messages, for debugging)
    # * a LogViewHandler to have the log available in the GUI
    # * a ErrorLabelHandler that visually notifies the user of an error or a warning
    logger = logging.getLogger()
    formatter = logging.Formatter('[%(levelname)-8s] : %(filename)15s:%(lineno)4d/%(funcName)-20s : %(message)s')

    filehandler = logging.FileHandler(filename='%s/.ricodebug/ricodebug.log' % str(QDir.homePath()))
    filehandler.setFormatter(formatter)
    logger.addHandler(filehandler)
    logger.setLevel(logging.DEBUG)

    logger.addHandler(criticalloghandler.CriticalLogHandler())

    window = MainWindow()

    logger.addHandler(window.logviewhandler)
    logger.addHandler(window.notificationFrameHandler)

    if (len(sys.argv) > 1):
        window.debugController.openExecutable(sys.argv[1])

    window.show()
    logging.shutdown()
    sys.exit(app.exec_())
Ejemplo n.º 2
0
    def __init__(self, canvas, fileName="Unknown", parent=None):
        """ Initialize the dialog. """

        super(ExportBitmapDialog, self).__init__(parent)
        self.setupUi(self)

        self._determine_image_formats()
        self._add_image_formats_to_gui()

        if fileName:
            self.fullPath = QDir.homePath() + "/" + \
                    QFileInfo(fileName).baseName()
        else:
            self.fullPath = QDir.homePath() + "/"
        extension = self.selected_file_extension()
        self.fileNameEdit.setText(self.fullPath + "." + extension)

        # NOTE: This has to come first since we rely on them
        # to syncronize the widgets
        self._set_up_connections()

        self.canvas = canvas
        self.currentUnit = 0
        self.unitSelector.setCurrentIndex(self.currentUnit)
        self.defaultDPI = 300

        self.update_dimensions()
        self.dpiSpinner.setValue(self.defaultDPI)
Ejemplo n.º 3
0
 def linux(self):
     if not self.aBaslat.isChecked():
         setting.setValue("ContextMenu/AcilistaBaslat", False)
         dosyaYolu = os.path.join(str(QDir.homePath()), ".kde", "Autostart", "Virux.desktop")
         if os.path.isfile(dosyaYolu):
             os.remove(dosyaYolu)
     else:
         setting.setValue("ContextMenu/AcilistaBaslat", True)
         dosyaYolu = os.path.join(str(QDir.homePath()), ".kde", "Autostart", "Virux.desktop")
         desktop = """[Desktop Entry]
         Comment[tr]=Platform bağımsız bir antivirüs uygulaması
         Comment=Platform bağımsız bir antivirüs uygulaması
         Exec=python %s/virux.py
         GenericName[tr]=Platform bağımsız bir antivirüs uygulaması
         GenericName=Platform bağımsız bir antivirüs uygulaması
         Icon=%s
         Type=Application
         Name[tr]=Virux
         Name=Virux
         Path=
         StartupNotify=true
         Terminal=false
         """ % (
             mainPath,
             os.path.join(mainPath, "data", "logo.png"),
         )
         yaz = open(dosyaYolu, "w")
         yaz.write(desktop)
         yaz.close()
Ejemplo n.º 4
0
 def linux(self):
     if not self.aBaslat.isChecked():
         setting.setValue("ContextMenu/AcilistaBaslat", False)
         dosyaYolu = os.path.join(str(QDir.homePath()), ".kde", "Autostart",
                                  "Virux.desktop")
         if os.path.isfile(dosyaYolu):
             os.remove(dosyaYolu)
     else:
         setting.setValue("ContextMenu/AcilistaBaslat", True)
         dosyaYolu = os.path.join(str(QDir.homePath()), ".kde", "Autostart",
                                  "Virux.desktop")
         desktop = """[Desktop Entry]
         Comment[tr]=Platform bağımsız bir antivirüs uygulaması
         Comment=Platform bağımsız bir antivirüs uygulaması
         Exec=python %s/virux.py
         GenericName[tr]=Platform bağımsız bir antivirüs uygulaması
         GenericName=Platform bağımsız bir antivirüs uygulaması
         Icon=%s
         Type=Application
         Name[tr]=Virux
         Name=Virux
         Path=
         StartupNotify=true
         Terminal=false
         """ % (mainPath, os.path.join(mainPath, "data", "logo.png"))
         yaz = open(dosyaYolu, "w")
         yaz.write(desktop)
         yaz.close()
Ejemplo n.º 5
0
    def __init__(self, canvas, fileName="Unknown", parent=None):
        """ Initialize the dialog. """

        super(ExportBitmapDialog, self).__init__(parent)
        self.setupUi(self)

        self._determine_image_formats()
        self._add_image_formats_to_gui()

        if fileName:
            self.fullPath = QDir.homePath() + "/" + QFileInfo(fileName).baseName()
        else:
            self.fullPath = QDir.homePath() + "/"
        extension = self.selected_file_extension()
        self.fileNameEdit.setText(self.fullPath + "." + extension)

        # NOTE: This has to come first since we rely on them
        # to syncronize the widgets
        self._set_up_connections()

        self.canvas = canvas
        self.currentUnit = 0
        self.unitSelector.setCurrentIndex(self.currentUnit)
        self.defaultDPI = 300

        self.update_dimensions()
        self.dpiSpinner.setValue(self.defaultDPI)
Ejemplo n.º 6
0
def main():
    pyqtRemoveInputHook()
    QDir(QDir.homePath()).mkdir(".ricodebug")

    app = QApplication(sys.argv)
    app.setApplicationName("ricodebug")

    Icons()

    # We use all kinds of loggers here:
    # * a CriticalLogHandler that will abort the program whenever a critical error is received
    # * a FileHandler writing to a log in the home directory (all messages, for debugging)
    # * a LogViewHandler to have the log available in the GUI
    # * a ErrorLabelHandler that visually notifies the user of an error or a warning
    logger = logging.getLogger()
    formatter = logging.Formatter('[%(levelname)-8s] : %(filename)15s:%(lineno)4d/%(funcName)-20s : %(message)s')

    filehandler = logging.FileHandler(filename='%s/.ricodebug/ricodebug.log' % str(QDir.homePath()))
    filehandler.setFormatter(formatter)
    logger.addHandler(filehandler)
    logger.setLevel(logging.DEBUG)

    logger.addHandler(criticalloghandler.CriticalLogHandler())

    window = MainWindow()

    logger.addHandler(window.logviewhandler)
    logger.addHandler(window.notificationFrameHandler)

    if (len(sys.argv) > 1):
        window.debugController.openExecutable(sys.argv[1])

    window.show()
    logging.shutdown()
    sys.exit(app.exec_())
Ejemplo n.º 7
0
 def s_browse(self):
     directory = QFileDialog.getExistingDirectory(self,QDir.homePath(), QDir.homePath())
     if directory!="":
         path = check_repository(directory)
         if path[0]:
             self.ui.Source_lineEdit.clear()
             self.ui.Source_lineEdit.insert(directory)
         else: QMessageBox.critical(self, "Error", "That directory is not a git repository", QMessageBox.Ok)
Ejemplo n.º 8
0
 def pdfPathSelected(self):
     if self.typeName == 'A':
         self.fileDir = QtGui.QFileDialog.getExistingDirectory(self, "Select Directory",
             QDir.homePath() + "/Desktop")
         self.pdfCounter = 1
     if self.typeName == 'B':
         self.fileDirB = QtGui.QFileDialog.getExistingDirectory(self, "Select Directory",
             QDir.homePath() + "/Desktop")
         self.pdfCounterB = 1
         self.labelSelectedPath.setText('<b>%s</b>' % str(self.fileDirB))
Ejemplo n.º 9
0
 def urlListSelected(self):
     if self.typeName == 'A':
         self.fileName = QtGui.QFileDialog.getOpenFileName(
             self, "Select Text File",
             QDir.homePath() + "/Desktop")
     if self.typeName == 'B':
         self.fileNameB = QtGui.QFileDialog.getOpenFileName(
             self, "Select Text File",
             QDir.homePath() + "/Desktop")
         self.labelSelectedUrl.setText('<b>%s</b>' % str(self.fileNameB))
Ejemplo n.º 10
0
 def browse(self):
     directory = QFileDialog.getExistingDirectory(self, QDir.homePath(), QDir.homePath())
     if directory!="":
         if check_repository(directory):
             if not db_adapter.exists_repository(directory):
                 name = QInputDialog().getText(self, 'Name', 'Put your repository name:', text=basename(directory))
                 if name[1]:
                     self.add_to_database(name[0], directory)
                     self.add_to_list(name[0], directory)
             else:
                 QMessageBox.critical(self, "Error", "This repository is already added", QMessageBox.Ok)
         else: QMessageBox.critical(self, "Error", "That directory is not a git repository", QMessageBox.Ok)
Ejemplo n.º 11
0
def select_git_directory():
    settings = QSettings("majerti", "gitbuster")
    settings.beginGroup("Last run")

    filepath = '/'
    last_directory = settings.value("directory", QVariant(QDir.homePath()))
    dirs_list = settings.value("recent directories",
                               QStringList()).toStringList()
    custom_entries = settings.value("custom entries",
                                    QStringList()).toStringList()

    recent_dirs_urls = [QUrl.fromLocalFile(dir) for dir in dirs_list]
    home_url = QUrl.fromLocalFile(QDir.homePath())
    custom_entries_urls = [QUrl.fromLocalFile(dir) for dir in custom_entries]

    while not is_top_git_directory(unicode(filepath)):
        file_dialog = QFileDialog(None, "Open git repository",
                                  last_directory.toString())
        file_dialog.setFileMode(QFileDialog.Directory)
        file_dialog.setOptions(QFileDialog.ShowDirsOnly)
        if recent_dirs_urls:
            file_dialog.setSidebarUrls(
                [home_url,] +
                custom_entries_urls +
                recent_dirs_urls[-6:]
            )
        ret = file_dialog.exec_()

        custom_entries = QStringList()
        custom_entries_urls = []
        for url in file_dialog.sidebarUrls():
            if url not in recent_dirs_urls and url != home_url:
                custom_entries.append(QString(url.path()))
                custom_entries_urls.append(url)
        settings.setValue("custom entries", custom_entries)

        if ret:
            filepath = file_dialog.selectedFiles()[0]
        else:
            return ret

        if not filepath:
            return filepath

    if not dirs_list.contains(filepath):
        dirs_list.append(filepath)
        settings.setValue("recent directories", dirs_list)

    settings.setValue("directory", filepath)
    settings.endGroup()
    settings.sync()

    return unicode(filepath)
Ejemplo n.º 12
0
 def pdfPathSelected(self):
     if self.typeName == 'A':
         self.fileDir = QtGui.QFileDialog.getExistingDirectory(
             self, "Select Directory",
             QDir.homePath() + "/Desktop")
         self.pdfCounter = 1
     if self.typeName == 'B':
         self.fileDirB = QtGui.QFileDialog.getExistingDirectory(
             self, "Select Directory",
             QDir.homePath() + "/Desktop")
         self.pdfCounterB = 1
         self.labelSelectedPath.setText('<b>%s</b>' % str(self.fileDirB))
Ejemplo n.º 13
0
def getHomeDir():
    """
    Function to get a users home directory
    
    @return home directory (string)
    """
    return unicode(QDir.homePath())
Ejemplo n.º 14
0
    def saveSettings(self, filename=None):
        if not filename:
            # file save dialog
            directory = QgsProject.instance().homePath()
            if not directory:
                directory = os.path.split(
                    self.ui.lineEdit_OutputFilename.text())[0]
            if not directory:
                directory = QDir.homePath()
            filename = QFileDialog.getSaveFileName(
                self, "Save Export Settings", directory,
                "Settings files (*.qto3settings)")
            if not filename:
                return

            # append .qto3settings extension if filename doesn't have
            if os.path.splitext(filename)[1].lower() != ".qto3settings":
                filename += ".qto3settings"

        # save settings to file (.qto3settings)
        import codecs
        import json
        with codecs.open(filename, "w", "UTF-8") as f:
            json.dump(self.settings(True),
                      f,
                      ensure_ascii=False,
                      indent=2,
                      sort_keys=True)

        logMessage(u"Settings saved: {0}".format(filename))
Ejemplo n.º 15
0
        def getRopeProject(self, fileName=""):
            " Provides existed or creates a new rope project "
            if self.project.isLoaded():
                return self.project.getRopeProject()

            # There is no current project so create a temporary one.
            # Two cases: the buffer has been saved
            #            not saved buffer
            if os.path.isabs(fileName):
                dirName = os.path.dirname(fileName)
            else:
                # Unsaved buffer, make an assumption that
                # it is in home directory
                dirName = str(QDir.homePath())

            prefs = copy.deepcopy(ropePreferences)

            # Exclude nested dirs as it could take too long
            # Get only dir names and do not get those dirs
            # where __init__.py[3] are present
            subdirsToExclude = getSubdirs(dirName, True, True)

            if "ignored_resources" in prefs:
                prefs["ignored_resources"] += subdirsToExclude
            else:
                prefs["ignored_resources"] = subdirsToExclude

            project = RopeProject(dirName, None, None, **prefs)
            project.validate(project.root)
            return project
Ejemplo n.º 16
0
    def _set_up_symbols_frame(self):
        """ Do whatever additional initialization we need in the
        update symbol widget.

        """

        self.svgPathEdit.setText(QDir.homePath())
Ejemplo n.º 17
0
 def browseClicked(self):
   directory = os.path.split(self.lineEdit_ImageFile.text())[0]
   if directory == "":
     directory = QDir.homePath()
   filename = QFileDialog.getOpenFileName(self, "Select image file", directory, "Images (*.png *.jpeg *.jpg *.tif *.gif *.bmp);;All files (*.*)")
   if filename:
     self.lineEdit_ImageFile.setText(filename)
Ejemplo n.º 18
0
def getHomeDir():
    """
    Function to get a users home directory
    
    @return home directory (string)
    """
    return unicode(QDir.homePath())
Ejemplo n.º 19
0
    def loadFromFile():
        if not Settings.rcFile:
            # If no file was specified we try to read it from environment
            # variable o standard path
            Settings.rcFile = os.environ.get('TERPRC') or os.path.join(
                str(QDir.toNativeSeparators(QDir.homePath())), '.koorc')
        try:
            if not os.path.isfile(Settings.rcFile):
                Settings.save()
                return False

            p = configparser.ConfigParser()
            p.read([Settings.rcFile])
            for section in p.sections():
                for (name, value) in p.items(section):
                    if value == 'True' or value == 'true':
                        value = True
                    if value == 'False' or value == 'false':
                        value = False
                    if value == 'None' or value == 'none':
                        value = None
                    Settings.options[section + '.' + name] = value
        except Exception as e:
            Debug.warning('Unable to read config file %s !' % Settings.rcFile)
        return True
Ejemplo n.º 20
0
    def open_file_selector(self):
        """ Open a file selector and ask for the name """

        formatStr = "All Files (*.*)"
        for aFormat in self.formats:
            if aFormat in imageFileFormats:
                description = imageFileFormats[aFormat]
            else:
                description = "Image Format"
            
            formatStr = ("%s;; %s ( *.%s)" % (formatStr, description, 
                                              aFormat))

        defaultPath = self.fileNameEdit.text()
        if not defaultPath:
            defaultPath = QDir.homePath()

        exportFilePath = QFileDialog.getSaveFileName(self,
                                        msg.exportPatternTitle,
                                        defaultPath,
                                        formatStr,
                                        QFileDialog.DontConfirmOverwrite) 

        if exportFilePath:
            self.update_export_path(exportFilePath)
Ejemplo n.º 21
0
    def __init__(self, parent=None):
        custom_dock.CustomDock.__init__(self)
        self.explorador = QTreeView()
        self.setWidget(self.explorador)
        self.explorador.header().setHidden(True)
        self.explorador.setAnimated(True)

        # Modelo
        self.modelo = QFileSystemModel(self.explorador)
        path = QDir.toNativeSeparators(QDir.homePath())
        self.modelo.setRootPath(path)
        self.explorador.setModel(self.modelo)
        self.modelo.setNameFilters(["*.c", "*.h", "*.s"])
        self.explorador.setRootIndex(QModelIndex(self.modelo.index(path)))
        self.modelo.setNameFilterDisables(False)

        # Se ocultan algunas columnas
        self.explorador.hideColumn(1)
        self.explorador.hideColumn(2)
        self.explorador.hideColumn(3)

        # Conexion
        self.explorador.doubleClicked.connect(self._abrir_archivo)

        EDIS.cargar_lateral("explorador", self)
    def on_mEndMarkerToolButton_clicked(self):
        if self.timeStart != 0:
            self.timeEnd = time.time()
            print self.timeEnd
            if self.timeEnd - self.timeStart <= 2:
                self.timeStart = 0
                return
        s = QSettings()
        openDir = QString()

        if (not self.mEndMarkerLineEdit.text().isEmpty()):
            fi = QFileInfo(self.mEndMarkerLineEdit.text())
            openDir = fi.dir().absolutePath()

        if (openDir.isEmpty()):
            openDir = s.value("/UI/lastComposerMarkerDir",
                              QDir.homePath()).toString()

        svgFileName = QFileDialog.getOpenFileName(
            self, QString("End marker svg file"), openDir)
        if (not svgFileName.isNull()):
            fileInfo = QFileInfo(svgFileName)
            s.setValue("/UI/lastComposerMarkerDir", fileInfo.absolutePath())
            self.mArrow.beginCommand(QString("Arrow end marker"))
            self.mEndMarkerLineEdit.setText(svgFileName)
            self.mArrow.endCommand()
        self.timeStart = time.time()
Ejemplo n.º 23
0
def open_files_prompt(title,
                      home_path=None,
                      file_extension_spec=None,
                      parent=None):
    """ Display a prompt to choose multiple existing files from the filesystem.

    :param title: The title to display for the prompt.
    :param home_path: The default filesystem path for the prompt.
    :param file_extension_spec: The specification of what file types will be shown by the prompt.
    :param parent: The parent widget of the prompt.
    :raise UserCancelledPromptException: If not files are selected or the user presses the cancel button.
    :return: A list of filepaths that were selected in the prompt.
    """
    if not home_path:
        home_path = QDir.homePath()

    if not file_extension_spec:
        file_extension_spec = 'All Files (*.*)'

    file_paths = QFileDialog.getOpenFileNames(parent, title, home_path,
                                              file_extension_spec, None)
    file_paths = [str(filepath) for filepath in file_paths]

    if not file_paths:
        raise UserCancelledPromptException('No filenames selected.')

    return file_paths
Ejemplo n.º 24
0
    def saveSettings(self, filename=None):
        if not filename:
            # file save dialog
            directory = QgsProject.instance().homePath()
            if not directory:
                directory = os.path.split(self.ui.lineEdit_OutputFilename.text())[0]
            if not directory:
                directory = QDir.homePath()
            filename = QFileDialog.getSaveFileName(
                self, "Save Export Settings", directory, "Settings files (*.qto3settings)"
            )
            if not filename:
                return

            # append .qto3settings extension if filename doesn't have
            if os.path.splitext(filename)[1].lower() != ".qto3settings":
                filename += ".qto3settings"

        # save settings to file (.qto3settings)
        import codecs
        import json

        with codecs.open(filename, "w", "UTF-8") as f:
            json.dump(self.settings(True), f, ensure_ascii=False)

        logMessage(u"Settings saved: {0}".format(filename))
Ejemplo n.º 25
0
        def getRopeProject( self, fileName = "" ):
            " Provides existed or creates a new rope project "
            if self.project.isLoaded():
                return self.project.getRopeProject()

            # There is no current project so create a temporary one.
            # Two cases: the buffer has been saved
            #            not saved buffer
            if os.path.isabs( fileName ):
                dirName = os.path.dirname( fileName )
            else:
                # Unsaved buffer, make an assumption that
                # it is in home directory
                dirName = str( QDir.homePath() )

            prefs = copy.deepcopy( ropePreferences )

            # Exclude nested dirs as it could take too long
            # Get only dir names and do not get those dirs
            # where __init__.py[3] are present
            subdirsToExclude = getSubdirs( dirName, True, True )

            if "ignored_resources" in prefs:
                prefs[ "ignored_resources" ] += subdirsToExclude
            else:
                prefs[ "ignored_resources" ] = subdirsToExclude

            project = RopeProject( dirName, None, None, **prefs )
            project.validate( project.root )
            return project
Ejemplo n.º 26
0
    def _set_up_symbols_frame(self):
        """ Do whatever additional initialization we need in the
        update symbol widget.

        """

        self.svgPathEdit.setText(QDir.homePath())
Ejemplo n.º 27
0
 def __askForFilePath(self):
     filepath, file_filter = QtGui.QFileDialog.getOpenFileNameAndFilter(parent=self,
                                                caption="Load Chat Log",
                                                directory=QDir.homePath(),
                                                filter='Text files (*.txt *.log);;All files (*)',
                                                options=QtGui.QFileDialog.ReadOnly)
     return (filepath, file_filter)
 def open_file_dialog(self, dialog_type):
     """
     Open a file dialog to select the data file to be loaded
     :param string dialog_type:
         Valid types are 'loss_layer' or 'zonal_layer'
     :returns:
     """
     if dialog_type == 'loss_layer':
         text = self.tr('Select loss map to import')
         # FIXME: What should be the format of the raster maps?
         filters = self.tr('Geojson vector loss maps (*.geojson);; '
                           'Shapefile vector loss maps (*.shp);; '
                           'Raster loss maps (*.*)')
     elif dialog_type == 'zonal_layer':
         text = self.tr('Select zonal layer to import')
         filters = self.tr('Vector shapefiles (*.shp);; SQLite (*.sqlite);;'
                           ' All files (*.*)')
     else:
         raise RuntimeError('Invalid dialog_type: {}'.format(dialog_type))
     file_name, file_type = QFileDialog.getOpenFileNameAndFilter(
         self, text, QDir.homePath(), filters)
     if file_name:
         if dialog_type == 'zonal_layer':
             layer = self.load_zonal_layer(file_name)
         elif dialog_type == 'loss_layer':
             if file_type == 'Raster loss maps (*.*)':
                 self.loss_layer_is_vector = False
             layer = self.load_loss_layer(file_name)
         else:
             raise RuntimeError
         return layer
     else:
         return None
Ejemplo n.º 29
0
 def urlListSelected(self):
     self.fileName = QtGui.QFileDialog.getOpenFileName(self, "Select Text File", QDir.homePath() + "/Desktop")
     f = open(self.fileName, 'rb')
     self.lists = f.readlines()
     f.close()
     if self.lists is not None:
         for line in self.lists:
             self.urlList.append(line)
Ejemplo n.º 30
0
 def slotImport(self):
     filetypes = "{0} (*.xml);;{1} (*)".format(_("XML Files"),
                                               _("All Files"))
     caption = app.caption(_("dialog title", "Import color theme"))
     filename = QFileDialog.getOpenFileName(self, caption, QDir.homePath(),
                                            filetypes)
     if filename:
         self.parent().import_(filename)
Ejemplo n.º 31
0
 def defaults(self):
     defaults_settings_dict = dict(recent=5, save_dir=QDir.homePath(), close_confirmation=True,
                                        display_image=True, list_recent=[])
     self.settings['recent'] = defaults_settings_dict['recent']
     self.settings['save_dir'] = defaults_settings_dict['save_dir']
     self.settings['close_confirmation'] = defaults_settings_dict['close_confirmation']
     self.settings['display_image'] = defaults_settings_dict['display_image']
     self.settings['list_recent'] = defaults_settings_dict['list_recent']
     self.set_values()
Ejemplo n.º 32
0
 def browseClicked(self):
     directory = os.path.split(self.lineEdit_ImageFile.text())[0]
     if directory == "":
         directory = QDir.homePath()
     filterString = "Images (*.png *.jpg *.gif *.bmp);;All files (*.*)"
     filename = QFileDialog.getOpenFileName(self, "Select image file",
                                            directory, filterString)
     if filename:
         self.lineEdit_ImageFile.setText(filename)
Ejemplo n.º 33
0
    def clear_symbol_info(self):
        """ This slot clears all entries in the addSymbolTab """

        self.symbolNameEntry.clear()
        self.symbolWidthSpinner.setValue(1)
        self.symbolDescriptionEntry.clear()
        self.svgWidget.load(QByteArray())
        self.svgPathEdit.setText(QDir.homePath())
        self._svgFilePath = None
Ejemplo n.º 34
0
    def choose_pressed(self):
        dialog = QFileDialog()
        dialog.setDirectory(QDir.homePath())
        dialog.setFileMode(QFileDialog.ExistingFiles)

        if dialog.exec_():
            filenames = dialog.selectedFiles()
            for filename in filenames:
                self.text_edit_files.append(filename)
Ejemplo n.º 35
0
    def choose_pressed(self):
        dialog = QFileDialog()
        dialog.setDirectory(QDir.homePath())
        dialog.setFileMode(QFileDialog.ExistingFiles)

        if dialog.exec_():
            filenames = dialog.selectedFiles()
            for filename in filenames:
                self.text_edit_files.append(filename)
Ejemplo n.º 36
0
Archivo: scj.py Proyecto: Ptaah/SCJ
 def getFiles(self):
     files = QFileDialog.getOpenFileNames(
                             parent = self,
                             caption = self.trUtf8("Choix des fichiers"),
                             directory = QDir.homePath(),
                             filter = u"%s (%s)" % (self.trUtf8("Sons"),
                                                    self.filter))
     for file in files:
         self.addFile(QFileInfo(file), createDir=False)
Ejemplo n.º 37
0
    def clear_symbol_info(self):
        """ This slot clears all entries in the addSymbolTab """

        self.symbolNameEntry.clear()
        self.symbolWidthSpinner.setValue(1)
        self.symbolDescriptionEntry.clear()
        self.svgWidget.load(QByteArray())
        self.svgPathEdit.setText(QDir.homePath())
        self._svgFilePath = None
Ejemplo n.º 38
0
    def index_path():
        options = Configuration._read_options(
            config_file=Configuration.INDEXING_CONFIG_FILE,
            config_file_header=Configuration.INDEXING_CONFIG_FILE_HEADER
        )

        if Configuration.INDEXING_CONFIG_PATH in options:
            return QDir.fromNativeSeparators(options[Configuration.INDEXING_CONFIG_PATH])

        return QDir.fromNativeSeparators('%s/%s' % (QDir.homePath(), 'index_db'))
Ejemplo n.º 39
0
 def htmlTagSelected(self):
     try:
         self.htmlFileName = QtGui.QFileDialog.getOpenFileName(
             self, "Select Text File", QDir.homePath() + "/Desktop"
         )
         f = open(self.htmlFileName, "rb")
         self.htmlTag = f.read()
         f.close()
     except Exception, x:
         print x
Ejemplo n.º 40
0
    def exportNotice(self):
        query = QSqlQuery(self.db)
        query.exec_("select stusn, stuname, classname, rightquestions, wrongquestions from student" ) 
        lstInfo = [["学号","姓名", "班级", "回答正确次数", "回答错误次数"]]
        while(query.next()):
            lstInfo.append([query.value(0),query.value(1),query.value(2),query.value(3),query.value(4)])

        from xlwt import Workbook,easyxf
        book = Workbook(encoding='ascii')
            # 'pattern: pattern solid,  fore_colour white;'
        style = easyxf(
            'font: height 280, name 黑体;'
            'align: vertical center, horizontal center;'
            )
        style2 = easyxf('font: height 260, name 仿宋_GB2312, bold True; align: vertical center, horizontal left;')
        style3 = easyxf('font: height 260, name 仿宋_GB2312, bold True; align: vertical center, horizontal left, wrap True;')

        sheet1 = book.add_sheet('学生提问情况汇总',cell_overwrite_ok=True)
        # sheet1.write(0,7,flagtxt, easyxf('font: height 200, name 黑体;align: vertical center, horizontal right;'))
        sheet1.write_merge(0,0,0,4, '学生提问情况汇总表',style)
        sheet1.row(0).height_mismatch = 1
        sheet1.row(0).height = 5*256

        sheet1.col(0).width = 10*256
        sheet1.col(1).width = 25*256
        sheet1.col(2).width = 25*256
        sheet1.col(3).width = 20*256
        sheet1.col(4).width = 20*256
        
        tmprows = 1
        for item in lstInfo:
            stusn               = item[0]
            stuname             = item[1]
            classname           = item[2]
            rightquestions      = item[3]
            wrongquestions      = item[4]

            sheet1.write(tmprows,0,stusn, style2)
            sheet1.write(tmprows,1,stuname, style2)
            sheet1.write(tmprows,2,classname, style2)
            sheet1.write(tmprows,3,rightquestions, style2)
            sheet1.write(tmprows,4,wrongquestions, style2)
            tmprows += 1
        # print(tmprows)
        sheet1.header_str = "".encode()
        sheet1.footer_str = "".encode()

        # book.save('d:/simple.xls')
        # print(QDir.home().dirName() , QDir.homePath ())
        filename = QDir.homePath () + "\学生提问情况汇总表.xls" 
        try:
            book.save(filename)
        except  Exception as e:
            QMessageBox.warning(self, "写入错误", "错误号:"+str(e.errno)+"\n错误描述:"+e.strerror+"\n请关闭已经打开的%s文档!" % filename)
        QMessageBox.about (self, "导出成功", "请查看文档:%s" % filename)
Ejemplo n.º 41
0
 def slotExport(self):
     name = self.scheme.currentText()
     filetypes = "{0} (*.xml);;{1} (*)".format(_("XML Files"), _("All Files"))
     caption = app.caption(_("dialog title",
         "Export {name}").format(name=name))
     path = os.path.join(QDir.homePath(), name+'.xml')
     filename = QFileDialog.getSaveFileName(self, caption, path, filetypes)
     if filename:
         if os.path.splitext(filename)[1] != '.xml':
             filename += '.xml'
         self.parent().export(name, filename)
Ejemplo n.º 42
0
 def _loadDetectorButtonPressed(self):
     fname = QFileDialog.getOpenFileName(self, caption='Open Detector File', 
                                         #filter="Pickled Objects (*.pkl);;All Files (*)",
                                         directory=QDir.homePath(),
                                         )
     if len(fname)>0: #not cancelled
         with open(fname, 'r') as f:
             pkl = f.read()
         
         self.topLevelOperatorView.loads(pkl)
         logger.debug("Loaded detector from file '{}'".format(fname))
Ejemplo n.º 43
0
    def populateModel( self ):
        " Populates the browser model "

        self.clear()
        self.addItem( TreeViewSysPathItem( self.rootItem ) )
        self.addItem( TreeViewDirectoryItem( self.rootItem, QDir.homePath() ) )
        for dname in QDir.drives():
            self.addItem( TreeViewDirectoryItem( self.rootItem,
                                                 dname.absoluteFilePath() ) )
        self.__populateProjectTopLevelDirs()
        return
Ejemplo n.º 44
0
Archivo: scj.py Proyecto: Ptaah/SCJ
    def getDir(self):
        self.dir = QFileDialog.getExistingDirectory(
                                parent = self,
                                caption = self.trUtf8("Choix du repertoire"),
					            directory = QDir.homePath(),
		                        options = QFileDialog.ShowDirsOnly |
                                QFileDialog.DontResolveSymlinks)
        if self.dir :
            directory = QDir(self.dir, self.filter)
            for file in directory.entryInfoList():
                self.addFile(file, createDir=True)
Ejemplo n.º 45
0
 def slotExport(self):
     name = self.scheme.currentText()
     filetypes = "{0} (*.xml);;{1} (*)".format(_("XML Files"), _("All Files"))
     caption = app.caption(_("dialog title",
         "Export {name}").format(name=name))
     path = os.path.join(QDir.homePath(), name+'.xml')
     filename = QFileDialog.getSaveFileName(self, caption, path, filetypes)
     if filename:
         if os.path.splitext(filename)[1] != '.xml':
             filename += '.xml'
         self.parent().export(name, filename)
Ejemplo n.º 46
0
def local_collection_path(id=None):
    """Get the path to the local collection dir.

    If id is not passed, it will just return the root dir of the collections.
    """
    path = os.path.join(QDir.homePath(), 'QGIS', 'Resource Sharing')
    if id:
        collection_name = config.COLLECTIONS[id]['name']
        dir_name = '%s (%s)' % (collection_name, id)
        path = os.path.join(path, dir_name)
    return path
Ejemplo n.º 47
0
    def parse(cls, lines):
        """ this function-call is required to get the yacc running! """
        lex.lex(reflags=re.DOTALL)

        parser = yacc.yacc(start="top", debug=0, outputdir=str(QDir.homePath()) + "/.ricodebug")
        r = []
        for line in lines:
            line = line.strip()
            r.append(parser.parse(line))
            r[-1].raw = line

        return r
Ejemplo n.º 48
0
    def show_symbol_path_fileSelector(self):
        """ Open up a file selector dialog allowing a user to change
        the path to where the custom knitting symbols are.

        """

        customSymbolFilePath = QFileDialog.getExistingDirectory(
            self, msg.customSymbolPathDirectoryTitle, QDir.homePath())

        if customSymbolFilePath:
            self.settings.personalSymbolPath.value = customSymbolFilePath
            self.customSymbolPathEdit.setText(customSymbolFilePath)
Ejemplo n.º 49
0
    def show_logging_path_fileSelector(self):
        """ Open up a file selector dialog allowing a user to change
        the path to where logfiles are stored.

        """

        loggingPath = QFileDialog.getExistingDirectory(
            self, msg.loggingPathDirectoryTitle, QDir.homePath())

        if loggingPath:
            self.settings.loggingPath.value = loggingPath
            self.loggingPathEdit.setText(loggingPath)
Ejemplo n.º 50
0
    def geometriePDF(self, titre, taillePlan):
        # Afficher un assistant de saisie pour le choix du composeur
        dlgConfigComposers = DICTDialogComposer(taillePlan)
        dlgConfigComposers.show()
        result = dlgConfigComposers.exec_()

        idx_plan = []

        if result:
            idx_plan = dlgConfigComposers.listComposers.selectedItems()
            # id_plan = dlgConfigComposers.listComposers.currentRow()
        # Sortie du plan en PDF
        composers = iface.activeComposers()

        out = []
        if len(idx_plan) > 0:

            for r in idx_plan:
                id_plan = dlgConfigComposers.listComposers.row(r)
                c = composers[id_plan].composition()

                # À configurer
                c_map_lists = c.composerMapItems()
                if (len(c_map_lists) == 0):
                    return out
                else:
                    c_map = c_map_lists[0]

                if c_map:
                    c_map.zoomToExtent(self._geomBB)

                    # A faire correctement
                    s = c_map.scale()
                    scal = self.__findScale(s)
                    iface.mapCanvas().zoomScale(scal)
                    c_map.setNewScale(scal)
                    c_map.updateCachedImage()
                    c_map.renderModeUpdateCachedImage()

                    # Sortie
                    out_dir = QSettings().value("/DICT/configRep")
                    if QDir(out_dir).exists() is False or out_dir is None:
                        out_dir = str(QDir.homePath())

                    pdf = out_dir + "/" + \
                        QSettings().value("/DICT/prefPlan", u"") + titre + \
                        QSettings().value("/DICT/sufPlan", u"") + \
                        str(id_plan) + ".pdf"

                    c.exportAsPDF(pdf)
                    out.append(pdf)

        return out
Ejemplo n.º 51
0
    def funcionComprimir(self):
        global contador
        numHilos = QThread.idealThreadCount()

        user_home = QDir.homePath()  #home del usuario

        try:
            os.mkdir(os.path.join(unicode(user_home), 'carpetadeliss'))
            # os.mkdir(user_home+'/micarpeta') #es lo mismo que la linea de arriba
        except (OSError):
            print("Carpeta ya existe.")

        #print("rutaGuardar")
        rutaGuardar = os.path.join(unicode(user_home), 'carpetadeliss')

        #self.proceso_comando.start('cpdf', ['-squeeze', elementoPDF, '-o', os.path.join(rutaGuardar, unicode(pdfName))])
        #self.proceso_comando.start('ls', ['-l'])
        # (comando, ['arg1' ,  'arg2',  'argN'])

        #for _ in self.a : es lo mismo que abajo
        procesos = []  # lista con procesos y lanzar
        for _ in range(0, len(self.a)):
            i = QProcess(self)
            i.finished.connect(self.funcionFinised)
            procesos.append(i)

        while len(self.a) != 0:
            mutex.lock()
            if contador <= 2:

                elementoPDF = self.a.pop(
                )  # hace pop al ultimo elemento de la lista
                pdfName = QFileInfo(elementoPDF).fileName()

                contador = contador + 1
                print("contador 1", contador)
                proceso_me = procesos.pop()
                print("u1")
                mutex.unlock()
                proceso_me.start('cpdf', [
                    '-squeeze', elementoPDF, '-o',
                    os.path.join(rutaGuardar, unicode(pdfName))
                ])
            else:
                print("u2")
                mutex.unlock()
                print("...................")
                mutex2.lock()
                print("mkcbnveoirbvrpobgt---------")
                wait_condition.wait(mutex2)

                print("mutex2")
                mutex2.unlock()
Ejemplo n.º 52
0
def main():
    pyqtRemoveInputHook()
    QDir(QDir.homePath()).mkdir(".ricodebug")

    app = QApplication(sys.argv)
    app.setApplicationName("ricodebug")

    window = MainWindow()

    logging.basicConfig(filename='%s/.ricodebug/ricodebug.log' % str(QDir.homePath()), level=logging.DEBUG)
    logviewhandler = logview.LogViewHandler(window.ui.logView, window.ui.filterSlider)
    window.ui.filterSlider.setValue(3)
    errormsghandler = logview.ErrorLabelHandler(window)
    logger = logging.getLogger()
    logger.addHandler(logviewhandler)
    logger.addHandler(errormsghandler)

    if (len(sys.argv) > 1):
        window.debugController.openExecutable(sys.argv[1])

    window.show()
    sys.exit(app.exec_())
Ejemplo n.º 53
0
    def show_logging_path_fileSelector(self):
        """ Open up a file selector dialog allowing a user to change
        the path to where logfiles are stored.

        """

        loggingPath = QFileDialog.getExistingDirectory(self,
                                      msg.loggingPathDirectoryTitle,
                                      QDir.homePath())

        if loggingPath:
            self.settings.loggingPath.value = loggingPath
            self.loggingPathEdit.setText(loggingPath)
Ejemplo n.º 54
0
    def funcionAgregar(self):
        homeUsuario = QDir.homePath()
        rutaPdf = QFileDialog.getOpenFileName(
            self,
            directory=homeUsuario)  #indico que me abra en el home del usuario
        objetoPDF = QFileInfo(rutaPdf)
        #self.listWidget.addItem(QFileDialog.getOpenFileName())
        self.listWidget.addItem(objetoPDF.fileName())

        self.a.append(unicode(rutaPdf))

        print(self.a)
        print("contenido de arreglo a")
Ejemplo n.º 55
0
    def export_custom_symbols(self):
        """ Helper function for saving custom symbols into a zip archive. """

        saveFilePath = QFileDialog.getSaveFileName(self,
                                                   "Export Custom Symbols",
                                                   QDir.homePath(),
                                                   "zip files (*.zip)")

        if saveFilePath:
            if not writezip(self._symbolPath, saveFilePath):
                QMessageBox.critical(self, msg.cannotExportSymbolsTitle,
                                     msg.cannotExportSymbolsText,
                                     QMessageBox.Ok)
Ejemplo n.º 56
0
def generate_recovery_filepath(filePath):
    """ Based on a filePath generate the name for the recovery File. """

    # check if sconcho directory in user's home directory exists
    sconchoDirName = QDir.homePath() + "/.sconcho"
    sconchoDir = QDir(sconchoDirName)
    if not sconchoDir.exists():
        status = sconchoDir.mkdir(sconchoDirName)

    recoveryFileInfo = QFileInfo(filePath)
    recoveryFilePath = sconchoDirName + "/" + \
            recoveryFileInfo.fileName() + ".recovery"

    return recoveryFilePath
Ejemplo n.º 57
0
    def parse(cls, lines):
        """Parse the lines with the above defined lexical rules
        """
        lex.lex(reflags=re.DOTALL)

        parser = yacc.yacc(start='top',
                           debug=0,
                           outputdir=str(QDir.homePath()) + "/.ricodebug")
        r = []
        for line in lines:
            line = line.strip()
            r.append(parser.parse(line))
            r[-1].raw = line

        return r
Ejemplo n.º 58
0
    def _loadHistogramsButtonPressed(self):
        fname = QFileDialog.getOpenFileName(
            self, caption='Open Histogram File',
            filter="HDF5 Files (*.h5 *.hdf5);;All Files (*)",
            directory=QDir.homePath())
        if len(fname) > 0:  # not cancelled
            #FIXME where do we get the real h5 path from???
            h5path = 'volume/data'

            # no try-catch because we want to propagate errors to the GUI
            histos = vigra.impex.readHDF5(str(fname), h5path)

            self.topLevelOperatorView.setPrecomputedHistograms(histos)
            logger.debug("Loaded histograms from file '{}' (shape: {})".format(
                fname, histos.shape))
    def OpenObstacleFile(self):
        settings = QSettings()

        lastusedir = settings.value("/UI/lastObstacleVectorFileDir",
                                    QDir.homePath()).toString()

        path = QFileDialog.getOpenFileName(self, "Open Obstacle File",
                                           lastusedir,
                                           "Obstacle files(*.txt *.csv)")

        if path == "":
            return

        self.ui.txtPath.setText(path)

        settings.setValue("/UI/lastObstacleVectorFileDir", path)