예제 #1
0
class AttachmentView(QListView):
    """ A dockWidget displaying attachments of the current note.
    """

    def __init__(self, parent=None):
        super(AttachmentView, self).__init__(parent)
        self.parent = parent
        self.settings = parent.settings

        self.model = QFileSystemModel()
        self.model.setFilter(QDir.Files)
        self.model.setRootPath(self.settings.attachmentPath)
        self.setModel(self.model)

        # self.setRootIndex(self.model.index(self.settings.attachmentPath))
        self.setViewMode(QListView.IconMode)
        self.setUniformItemSizes(True)
        self.setResizeMode(QListView.Adjust)
        self.setItemDelegate(AttachmentItemDelegate(self))
        self.clicked.connect(self.click)

    def contextMenuEvent(self, event):
        menu = QMenu()
        indice = self.selectedIndexes()
        if len(indice):
            menu.addAction("Insert into note", self.insert)
            menu.addAction("Delete", self.delete)
        else:
            pass
        menu.exec_(event.globalPos())

    def mousePressEvent(self, event):
        """ Trigger click() when an item is pressed.
        """
        self.clearSelection()
        QListView.mousePressEvent(self, event)

    def mouseReleaseEvent(self, event):
        """ Trigger click() when an item is pressed.
        """
        self.clearSelection()
        QListView.mouseReleaseEvent(self, event)

    def insert(self):
        indice = self.selectedIndexes()
        for i in indice:
            filePath = self.model.filePath(i)
            filePath = filePath.replace(self.settings.notebookPath, "..")
            fileName = os.path.basename(filePath)
            text = "![%s](%s)" % (fileName, filePath)
            self.parent.notesEdit.insertPlainText(text)

    def delete(self):
        indice = self.selectedIndexes()
        for i in indice:
            filePath = self.model.filePath(i)
            QFile(filePath).remove()

    def click(self, index):
        self.setCurrentIndex(index)
예제 #2
0
class AttachmentView(QListView):
    """ A dockWidget displaying attachments of the current note.
    """
    def __init__(self, parent=None):
        super(AttachmentView, self).__init__(parent)
        self.parent = parent
        self.settings = parent.settings

        self.model = QFileSystemModel()
        self.model.setFilter(QDir.Files)
        self.model.setRootPath(self.settings.attachmentPath)
        self.setModel(self.model)

        # self.setRootIndex(self.model.index(self.settings.attachmentPath))
        self.setViewMode(QListView.IconMode)
        self.setUniformItemSizes(True)
        self.setResizeMode(QListView.Adjust)
        self.setItemDelegate(AttachmentItemDelegate(self))
        self.clicked.connect(self.click)

    def contextMenuEvent(self, event):
        menu = QMenu()
        indice = self.selectedIndexes()
        if len(indice):
            menu.addAction(self.tr("Insert into note"), self.insert)
            menu.addAction(self.tr("Delete"), self.delete)
        else:
            pass
        menu.exec_(event.globalPos())

    def mousePressEvent(self, event):
        """ Trigger click() when an item is pressed.
        """
        self.clearSelection()
        QListView.mousePressEvent(self, event)

    def mouseReleaseEvent(self, event):
        """ Trigger click() when an item is pressed.
        """
        self.clearSelection()
        QListView.mouseReleaseEvent(self, event)

    def insert(self):
        indice = self.selectedIndexes()
        for i in indice:
            filePath = self.model.filePath(i)
            filePath = filePath.replace(self.settings.notebookPath, "..")
            fileName = os.path.basename(filePath)
            text = "![%s](%s)" % (fileName, filePath)
            self.parent.notesEdit.insertPlainText(text)

    def delete(self):
        indice = self.selectedIndexes()
        for i in indice:
            filePath = self.model.filePath(i)
            QFile(filePath).remove()

    def click(self, index):
        self.setCurrentIndex(index)
예제 #3
0
class Explorer(QTreeView):

    def __init__(self, parent=None):
        QTreeView.__init__(self)
        self.header().setHidden(True)
        self.setAnimated(True)

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

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

        # Conexion
        self.doubleClicked.connect(self._open_file)

        Edis.load_lateral("explorer", self)

    def _open_file(self, i):
        if not self.model.isDir(i):
            indice = self.model.index(i.row(), 0, i.parent())
            archivo = self.model.filePath(indice)
            principal = Edis.get_component("principal")
            principal.open_file(archivo)
예제 #4
0
class OrLogsListView(QListView):
    def __init__(self, parent=None):
        super(OrLogsListView, self).__init__(parent)
        self.model = QFileSystemModel()
        self.model.sort(3, Qt.DescendingOrder)
        self.model.setFilter(QDir.Files)
        self.setModel(self.model)

    def mouseDoubleClickEvent(self, event):
        """method override"""
        QListView.mouseDoubleClickEvent(self, event)
        self.clicked()

    def getSelectedPath(self):
        """Return selected filename"""
        index = self.currentIndex()
        if index:
            return os.path.normpath(self.model.filePath(index))

    def clicked(self):
        fname = self.getSelectedPath()
        if fname:
            self.open(fname)

    def open(self, fname):
        QDesktopServices.openUrl(QUrl('file:///' + fname))

    def setup(self, wdir='.'):
        os.makedirs(wdir, exist_ok=True)
        self.model.setRootPath(wdir)
        self.setRootIndex(self.model.index(wdir))
예제 #5
0
파일: explorador.py 프로젝트: ekimdev/edis
class Explorador(custom_dock.CustomDock):

    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 _abrir_archivo(self, i):
        if not self.modelo.isDir(i):
            indice = self.modelo.index(i.row(), 0, i.parent())
            archivo = self.modelo.filePath(indice)
            principal = EDIS.componente("principal")
            principal.abrir_archivo(archivo)
예제 #6
0
파일: explorer.py 프로젝트: koll00/Gui_SM
class DirView(QTreeView):
    """Base file/directory tree view"""
    def __init__(self, parent=None):
        super(DirView, self).__init__(parent)
        self.name_filters = None
        self.parent_widget = parent
        self.valid_types = None
        self.show_all = None
        self.menu = None
        self.common_actions = None
        self.__expanded_state = None
        self._to_be_loaded = None
        self.fsmodel = None
        self.setup_fs_model()
        self._scrollbar_positions = None

    #---- Model
    def setup_fs_model(self):
        """Setup filesystem model"""
        filters = QDir.AllDirs | QDir.Files | QDir.Drives | QDir.NoDotAndDotDot
        self.fsmodel = QFileSystemModel(self)
        self.fsmodel.setFilter(filters)
        self.fsmodel.setNameFilterDisables(False)

    def install_model(self):
        """Install filesystem model"""
        self.setModel(self.fsmodel)

    def setup_view(self):
        """Setup view"""
        self.install_model()
        self.connect(self.fsmodel, SIGNAL('directoryLoaded(QString)'),
                     lambda: self.resizeColumnToContents(0))
        self.setAnimated(False)
        self.setSortingEnabled(True)
        self.sortByColumn(0, Qt.AscendingOrder)

    def set_name_filters(self, name_filters):
        """Set name filters"""
        self.name_filters = name_filters
        self.fsmodel.setNameFilters(name_filters)

    def set_show_all(self, state):
        """Toggle 'show all files' state"""
        if state:
            self.fsmodel.setNameFilters([])
        else:
            self.fsmodel.setNameFilters(self.name_filters)

    def get_filename(self, index):
        """Return filename associated with *index*"""
        if index:
            return osp.normpath(unicode(self.fsmodel.filePath(index)))

    def get_index(self, filename):
        """Return index associated with filename"""
        return self.fsmodel.index(filename)

    def get_selected_filenames(self):
        """Return selected filenames"""
        if self.selectionMode() == self.ExtendedSelection:
            return [self.get_filename(idx) for idx in self.selectedIndexes()]
        else:
            return [self.get_filename(self.currentIndex())]

    def get_dirname(self, index):
        """Return dirname associated with *index*"""
        fname = self.get_filename(index)
        if fname:
            if osp.isdir(fname):
                return fname
            else:
                return osp.dirname(fname)

    #---- Tree view widget
    def setup(self,
              name_filters=['*.py', '*.pyw'],
              valid_types=('.py', '.pyw'),
              show_all=False):
        """Setup tree widget"""
        self.setup_view()

        self.set_name_filters(name_filters)
        self.valid_types = valid_types
        self.show_all = show_all

        # Setup context menu
        self.menu = QMenu(self)
        self.common_actions = self.setup_common_actions()

    #---- Context menu
    def setup_common_actions(self):
        """Setup context menu common actions"""
        # Filters
        filters_action = create_action(self,
                                       _("Edit filename filters..."),
                                       None,
                                       get_icon('filter.png'),
                                       triggered=self.edit_filter)
        # Show all files
        all_action = create_action(self,
                                   _("Show all files"),
                                   toggled=self.toggle_all)
        all_action.setChecked(self.show_all)
        self.toggle_all(self.show_all)

        return [filters_action, all_action]

    def edit_filter(self):
        """Edit name filters"""
        filters, valid = QInputDialog.getText(self, _('Edit filename filters'),
                                              _('Name filters:'),
                                              QLineEdit.Normal,
                                              ", ".join(self.name_filters))
        if valid:
            filters = [f.strip() for f in unicode(filters).split(',')]
            self.parent_widget.sig_option_changed.emit('name_filters', filters)
            self.set_name_filters(filters)

    def toggle_all(self, checked):
        """Toggle all files mode"""
        self.parent_widget.sig_option_changed.emit('show_all', checked)
        self.show_all = checked
        self.set_show_all(checked)

    def create_file_new_actions(self, fnames):
        """Return actions for submenu 'New...'"""
        if not fnames:
            return []
        new_file_act = create_action(
            self,
            _("File..."),
            icon='filenew.png',
            triggered=lambda: self.new_file(fnames[-1]))
        new_module_act = create_action(
            self,
            _("Module..."),
            icon='py.png',
            triggered=lambda: self.new_module(fnames[-1]))
        new_folder_act = create_action(
            self,
            _("Folder..."),
            icon='folder_new.png',
            triggered=lambda: self.new_folder(fnames[-1]))
        new_package_act = create_action(
            self,
            _("Package..."),
            icon=get_icon('package_collapsed.png'),
            triggered=lambda: self.new_package(fnames[-1]))
        return [
            new_file_act, new_folder_act, None, new_module_act, new_package_act
        ]

    def create_file_import_actions(self, fnames):
        """Return actions for submenu 'Import...'"""
        return []

    def create_file_manage_actions(self, fnames):
        """Return file management actions"""
        only_files = all([osp.isfile(_fn) for _fn in fnames])
        only_modules = all([
            osp.splitext(_fn)[1] in ('.py', '.pyw', '.ipy') for _fn in fnames
        ])
        only_valid = all(
            [osp.splitext(_fn)[1] in self.valid_types for _fn in fnames])
        run_action = create_action(self,
                                   _("Run"),
                                   icon="run_small.png",
                                   triggered=self.run)
        edit_action = create_action(self,
                                    _("Edit"),
                                    icon="edit.png",
                                    triggered=self.clicked)
        move_action = create_action(self,
                                    _("Move..."),
                                    icon="move.png",
                                    triggered=self.move)
        delete_action = create_action(self,
                                      _("Delete..."),
                                      icon="delete.png",
                                      triggered=self.delete)
        rename_action = create_action(self,
                                      _("Rename..."),
                                      icon="rename.png",
                                      triggered=self.rename)
        open_action = create_action(self, _("Open"), triggered=self.open)

        actions = []
        if only_modules:
            actions.append(run_action)
        if only_valid and only_files:
            actions.append(edit_action)
        else:
            actions.append(open_action)
        actions += [delete_action, rename_action]
        basedir = fixpath(osp.dirname(fnames[0]))
        if all([fixpath(osp.dirname(_fn)) == basedir for _fn in fnames]):
            actions.append(move_action)
        actions += [None]

        # VCS support is quite limited for now, so we are enabling the VCS
        # related actions only when a single file/folder is selected:
        dirname = fnames[0] if osp.isdir(fnames[0]) else osp.dirname(fnames[0])
        if len(fnames) == 1 and vcs.is_vcs_repository(dirname):
            vcs_ci = create_action(self,
                                   _("Commit"),
                                   icon="vcs_commit.png",
                                   triggered=lambda fnames=[dirname]: self.
                                   vcs_command(fnames, tool='commit'))
            vcs_log = create_action(self,
                                    _("Browse repository"),
                                    icon="vcs_browse.png",
                                    triggered=lambda fnames=[dirname]: self.
                                    vcs_command(fnames, tool='browse'))
            actions += [None, vcs_ci, vcs_log]

        return actions

    def create_folder_manage_actions(self, fnames):
        """Return folder management actions"""
        actions = []
        if os.name == 'nt':
            _title = _("Open command prompt here")
        else:
            _title = _("Open terminal here")
        action = create_action(
            self,
            _title,
            icon="cmdprompt.png",
            triggered=lambda fnames=fnames: self.open_terminal(fnames))
        actions.append(action)
        _title = _("Open Python interpreter here")
        action = create_action(
            self,
            _title,
            icon="python.png",
            triggered=lambda fnames=fnames: self.open_interpreter(fnames))
        actions.append(action)
        return actions

    def create_context_menu_actions(self):
        """Create context menu actions"""
        actions = []
        fnames = self.get_selected_filenames()
        new_actions = self.create_file_new_actions(fnames)
        if len(new_actions) > 1:
            # Creating a submenu only if there is more than one entry
            new_act_menu = QMenu(_('New'), self)
            add_actions(new_act_menu, new_actions)
            actions.append(new_act_menu)
        else:
            actions += new_actions
        import_actions = self.create_file_import_actions(fnames)
        if len(import_actions) > 1:
            # Creating a submenu only if there is more than one entry
            import_act_menu = QMenu(_('Import'), self)
            add_actions(import_act_menu, import_actions)
            actions.append(import_act_menu)
        else:
            actions += import_actions
        if actions:
            actions.append(None)
        if fnames:
            actions += self.create_file_manage_actions(fnames)
        if actions:
            actions.append(None)
        if fnames and all([osp.isdir(_fn) for _fn in fnames]):
            actions += self.create_folder_manage_actions(fnames)
        if actions:
            actions.append(None)
        actions += self.common_actions
        return actions

    def update_menu(self):
        """Update context menu"""
        self.menu.clear()
        add_actions(self.menu, self.create_context_menu_actions())

    #---- Events
    def viewportEvent(self, event):
        """Reimplement Qt method"""

        # Prevent Qt from crashing or showing warnings like:
        # "QSortFilterProxyModel: index from wrong model passed to
        # mapFromSource", probably due to the fact that the file system model
        # is being built. See Issue 1250.
        #
        # This workaround was inspired by the following KDE bug:
        # https://bugs.kde.org/show_bug.cgi?id=172198
        #
        # Apparently, this is a bug from Qt itself.
        self.executeDelayedItemsLayout()

        return QTreeView.viewportEvent(self, event)

    def contextMenuEvent(self, event):
        """Override Qt method"""
        self.update_menu()
        self.menu.popup(event.globalPos())

    def keyPressEvent(self, event):
        """Reimplement Qt method"""
        if event.key() in (Qt.Key_Enter, Qt.Key_Return):
            self.clicked()
        elif event.key() == Qt.Key_F2:
            self.rename()
        elif event.key() == Qt.Key_Delete:
            self.delete()
        else:
            QTreeView.keyPressEvent(self, event)

    def mouseDoubleClickEvent(self, event):
        """Reimplement Qt method"""
        QTreeView.mouseDoubleClickEvent(self, event)
        self.clicked()

    def clicked(self):
        """Selected item was double-clicked or enter/return was pressed"""
        fnames = self.get_selected_filenames()
        for fname in fnames:
            if osp.isdir(fname):
                self.directory_clicked(fname)
            else:
                self.open([fname])

    def directory_clicked(self, dirname):
        """Directory was just clicked"""
        pass

    #---- Drag
    def dragEnterEvent(self, event):
        """Drag and Drop - Enter event"""
        event.setAccepted(event.mimeData().hasFormat("text/plain"))

    def dragMoveEvent(self, event):
        """Drag and Drop - Move event"""
        if (event.mimeData().hasFormat("text/plain")):
            event.setDropAction(Qt.MoveAction)
            event.accept()
        else:
            event.ignore()

    def startDrag(self, dropActions):
        """Reimplement Qt Method - handle drag event"""
        data = QMimeData()
        data.setUrls([QUrl(fname) for fname in self.get_selected_filenames()])
        drag = QDrag(self)
        drag.setMimeData(data)
        drag.exec_()

    #---- File/Directory actions
    def open(self, fnames=None):
        """Open files with the appropriate application"""
        if fnames is None:
            fnames = self.get_selected_filenames()
        for fname in fnames:
            ext = osp.splitext(fname)[1]
            if osp.isfile(fname) and ext in self.valid_types:
                self.parent_widget.sig_open_file.emit(fname)
            else:
                self.open_outside_spyder([fname])

    def open_outside_spyder(self, fnames):
        """Open file outside Spyder with the appropriate application
        If this does not work, opening unknown file in Spyder, as text file"""
        for path in sorted(fnames):
            path = file_uri(path)
            ok = programs.start_file(path)
            if not ok:
                self.parent_widget.emit(SIGNAL("edit(QString)"), path)

    def open_terminal(self, fnames):
        """Open terminal"""
        for path in sorted(fnames):
            self.parent_widget.emit(SIGNAL("open_terminal(QString)"), path)

    def open_interpreter(self, fnames):
        """Open interpreter"""
        for path in sorted(fnames):
            self.parent_widget.emit(SIGNAL("open_interpreter(QString)"), path)

    def run(self, fnames=None):
        """Run Python scripts"""
        if fnames is None:
            fnames = self.get_selected_filenames()
        for fname in fnames:
            self.parent_widget.emit(SIGNAL("run(QString)"), fname)

    def remove_tree(self, dirname):
        """Remove whole directory tree
        Reimplemented in project explorer widget"""
        shutil.rmtree(dirname, onerror=misc.onerror)

    def delete_file(self, fname, multiple, yes_to_all):
        """Delete file"""
        if multiple:
            buttons = QMessageBox.Yes|QMessageBox.YesAll| \
                      QMessageBox.No|QMessageBox.Cancel
        else:
            buttons = QMessageBox.Yes | QMessageBox.No
        if yes_to_all is None:
            answer = QMessageBox.warning(
                self, _("Delete"),
                _("Do you really want "
                  "to delete <b>%s</b>?") % osp.basename(fname), buttons)
            if answer == QMessageBox.No:
                return yes_to_all
            elif answer == QMessageBox.Cancel:
                return False
            elif answer == QMessageBox.YesAll:
                yes_to_all = True
        try:
            if osp.isfile(fname):
                misc.remove_file(fname)
                self.parent_widget.emit(SIGNAL("removed(QString)"), fname)
            else:
                self.remove_tree(fname)
                self.parent_widget.emit(SIGNAL("removed_tree(QString)"), fname)
            return yes_to_all
        except EnvironmentError, error:
            action_str = _('delete')
            QMessageBox.critical(
                self, _("Project Explorer"),
                _("<b>Unable to %s <i>%s</i></b>"
                  "<br><br>Error message:<br>%s") %
                (action_str, fname, unicode(error)))
        return False
예제 #7
0
class DirectoryWidget(RWidget):

    def __init__(self, parent, base="."):
        RWidget.__init__(self, parent)
        self.base = base
        self.model = QFileSystemModel()
        self.model.setRootPath(QDir.rootPath())
        self.proxyModel = FileSystemProxyModel()
        self.proxyModel.setDynamicSortFilter(True)
        self.proxyModel.setFilterKeyColumn(0)
        self.proxyModel.setSourceModel(self.model)
        
        self.listView = QListView(self)
        self.listView.setModel(self.proxyModel)
        index = self.model.index(QDir.currentPath())
        self.listView.setRootIndex(self.proxyModel.mapFromSource(index))
        self.listView.setContextMenuPolicy(Qt.CustomContextMenu)
        self.lineEdit = QLineEdit(self)
        
        filterLineEdit = QLineEdit()
        filterLabel = QLabel("Filter:")
        self.connect(filterLineEdit, SIGNAL("textChanged(QString)"), 
            self.proxyModel.setFilterWildcard)
        self.actions = []

        self.upAction = QAction("&Up", self)
        self.upAction.setStatusTip("Move to parent directory")
        self.upAction.setToolTip("Move to parent directory")
        self.upAction.setIcon(QIcon(":go-up"))
        self.upAction.setEnabled(True)
        self.actions.append(self.upAction)
        self.newAction = QAction("&New Directory", self)
        self.newAction.setStatusTip("Create new directory")
        self.newAction.setToolTip("Create new directory")
        self.newAction.setIcon(QIcon(":folder-new"))
        self.newAction.setEnabled(True)
        self.actions.append(self.newAction)
        self.synchAction = QAction("&Synch", self)
        self.synchAction.setStatusTip("Synch with current working directory")
        self.synchAction.setToolTip("Synch with current working directory")
        self.synchAction.setIcon(QIcon(":view-refresh"))
        self.synchAction.setEnabled(True)
        self.actions.append(self.synchAction)
        self.rmAction = QAction("&Delete", self)
        self.rmAction.setStatusTip("Delete selected item")
        self.rmAction.setToolTip("delete selected item")
        self.rmAction.setIcon(QIcon(":edit-delete"))
        self.rmAction.setEnabled(True)
        self.actions.append(self.rmAction)
        self.openAction = QAction("&Open", self)
        self.openAction.setStatusTip("Open selected R script")
        self.openAction.setToolTip("Open selected R script")
        self.openAction.setIcon(QIcon(":document-open"))
        self.openAction.setEnabled(True)
        self.actions.append(self.openAction)
        self.loadAction = QAction("&Load", self)
        self.loadAction.setStatusTip("Load selected R data")
        self.loadAction.setToolTip("Load selected R data")
        self.loadAction.setIcon(QIcon(":document-open"))
        self.loadAction.setEnabled(True)
        self.actions.append(self.loadAction)
        self.setAction = QAction("Set as &current", self)
        self.setAction.setStatusTip("Set folder as R working directory")
        self.setAction.setToolTip("Set folder as R working directory")
        self.setAction.setIcon(QIcon(":folder-home"))
        self.setAction.setEnabled(True)
        self.actions.append(self.setAction)
        self.loadExternal = QAction("Open &Externally", self)
        self.loadExternal.setStatusTip("Load file in external application")
        self.loadExternal.setToolTip("Load file in external application")
        self.loadExternal.setIcon(QIcon(":folder-system"))
        self.loadExternal.setEnabled(True)
        self.actions.append(self.loadExternal)
        self.rootChanged()
        
        hiddenAction = QAction("Toggle hidden files", self)
        hiddenAction.setStatusTip("Show/hide hidden files and folders")
        hiddenAction.setToolTip("Show/hide hidden files and folders")
        hiddenAction.setIcon(QIcon(":stock_keyring"))
        hiddenAction.setCheckable(True)

        self.connect(self.newAction, SIGNAL("triggered()"), self.newFolder)
        self.connect(self.upAction, SIGNAL("triggered()"), self.upFolder)
        self.connect(self.synchAction, SIGNAL("triggered()"), self.synchFolder)
        self.connect(self.rmAction, SIGNAL("triggered()"), self.rmItem)
        self.connect(self.openAction, SIGNAL("triggered()"), self.openItem)
        self.connect(self.loadAction, SIGNAL("triggered()"), self.loadItem)
        self.connect(self.loadExternal, SIGNAL("triggered()"), self.externalItem)
        self.connect(self.setAction, SIGNAL("triggered()"), self.setFolder)
        self.connect(hiddenAction, SIGNAL("toggled(bool)"), self.toggleHidden)
        self.connect(self.listView, SIGNAL("activated(QModelIndex)"), self.cdFolder)
        self.connect(self.listView, SIGNAL("customContextMenuRequested(QPoint)"), self.customContext)
        self.connect(self.lineEdit, SIGNAL("returnPressed()"), self.gotoFolder)

        upButton = QToolButton()
        upButton.setDefaultAction(self.upAction)
        upButton.setAutoRaise(True)
        newButton = QToolButton()
        newButton.setDefaultAction(self.newAction)
        newButton.setAutoRaise(True)
        synchButton = QToolButton()
        synchButton.setDefaultAction(self.synchAction)
        synchButton.setAutoRaise(True)
        setButton = QToolButton()
        setButton.setDefaultAction(self.setAction)
        setButton.setAutoRaise(True)
        hiddenButton = QToolButton()
        hiddenButton.setDefaultAction(hiddenAction)
        hiddenButton.setAutoRaise(True)

        hbox = QHBoxLayout()
        hbox.addWidget(upButton)
        hbox.addWidget(synchButton)
        hbox.addWidget(newButton)
        hbox.addWidget(setButton)
        hbox.addWidget(hiddenButton)
        vbox = QVBoxLayout(self)
        vbox.addLayout(hbox)
        vbox.addWidget(self.lineEdit)
        vbox.addWidget(self.listView)
        vbox.addWidget(filterLabel)
        vbox.addWidget(filterLineEdit)

    def toggleHidden(self, toggled):
        base = QDir.AllDirs|QDir.AllEntries|QDir.NoDotAndDotDot
        if toggled:
            self.model.setFilter(base|QDir.Hidden)
        else:
            self.model.setFilter(base)

    def gotoFolder(self):
        text = self.lineEdit.text()
        self.listView.setRootIndex(self.proxyModel.mapFromSource(self.model.index(text, 0)))

    def rootChanged(self):
        index1 = self.listView.rootIndex()
        index2 = self.proxyModel.mapToSource(index1)
        self.lineEdit.setText(self.model.filePath(index2))
        self.listView.setCurrentIndex(index1)

    def customContext(self, pos):
        index = self.listView.indexAt(pos)
        index = self.proxyModel.mapToSource(index)
        if not index.isValid():
            self.rmAction.setEnabled(False)
            self.openAction.setEnabled(False)
            self.loadAction.setEnabled(False)
        elif not self.model.isDir(index):
            info = self.model.fileInfo(index)
            suffix = info.suffix()
            if suffix in ("Rd","Rdata","RData"):
                self.loadAction.setEnabled(True)
                self.openAction.setEnabled(False)
                self.loadExternal.setEnabled(False)
            elif suffix in ("txt","csv","R","r"):
                self.openAction.setEnabled(True)
                self.loadAction.setEnabled(False)
                self.loadExternal.setEnabled(True)
            else:
                self.loadAction.setEnabled(False)
                self.openAction.setEnabled(False)
                self.loadExternal.setEnabled(True)
        menu = QMenu(self)
        for action in self.actions:
            menu.addAction(action)
        menu.exec_(self.listView.mapToGlobal(pos))

    def openItem(self):
        index = self.listView.currentIndex()
        index = self.proxyModel.mapToSource(index)
        self.emit(SIGNAL("openFileRequest(QString)"),
        self.model.filePath(index))

    def loadItem(self):
        index = self.listView.currentIndex()
        index = self.proxyModel.mapToSource(index)
        self.emit(SIGNAL("loadFileRequest(QString)"),
        self.model.filePath(index))
        
    def externalItem(self):
        index = self.listView.currentIndex()
        index = self.proxyModel.mapToSource(index)
        QDesktopServices.openUrl(QUrl(self.model.filePath(index)))

    def newFolder(self):
        text, ok = QInputDialog.getText(self,
            "New Folder", "Folder name:", QLineEdit.Normal,
            "new_folder")
        if ok:
            index = self.listView.rootIndex()
            index = self.proxyModel.mapToSource(index)
            self.model.mkdir(index, text)

    def setFolder(self):
        index = self.listView.currentIndex()
        index = self.proxyModel.mapToSource(index)
        commands = "setwd('%s')" % self.model.filePath(index)
        self.emitCommands(commands)

    def rmItem(self):
        index = self.listView.currentIndex()
        if index == self.listView.rootIndex():
            return
        yes = QMessageBox.question(self, "manageR Warning",
            "Are you sure you want to delete '%s'?" % self.model.fileName(index),
            QMessageBox.Yes|QMessageBox.Cancel)
        if not yes == QMessageBox.Yes:
            return
        index = self.proxyModel.mapToSource(index)
        if self.model.isDir(index):
            result = self.model.rmdir(index)
        else:
            result = self.model.remove(index)
        if not result:
            QMessageBox.warning(self, "manageR Error",
            "Unable to delete %s!" % self.model.fileName(index))

    def upFolder(self):
        index = self.listView.rootIndex()
        index = self.proxyModel.parent(index)
        self.listView.setRootIndex(index)
        self.rootChanged()

    def cdFolder(self):
        indexes = self.listView.selectedIndexes()
        if len(indexes) < 1:
            return
        index = indexes[0]
        if self.model.isDir(self.proxyModel.mapToSource(index)):
            self.listView.setRootIndex(index)
        self.rootChanged()
        self.listView.clearSelection()

    def synchFolder(self):
        text = robjects.r.getwd()[0]
        index = self.model.index(text, 0)
        index = self.proxyModel.mapFromSource(index)
        self.listView.setRootIndex(index)
        self.rootChanged()
예제 #8
0
파일: explorer.py 프로젝트: koll00/Gui_SM
class DirView(QTreeView):
    """Base file/directory tree view"""

    def __init__(self, parent=None):
        super(DirView, self).__init__(parent)
        self.name_filters = None
        self.parent_widget = parent
        self.valid_types = None
        self.show_all = None
        self.menu = None
        self.common_actions = None
        self.__expanded_state = None
        self._to_be_loaded = None
        self.fsmodel = None
        self.setup_fs_model()
        self._scrollbar_positions = None

    # ---- Model
    def setup_fs_model(self):
        """Setup filesystem model"""
        filters = QDir.AllDirs | QDir.Files | QDir.Drives | QDir.NoDotAndDotDot
        self.fsmodel = QFileSystemModel(self)
        self.fsmodel.setFilter(filters)
        self.fsmodel.setNameFilterDisables(False)

    def install_model(self):
        """Install filesystem model"""
        self.setModel(self.fsmodel)

    def setup_view(self):
        """Setup view"""
        self.install_model()
        self.connect(self.fsmodel, SIGNAL("directoryLoaded(QString)"), lambda: self.resizeColumnToContents(0))
        self.setAnimated(False)
        self.setSortingEnabled(True)
        self.sortByColumn(0, Qt.AscendingOrder)

    def set_name_filters(self, name_filters):
        """Set name filters"""
        self.name_filters = name_filters
        self.fsmodel.setNameFilters(name_filters)

    def set_show_all(self, state):
        """Toggle 'show all files' state"""
        if state:
            self.fsmodel.setNameFilters([])
        else:
            self.fsmodel.setNameFilters(self.name_filters)

    def get_filename(self, index):
        """Return filename associated with *index*"""
        if index:
            return osp.normpath(unicode(self.fsmodel.filePath(index)))

    def get_index(self, filename):
        """Return index associated with filename"""
        return self.fsmodel.index(filename)

    def get_selected_filenames(self):
        """Return selected filenames"""
        if self.selectionMode() == self.ExtendedSelection:
            return [self.get_filename(idx) for idx in self.selectedIndexes()]
        else:
            return [self.get_filename(self.currentIndex())]

    def get_dirname(self, index):
        """Return dirname associated with *index*"""
        fname = self.get_filename(index)
        if fname:
            if osp.isdir(fname):
                return fname
            else:
                return osp.dirname(fname)

    # ---- Tree view widget
    def setup(self, name_filters=["*.py", "*.pyw"], valid_types=(".py", ".pyw"), show_all=False):
        """Setup tree widget"""
        self.setup_view()

        self.set_name_filters(name_filters)
        self.valid_types = valid_types
        self.show_all = show_all

        # Setup context menu
        self.menu = QMenu(self)
        self.common_actions = self.setup_common_actions()

    # ---- Context menu
    def setup_common_actions(self):
        """Setup context menu common actions"""
        # Filters
        filters_action = create_action(
            self, _("Edit filename filters..."), None, get_icon("filter.png"), triggered=self.edit_filter
        )
        # Show all files
        all_action = create_action(self, _("Show all files"), toggled=self.toggle_all)
        all_action.setChecked(self.show_all)
        self.toggle_all(self.show_all)

        return [filters_action, all_action]

    def edit_filter(self):
        """Edit name filters"""
        filters, valid = QInputDialog.getText(
            self, _("Edit filename filters"), _("Name filters:"), QLineEdit.Normal, ", ".join(self.name_filters)
        )
        if valid:
            filters = [f.strip() for f in unicode(filters).split(",")]
            self.parent_widget.sig_option_changed.emit("name_filters", filters)
            self.set_name_filters(filters)

    def toggle_all(self, checked):
        """Toggle all files mode"""
        self.parent_widget.sig_option_changed.emit("show_all", checked)
        self.show_all = checked
        self.set_show_all(checked)

    def create_file_new_actions(self, fnames):
        """Return actions for submenu 'New...'"""
        if not fnames:
            return []
        new_file_act = create_action(
            self, _("File..."), icon="filenew.png", triggered=lambda: self.new_file(fnames[-1])
        )
        new_module_act = create_action(
            self, _("Module..."), icon="py.png", triggered=lambda: self.new_module(fnames[-1])
        )
        new_folder_act = create_action(
            self, _("Folder..."), icon="folder_new.png", triggered=lambda: self.new_folder(fnames[-1])
        )
        new_package_act = create_action(
            self,
            _("Package..."),
            icon=get_icon("package_collapsed.png"),
            triggered=lambda: self.new_package(fnames[-1]),
        )
        return [new_file_act, new_folder_act, None, new_module_act, new_package_act]

    def create_file_import_actions(self, fnames):
        """Return actions for submenu 'Import...'"""
        return []

    def create_file_manage_actions(self, fnames):
        """Return file management actions"""
        only_files = all([osp.isfile(_fn) for _fn in fnames])
        only_modules = all([osp.splitext(_fn)[1] in (".py", ".pyw", ".ipy") for _fn in fnames])
        only_valid = all([osp.splitext(_fn)[1] in self.valid_types for _fn in fnames])
        run_action = create_action(self, _("Run"), icon="run_small.png", triggered=self.run)
        edit_action = create_action(self, _("Edit"), icon="edit.png", triggered=self.clicked)
        move_action = create_action(self, _("Move..."), icon="move.png", triggered=self.move)
        delete_action = create_action(self, _("Delete..."), icon="delete.png", triggered=self.delete)
        rename_action = create_action(self, _("Rename..."), icon="rename.png", triggered=self.rename)
        open_action = create_action(self, _("Open"), triggered=self.open)

        actions = []
        if only_modules:
            actions.append(run_action)
        if only_valid and only_files:
            actions.append(edit_action)
        else:
            actions.append(open_action)
        actions += [delete_action, rename_action]
        basedir = fixpath(osp.dirname(fnames[0]))
        if all([fixpath(osp.dirname(_fn)) == basedir for _fn in fnames]):
            actions.append(move_action)
        actions += [None]

        # VCS support is quite limited for now, so we are enabling the VCS
        # related actions only when a single file/folder is selected:
        dirname = fnames[0] if osp.isdir(fnames[0]) else osp.dirname(fnames[0])
        if len(fnames) == 1 and vcs.is_vcs_repository(dirname):
            vcs_ci = create_action(
                self,
                _("Commit"),
                icon="vcs_commit.png",
                triggered=lambda fnames=[dirname]: self.vcs_command(fnames, tool="commit"),
            )
            vcs_log = create_action(
                self,
                _("Browse repository"),
                icon="vcs_browse.png",
                triggered=lambda fnames=[dirname]: self.vcs_command(fnames, tool="browse"),
            )
            actions += [None, vcs_ci, vcs_log]

        return actions

    def create_folder_manage_actions(self, fnames):
        """Return folder management actions"""
        actions = []
        if os.name == "nt":
            _title = _("Open command prompt here")
        else:
            _title = _("Open terminal here")
        action = create_action(
            self, _title, icon="cmdprompt.png", triggered=lambda fnames=fnames: self.open_terminal(fnames)
        )
        actions.append(action)
        _title = _("Open Python interpreter here")
        action = create_action(
            self, _title, icon="python.png", triggered=lambda fnames=fnames: self.open_interpreter(fnames)
        )
        actions.append(action)
        return actions

    def create_context_menu_actions(self):
        """Create context menu actions"""
        actions = []
        fnames = self.get_selected_filenames()
        new_actions = self.create_file_new_actions(fnames)
        if len(new_actions) > 1:
            # Creating a submenu only if there is more than one entry
            new_act_menu = QMenu(_("New"), self)
            add_actions(new_act_menu, new_actions)
            actions.append(new_act_menu)
        else:
            actions += new_actions
        import_actions = self.create_file_import_actions(fnames)
        if len(import_actions) > 1:
            # Creating a submenu only if there is more than one entry
            import_act_menu = QMenu(_("Import"), self)
            add_actions(import_act_menu, import_actions)
            actions.append(import_act_menu)
        else:
            actions += import_actions
        if actions:
            actions.append(None)
        if fnames:
            actions += self.create_file_manage_actions(fnames)
        if actions:
            actions.append(None)
        if fnames and all([osp.isdir(_fn) for _fn in fnames]):
            actions += self.create_folder_manage_actions(fnames)
        if actions:
            actions.append(None)
        actions += self.common_actions
        return actions

    def update_menu(self):
        """Update context menu"""
        self.menu.clear()
        add_actions(self.menu, self.create_context_menu_actions())

    # ---- Events
    def viewportEvent(self, event):
        """Reimplement Qt method"""

        # Prevent Qt from crashing or showing warnings like:
        # "QSortFilterProxyModel: index from wrong model passed to
        # mapFromSource", probably due to the fact that the file system model
        # is being built. See Issue 1250.
        #
        # This workaround was inspired by the following KDE bug:
        # https://bugs.kde.org/show_bug.cgi?id=172198
        #
        # Apparently, this is a bug from Qt itself.
        self.executeDelayedItemsLayout()

        return QTreeView.viewportEvent(self, event)

    def contextMenuEvent(self, event):
        """Override Qt method"""
        self.update_menu()
        self.menu.popup(event.globalPos())

    def keyPressEvent(self, event):
        """Reimplement Qt method"""
        if event.key() in (Qt.Key_Enter, Qt.Key_Return):
            self.clicked()
        elif event.key() == Qt.Key_F2:
            self.rename()
        elif event.key() == Qt.Key_Delete:
            self.delete()
        else:
            QTreeView.keyPressEvent(self, event)

    def mouseDoubleClickEvent(self, event):
        """Reimplement Qt method"""
        QTreeView.mouseDoubleClickEvent(self, event)
        self.clicked()

    def clicked(self):
        """Selected item was double-clicked or enter/return was pressed"""
        fnames = self.get_selected_filenames()
        for fname in fnames:
            if osp.isdir(fname):
                self.directory_clicked(fname)
            else:
                self.open([fname])

    def directory_clicked(self, dirname):
        """Directory was just clicked"""
        pass

    # ---- Drag
    def dragEnterEvent(self, event):
        """Drag and Drop - Enter event"""
        event.setAccepted(event.mimeData().hasFormat("text/plain"))

    def dragMoveEvent(self, event):
        """Drag and Drop - Move event"""
        if event.mimeData().hasFormat("text/plain"):
            event.setDropAction(Qt.MoveAction)
            event.accept()
        else:
            event.ignore()

    def startDrag(self, dropActions):
        """Reimplement Qt Method - handle drag event"""
        data = QMimeData()
        data.setUrls([QUrl(fname) for fname in self.get_selected_filenames()])
        drag = QDrag(self)
        drag.setMimeData(data)
        drag.exec_()

    # ---- File/Directory actions
    def open(self, fnames=None):
        """Open files with the appropriate application"""
        if fnames is None:
            fnames = self.get_selected_filenames()
        for fname in fnames:
            ext = osp.splitext(fname)[1]
            if osp.isfile(fname) and ext in self.valid_types:
                self.parent_widget.sig_open_file.emit(fname)
            else:
                self.open_outside_spyder([fname])

    def open_outside_spyder(self, fnames):
        """Open file outside Spyder with the appropriate application
        If this does not work, opening unknown file in Spyder, as text file"""
        for path in sorted(fnames):
            path = file_uri(path)
            ok = programs.start_file(path)
            if not ok:
                self.parent_widget.emit(SIGNAL("edit(QString)"), path)

    def open_terminal(self, fnames):
        """Open terminal"""
        for path in sorted(fnames):
            self.parent_widget.emit(SIGNAL("open_terminal(QString)"), path)

    def open_interpreter(self, fnames):
        """Open interpreter"""
        for path in sorted(fnames):
            self.parent_widget.emit(SIGNAL("open_interpreter(QString)"), path)

    def run(self, fnames=None):
        """Run Python scripts"""
        if fnames is None:
            fnames = self.get_selected_filenames()
        for fname in fnames:
            self.parent_widget.emit(SIGNAL("run(QString)"), fname)

    def remove_tree(self, dirname):
        """Remove whole directory tree
        Reimplemented in project explorer widget"""
        shutil.rmtree(dirname, onerror=misc.onerror)

    def delete_file(self, fname, multiple, yes_to_all):
        """Delete file"""
        if multiple:
            buttons = QMessageBox.Yes | QMessageBox.YesAll | QMessageBox.No | QMessageBox.Cancel
        else:
            buttons = QMessageBox.Yes | QMessageBox.No
        if yes_to_all is None:
            answer = QMessageBox.warning(
                self, _("Delete"), _("Do you really want " "to delete <b>%s</b>?") % osp.basename(fname), buttons
            )
            if answer == QMessageBox.No:
                return yes_to_all
            elif answer == QMessageBox.Cancel:
                return False
            elif answer == QMessageBox.YesAll:
                yes_to_all = True
        try:
            if osp.isfile(fname):
                misc.remove_file(fname)
                self.parent_widget.emit(SIGNAL("removed(QString)"), fname)
            else:
                self.remove_tree(fname)
                self.parent_widget.emit(SIGNAL("removed_tree(QString)"), fname)
            return yes_to_all
        except EnvironmentError, error:
            action_str = _("delete")
            QMessageBox.critical(
                self,
                _("Project Explorer"),
                _("<b>Unable to %s <i>%s</i></b>" "<br><br>Error message:<br>%s") % (action_str, fname, unicode(error)),
            )
        return False
예제 #9
0
파일: main.py 프로젝트: eustas/PyQtures
class Window(QMainWindow):

  def __init__(self):
    super(Window, self).__init__()

    central_widget = QWidget()

    self._current_path = None
    self._use_suffix = False

    self._file_model = QFileSystemModel()
    self._file_model.setNameFilters(['*.jpg', '*.png'])
    self._file_model.setNameFilterDisables(False)
    self._file_model.setRootPath(QDir.rootPath())

    self._file_selection_model = QItemSelectionModel(self._file_model)
    self._file_selection_model.currentChanged.connect(self._on_current_file_changed)

    self._file_tree = QTreeView(parent=self)
    self._file_tree.collapsed.connect(self._on_tree_expanded_collapsed)
    self._file_tree.expanded.connect(self._on_tree_expanded_collapsed)
    self._file_tree.setModel(self._file_model)
    self._file_tree.setSelectionModel(self._file_selection_model)
    self._file_tree.setColumnHidden(1, True)
    self._file_tree.setColumnHidden(2, True)
    self._file_tree.setColumnHidden(3, True)
    self._file_tree.header().hide()

    self._viewer = Viewer(Loader(24))

    self._splitter = QSplitter();
    self._splitter.addWidget(self._file_tree)
    self._splitter.addWidget(self._viewer)
    self._splitter.setStretchFactor(0, 0)
    self._splitter.setStretchFactor(1, 1)
    self._splitter.setCollapsible(0, False)

    self._layout = QGridLayout()
    self._layout.addWidget(self._splitter)
    self._switch_to_normal()
    central_widget.setLayout(self._layout)

    self._file_tree.installEventFilter(self);

    self.resize(800, 600)
    self.setWindowTitle('pyQtures')
    self.setCentralWidget(central_widget)
    self.show()

  def eventFilter(self, widget, event):
    if event.type() == QEvent.KeyPress:
      if event.key() == Qt.Key_Tab:
        self._toggle_path_suffix()
        return True
    return QMainWindow.eventFilter(self, widget, event)

  def _toggle_path_suffix(self):
    self._use_suffix = not self._use_suffix
    self._update_path()

  def _switch_to_fullscreen(self):
    self._splitter.widget(0).hide()
    self._layout.setMargin(0)
    self.showFullScreen()

  def _switch_to_normal(self):
    self._splitter.widget(0).show()
    self._layout.setMargin(4)
    self.showNormal()

  def keyPressEvent(self, key_event):  # Signal handler.
    key = key_event.key()
    if self.isFullScreen():
      self._full_screen_key_handler(key)
    else:
      self._normal_key_handler(key)

  def _full_screen_key_handler(self, key):
    if Qt.Key_Escape == key:
      self._switch_to_normal()
    elif Qt.Key_Return == key:
      self._switch_to_normal()
    elif Qt.Key_Up == key:
      self._go_to_sibling_image(-1)
    elif Qt.Key_Down == key:
      self._go_to_sibling_image(1)
    elif Qt.Key_Tab == key:
      self._toggle_path_suffix()

  def _go_to_sibling_image(self, offset):
    current = self._file_selection_model.currentIndex()
    nxt = current.sibling(current.row() + offset, current.column())
    if (nxt.parent() != current.parent()):
      return
    # TODO(eustas): Iterate through dirs?
    self._file_selection_model.setCurrentIndex(nxt, QItemSelectionModel.SelectCurrent)

  def _normal_key_handler(self, key):
    if Qt.Key_Escape == key:
      QCoreApplication.instance().quit()
    elif Qt.Key_Return == key:
      self._switch_to_fullscreen()

  def _on_current_file_changed(self, new_current):
    new_path = self._file_model.filePath(new_current)
    if not self._current_path == new_path:
        self._current_path = new_path
        self._update_path()

  def _update_path(self):
    if not self._use_suffix:
      self._viewer.set_path(self._current_path)
      return

    self._viewer.reset_path()
    if not self._current_path:
      return

    selected_file = QFileInfo(self._current_path)
    if not selected_file.exists():
      return

    selected_dir = selected_file.absoluteDir()
    file_name = selected_file.fileName()
    if not selected_dir.exists():
      return

    if not selected_dir.cd('converted'):
      return

    suffixed_path = selected_dir.absoluteFilePath(file_name)
    self._viewer.set_path(suffixed_path)

  def _on_tree_expanded_collapsed(self, unused_index):
    QTimer.singleShot(1, lambda: self._file_tree.resizeColumnToContents(0))
예제 #10
0
class MainWindow(QWidget):
    
    '''
    The initial method creates the window and connects the rename method.
    '''
    def __init__(self):
        QWidget.__init__(self)
        
        self.setWindowTitle("cuteRenamer")

        #Set Data-Model for showing the directories
        self.dirModel = QFileSystemModel()
        self.dirModel.setRootPath('/')
        self.dirModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)#Show only directories without '.' and '..'
        #Set the view for the directories
        self.dirView = QTreeView()
        self.dirView.setModel(self.dirModel)
        #Show only the directories in the view
        self.dirView.setColumnHidden(1, True)
        self.dirView.setColumnHidden(2, True)
        self.dirView.setColumnHidden(3, True)
        
        self.dirView.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        
        #Listedit for the optional listfile
        listPathLabel = QLabel("Path to list:")
        self.listPathEdit = QLineEdit()
        
        #Start renaming with number...
        startLabel = QLabel("Start (default is 1)")
        self.startEdit = QLineEdit()
        
        #LineEdit for the prefix
        prefixLabel = QLabel("Prefix")
        self.prefixEdit = QLineEdit()
        
        #LineEdit for the postfix
        postfixLabel = QLabel("Postfix")
        self.postfixEdit = QLineEdit()
        
        #Checkbox to conserve file extensions
        self.checkboxConserve = QCheckBox("Conserve file extensions")
        checkboxLayout = QHBoxLayout()
        checkboxLayout.addStretch(1)
        checkboxLayout.addWidget(self.checkboxConserve)
        
        #The button to start renaming
        renameButton = QPushButton('Rename!')
        buttonsLayout = QHBoxLayout()
        buttonsLayout.addStretch(1)
        buttonsLayout.addWidget(renameButton)
        
        vertical = QVBoxLayout()
        vertical.addWidget(self.dirView)
        vertical.addSpacing(10)
        vertical.addWidget(listPathLabel)
        vertical.addWidget(self.listPathEdit)
        vertical.addSpacing(10)
        vertical.addWidget(startLabel)
        vertical.addWidget(self.startEdit)
        vertical.addSpacing(10)
        vertical.addWidget(prefixLabel)
        vertical.addWidget(self.prefixEdit)
        vertical.addSpacing(10)
        vertical.addWidget(postfixLabel)
        vertical.addWidget(self.postfixEdit)
        vertical.addSpacing(10)
        vertical.addLayout(checkboxLayout)
        vertical.addSpacing(20)
        vertical.addLayout(buttonsLayout)
        
        self.setLayout(vertical)
        
        #If the button is clicked start the renaming
        self.connect(renameButton, SIGNAL('clicked()'), self.rename)
    
    '''
    This method prepares all options and starts the rename progress.
    '''
    def rename(self):
        selectedIndex = self.dirView.selectedIndexes()
        
        if self.listPathEdit.text() == "":
            print "Read the whole directory"
            
            files = os.listdir(self.dirModel.filePath(selectedIndex[0]))
        
        elif (not self.listPathEdit.text() == "") and os.path.isfile(self.listPathEdit.text()):
            print "Read filenames from %s" % self.listPathEdit.text()
            
            files = [i.rstrip('\n') for i in open(self.listPathEdit.text(), "r")]
        
        else:
            print "Path to list doesn't exist or is not a file!"
        
        if not self.startEdit.text() == "":
            start = int(self.startEdit.text())
        
        else:
            start = 1
        
        prefix = self.prefixEdit.text()
        postfix = self.postfixEdit.text()
        
        if self.checkboxConserve.isChecked():
            conserve = True
        else:
            conserve = False
        
        print "Start: %d\nPrefix: %s\nPostfix: %s\nConserve: %s" % (start, prefix, postfix, conserve)
        print "Change directory"
        
        os.chdir(self.dirModel.filePath(selectedIndex[0]))
        
        rename_files(start, prefix, postfix, conserve, files)
    
    '''
    A simple close event.
    '''
    def closeEvent(self, event):
        print "Quit application"
        exit()
예제 #11
0
class EncryptDialog(QDialog):
    def __init__(self):
        self.techniquesClass = {
            'caesar cipher': caesarCipher,
            'mono alphabetic cipher': monoAlphabeticCipher,
            'vigenere cipher': vigenereCipher,
            'vernan cipher': vernanCipher,
            'one time pad': oneTimePad
        }

        self.rowsview = []
        self.filesview = []
        self.techniques = []

        QDialog.__init__(self)
        self.setWindowTitle("CryptoSystems")
        self.resize(1024, 600)
        self.setMinimumSize(QSize(1024, 600))
        self.setMaximumSize(QSize(1024, 600))

        self.checkBox_2 = QCheckBox(self)
        self.checkBox_2.setGeometry(QRect(620, 10, 130, 20))
        self.checkBox_2.setText('Select All')
        self.checkBox_2.clicked.connect(self.__selectAllFiles)

        self.treeView = QTreeView(self)
        self.treeView.setGeometry(QRect(10, 10, 230, 580))
        self.treeView.setObjectName("treeView")

        self.fileSystemModel = QFileSystemModel(self.treeView)
        self.fileSystemModel.setReadOnly(False)

        self.fileSystemModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
        root = self.fileSystemModel.setRootPath("/")
        self.treeView.setModel(self.fileSystemModel)
        self.treeView.setRootIndex(root)
        self.treeView.hideColumn(1)
        self.treeView.hideColumn(2)
        self.treeView.hideColumn(3)
        self.treeView.clicked.connect(self.__eventDirectoryChanged)

        self.mygroupbox = QGroupBox(self)
        self.mygroupbox.setGeometry(QRect(0, 0, 1000, 1000))
        self.myform = QFormLayout()
        for j in list(range(100)):
            horizontalLayout = QHBoxLayout()
            self.myform.addRow(horizontalLayout)
            self.rowsview.append(horizontalLayout)

        self.mygroupbox.setLayout(self.myform)
        scroll = QScrollArea(self)
        scroll.setWidget(self.mygroupbox)
        scroll.setWidgetResizable(True)
        scroll.setGeometry(QRect(250, 30, 500, 580))
        scroll.setWidgetResizable(True)

        self.label_4 = QLabel(self)
        self.label_4.setGeometry(QRect(780, 30, 31, 16))
        self.label_4.setPixmap(QPixmap("images/key.png"))
        self.label_4.setScaledContents(True)

        self.lineEdit = QLineEdit(self)
        self.lineEdit.setGeometry(QRect(820, 30, 180, 20))
        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit.setPlaceholderText(_fromUtf8('write your password'))
        self.lineEdit.setEchoMode(QLineEdit.Password)

        self.techniquesGroup = QGroupBox(self)
        self.tecniquesform = QFormLayout()
        self.techniquesGroup.setLayout(self.tecniquesform)

        self.techniquesScroll = QScrollArea(self)
        self.techniquesScroll.setGeometry(QRect(770, 100, 230, 300))
        self.techniquesScroll.setWidget(self.techniquesGroup)
        self.techniquesScroll.setWidgetResizable(True)

        self.rowsTechiques = []
        for i in list(range(8)):
            horizontalLayout = QHBoxLayout()
            self.tecniquesform.addRow(horizontalLayout)
            self.rowsTechiques.append(horizontalLayout)

        techniquesCombo = QComboBox()
        techniquesCombo.setGeometry(QRect(10, 50, 171, 22))
        techniquesCombo.addItems(self.techniquesClass.keys())
        self.techniques.append(techniquesCombo)
        self.rowsTechiques[0].addWidget(techniquesCombo)
        self.techniquesNumber = 1

        self.addTechnique = QPushButton()
        self.addTechnique.setGeometry(QRect(90, 90, 31, 21))
        self.addTechnique.setFixedSize(31, 21)
        self.addTechnique.setText('+')
        self.connect(self.addTechnique, SIGNAL("clicked()"),
                     self.__eventAddTechnique)
        self.rowsTechiques[len(self.rowsTechiques) - 1].addWidget(
            self.addTechnique)

        self.okButton = QPushButton(self)
        self.okButton.setGeometry(QRect(920, 560, 80, 20))
        self.okButton.setText('Start...')
        self.connect(self.okButton, SIGNAL("clicked()"),
                     self.__eventInitEncryption)

    def __eventAddTechnique(self):
        techniquesCombo = QComboBox()
        techniquesCombo.setGeometry(QRect(10, 50, 171, 22))
        techniquesCombo.addItems(self.techniquesClass.keys())
        self.techniques.append(techniquesCombo)
        self.rowsTechiques[self.techniquesNumber].addWidget(techniquesCombo)
        self.techniquesNumber = self.techniquesNumber + 1
        if ((len(self.rowsTechiques) - 1) == self.techniquesNumber):
            self.addTechnique.setEnabled(False)

    def __eventDirectoryChanged(self):
        index = self.treeView.currentIndex()
        self.__changeDirectory(self.fileSystemModel.filePath(index))

    def __changeDirectory(self, path):
        for c in self.filesview:
            c.setParent(None)
            c.deleteLater()
        self.filesview = []
        self.checkBox_2.setChecked(False)

        self.progressBars = {}
        for f in self.__getFiles(path):
            try:
                group = QGroupBox(f, self)
                group.setGeometry(QRect(20, 20, 100, 150))
                group.setCheckable(True)
                group.setChecked(False)
                group.setFixedSize(100, 150)
                group.setFlat(True)
                group.setToolTip(f)

                label = QLabel(group)
                label.setScaledContents(True)
                label.setGeometry(QRect(5, 25, 90, 90))
                label.setToolTip(f)

                progressBar = QProgressBar(group)
                progressBar.setGeometry(QRect(0, 70, 111, 10))
                progressBar.setProperty("value", 0)
                progressBar.setTextVisible(False)
                progressBar.setToolTip('0%')
                progressBar.setVisible(False)
                self.progressBars[f] = progressBar

                self.filesview.append(group)
                from os.path import isfile
                if isfile(path + '/' + f):
                    ext = f.split('.')[-1]
                    if isfile('icons/' + ext.lower() + '.png'):
                        label.setPixmap(
                            QPixmap('icons/' + ext.lower() + '.png'))
                    else:
                        label.setPixmap(QPixmap('icons/default.png'))
                else:
                    label.setPixmap(QPixmap('icons/folder.png'))
                self.connect(group, SIGNAL("clicked()"), self.__deselectFile)
            except ValueError:
                pass

        i = 0
        for x in list(range(len(self.filesview))):
            if (x % 4) == 0:
                i = i + 1
            self.rowsview[i].addWidget(self.filesview[x])

    def __selectAllFiles(self):
        for o in self.filesview:
            o.setChecked(self.checkBox_2.isChecked())

    def __deselectFile(self):
        #print 'deselect'
        self.checkBox_2.setChecked(False)

    def __arrozconpollo(self):
        self.__obtainSelectedFIles()

    def __obtainSelectedFIles(self):
        files = []
        for o in self.filesview:
            if o.isChecked():
                files.append(str(o.title()))
                self.progressBars[str(o.title())].setVisible(True)
        return files

    def __getFiles(self, path):
        from os import listdir
        from os.path import isfile

        f = []

        for base in listdir(path):
            try:
                if isfile(path + '/' + base):
                    f.append(base)
            except ValueError:
                pass
        f.sort()
        return f

    def __eventInitEncryption(self):
        if len(self.__obtainSelectedFIles()) == 0:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText("You must specify the files you want to encrypt")
            msg.setWindowTitle("CryptoSystems")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()
            return

        if str(self.lineEdit.text()).strip() == '':
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText("You must specify a key")
            msg.setWindowTitle("CryptoSystems")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()
            return

        self.okButton.setEnabled(False)
        self.techniquesGroup.setEnabled(False)
        self.lineEdit.setEnabled(False)

        index = self.treeView.currentIndex()

        path = self.fileSystemModel.filePath(index)
        selectedFiles = self.__obtainSelectedFIles()

        from os.path import getsize
        blockSize = 4096

        from hashlib import md5
        Hash = md5()
        Hash.update(str(self.lineEdit.text()))
        key = Hash.hexdigest()

        for f in selectedFiles:

            f_in = open(path + '/' + f, 'rb')
            f_out = open(
                path + '/' + reduceMd5(checksum(path + '/' + f)) + '.cry',
                'wb')

            f_out.write('CRYOGENESIS' + unhexlify('00') + 'ARCHIVE' +
                        unhexlify('01'))

            header_list = ''
            techniquesObjects = []
            for t in self.techniques:
                header_list = header_list + t.currentText() + ':'
                techniquesObjects.append(self.techniquesClass[str(
                    t.currentText())](key))

            file_header = str('header|' + str(f_in.name.split('/')[-1]) + '|' +
                              str(header_list) + '|' +
                              str(checksum(path + '/' + f)))

            aes = AES(key)
            f_out.write(aes.encrypt(file_header))
            f_out.write(unhexlify('02'))

            in_size = getsize(path + '/' + f)
            in_progress = 0.0

            block = f_in.read(blockSize)
            while (block):
                block_c = block
                for t in techniquesObjects:
                    block_c = t.encrypt(block_c)
                f_out.write(block_c)
                in_progress = in_progress + blockSize

                progress = (in_progress / in_size) * 100
                #print progress
                self.progressBars[str(f)].setProperty("value", int(progress))
                self.progressBars[str(f)].setToolTip(str(progress) + '%')
                block = f_in.read(blockSize)

            f_in.close()
            f_out.close()

        msg = QMessageBox()

        msg.setIcon(QMessageBox.Information)

        msg.setText("Encryption has successfully concluded")
        msg.setWindowTitle("CryptoSystems")
        msg.setStandardButtons(QMessageBox.Ok)
        msg.exec_()

        self.hide()
예제 #12
0
class DecryptDialog(QDialog):
    def __init__(self):
        self.techniquesClass = {
            'caesar cipher': caesarCipher,
            'mono alphabetic cipher': monoAlphabeticCipher,
            'vigenere cipher': vigenereCipher,
            'vernan cipher': vernanCipher,
            'one time pad': oneTimePad
        }

        self.rowsview = []
        self.filesview = []
        #self.techniques = []

        QDialog.__init__(self)
        self.setWindowTitle("Desencriptador de Cryogenesis Systems.")
        self.resize(1024, 600)
        self.setMinimumSize(QSize(1024, 600))
        self.setMaximumSize(QSize(1024, 600))

        self.checkBox_2 = QCheckBox(self)
        self.checkBox_2.setGeometry(QRect(620, 10, 130, 20))
        self.checkBox_2.setText('seleccionar todos')
        self.checkBox_2.clicked.connect(self.__selectAllFiles)

        self.treeView = QTreeView(self)
        self.treeView.setGeometry(QRect(10, 10, 230, 580))
        self.treeView.setObjectName("treeView")

        self.fileSystemModel = QFileSystemModel(self.treeView)
        self.fileSystemModel.setReadOnly(False)

        self.fileSystemModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
        root = self.fileSystemModel.setRootPath("/")
        self.treeView.setModel(self.fileSystemModel)
        self.treeView.setRootIndex(root)
        self.treeView.hideColumn(1)
        self.treeView.hideColumn(2)
        self.treeView.hideColumn(3)
        self.treeView.clicked.connect(self.__eventDirectoryChanged)

        self.mygroupbox = QGroupBox(self)
        self.mygroupbox.setGeometry(QRect(0, 0, 1000, 1000))
        self.myform = QFormLayout()
        for j in list(range(100)):
            horizontalLayout = QHBoxLayout()
            self.myform.addRow(horizontalLayout)
            self.rowsview.append(horizontalLayout)

        self.mygroupbox.setLayout(self.myform)
        scroll = QScrollArea(self)
        scroll.setWidget(self.mygroupbox)
        scroll.setWidgetResizable(True)
        scroll.setGeometry(QRect(250, 30, 500, 580))
        scroll.setWidgetResizable(True)

        self.label_4 = QLabel(self)
        self.label_4.setGeometry(QRect(780, 30, 31, 16))
        self.label_4.setPixmap(QPixmap("images/key.png"))
        self.label_4.setScaledContents(True)

        self.lineEdit = QLineEdit(self)
        self.lineEdit.setGeometry(QRect(820, 30, 180, 20))
        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit.setPlaceholderText(_fromUtf8('escriba su contraseña'))
        self.lineEdit.setEchoMode(QLineEdit.Password)

        self.okButton = QPushButton(self)
        self.okButton.setGeometry(QRect(920, 560, 80, 20))
        self.okButton.setText('Iniciar...')
        self.connect(self.okButton, SIGNAL("clicked()"),
                     self.__eventInitDecryption)

    def __eventDirectoryChanged(self):
        index = self.treeView.currentIndex()
        self.__changeDirectory(self.fileSystemModel.filePath(index))

    def __changeDirectory(self, path):
        for c in self.filesview:
            c.setParent(None)
            c.deleteLater()
        self.filesview = []
        self.checkBox_2.setChecked(False)

        self.progressBars = {}
        for f in self.__getFiles(path):
            try:
                group = QGroupBox(f, self)
                group.setGeometry(QRect(20, 20, 100, 150))
                group.setCheckable(True)
                group.setChecked(False)
                group.setFixedSize(100, 150)
                group.setFlat(True)
                group.setToolTip(f)

                label = QLabel(group)
                label.setScaledContents(True)
                label.setGeometry(QRect(5, 25, 90, 90))
                label.setToolTip(f)

                progressBar = QProgressBar(group)
                progressBar.setGeometry(QRect(0, 70, 111, 10))
                progressBar.setProperty("value", 0)
                progressBar.setTextVisible(False)
                progressBar.setToolTip('0%')
                progressBar.setVisible(False)
                self.progressBars[f] = progressBar

                self.filesview.append(group)
                from os.path import isfile
                if isfile(path + '/' + f):
                    ext = f.split('.')[-1]
                    if isfile('icons/' + ext.lower() + '.png'):
                        label.setPixmap(
                            QPixmap('icons/' + ext.lower() + '.png'))
                    else:
                        label.setPixmap(QPixmap('icons/default.png'))
                else:
                    label.setPixmap(QPixmap('icons/folder.png'))
                self.connect(group, SIGNAL("clicked()"), self.__deselectFile)
            except ValueError:
                pass

        i = 0
        for x in list(range(len(self.filesview))):
            if (x % 4) == 0:
                i = i + 1
            self.rowsview[i].addWidget(self.filesview[x])

    def __selectAllFiles(self):
        for o in self.filesview:
            o.setChecked(self.checkBox_2.isChecked())

    def __deselectFile(self):
        #print 'deselect'
        self.checkBox_2.setChecked(False)

    def __arrozconpollo(self):
        self.__obtainSelectedFIles()

    def __obtainSelectedFIles(self):
        files = []
        for o in self.filesview:
            if o.isChecked():
                files.append(str(o.title()))
                self.progressBars[str(o.title())].setVisible(True)
        return files

    def __getFiles(self, path):
        from os import listdir
        from os.path import isfile

        f = []

        for base in listdir(path):
            try:
                if isfile(path + '/' + base) and base.split('.')[-1] == 'cry':
                    f.append(base)
            except ValueError:
                pass
        f.sort()
        return f

    def __eventInitDecryption(self):
        if len(self.__obtainSelectedFIles()) == 0:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText(
                "Debes especificar los archivos que quieres desencriptar")
            msg.setWindowTitle("Cryosystems")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()
            return

        if str(self.lineEdit.text()).strip() == '':
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText("Debes especificar una clave")
            msg.setWindowTitle("Cryosystems")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()
            return

        self.okButton.setEnabled(False)
        self.lineEdit.setEnabled(False)

        index = self.treeView.currentIndex()

        path = self.fileSystemModel.filePath(index)
        selectedFiles = self.__obtainSelectedFIles()

        from hashlib import md5
        Hash = md5()
        Hash.update(str(self.lineEdit.text()))
        key = Hash.hexdigest()

        errors = 0

        from os.path import getsize
        blockSize = 4096
        for f in selectedFiles:

            f_in = open(path + '/' + f, 'rb')
            print path + '/' + f

            header = ''
            if (f_in.read(20) == ('CRYOGENESIS' + unhexlify('00') + 'ARCHIVE' +
                                  unhexlify('01'))):
                while (True):
                    c = f_in.read(1)
                    if c == unhexlify('02'):
                        break
                    else:
                        header = header + c
            else:
                print 'esto no es un archivo cifradodo de Cryogenesis Systems'

            #print key
            aes = AES(key)
            #print aes.decrypt(header)
            header_sections = aes.decrypt(header).split('|')

            if header_sections[0] != 'header':
                msg = QMessageBox()
                msg.setIcon(QMessageBox.Critical)
                msg.setText("La clave no es correcta para el archivo:" + f)
                msg.setWindowTitle("Cryosystems")
                msg.setStandardButtons(QMessageBox.Ok)
                msg.exec_()
                errors = errors + 1
                continue

            f_out = open(path + '/' + header_sections[1], 'wb')

            techniques = header_sections[2].split(':')[:-1]

            techniquesObjects = []

            for t in techniques:
                techniquesObjects.append(self.techniquesClass[t](key))
            techniquesObjects.reverse()

            in_size = getsize(path + '/' + f)
            in_progress = 0.0

            block = f_in.read(blockSize)
            while (block):
                block_p = block
                for t in techniquesObjects:
                    block_p = t.decrypt(block_p)
                f_out.write(block_p)
                in_progress = in_progress + blockSize
                progress = (in_progress / in_size) * 100
                self.progressBars[str(f)].setProperty("value", int(progress))
                self.progressBars[str(f)].setToolTip(str(progress) + '%')
                block = f_in.read(blockSize)

            f_in.close()
            f_out.close()

            if (checksum(path + '/' + header_sections[1]) !=
                    header_sections[3]):
                msg = QMessageBox()
                msg.setIcon(QMessageBox.Critical)
                msg.setText("El archivo" + f + 'se ha corrompido')
                msg.setWindowTitle("Cryosystems")
                msg.setStandardButtons(QMessageBox.Ok)
                msg.exec_()
                errors = errors + 1
                from os import remove
                remove(header_sections[1])

        msg = QMessageBox()
        msg.setWindowTitle("Cryosystems")
        msg.setStandardButtons(QMessageBox.Ok)

        if (errors == 0):
            msg.setIcon(QMessageBox.Information)
            msg.setText("La desencriptacion ha concluido exitosamente")
        else:
            msg.setIcon(QMessageBox.Warning)
            msg.setText("La desencriptacion ha concluido con " + str(errors) +
                        ' error(es)')

        msg.exec_()
        self.hide()
예제 #13
0
class SourceFileTreeWidget(QWidget):
    """ Config window"""
    def __init__(self, parent):
        super(SourceFileTreeWidget, self).__init__(parent)
        self.ui = Ui_SourceFileTreeWidget()
        self.ui.setupUi(self)
        self.file_model = QFileSystemModel()
        #self.file_model.setFilter(QDir.AllEntries | QDir.NoDot)
        self.set_filter()
        self.ui.tree.setModel(self.file_model)
        self.ui.tree.resizeColumnToContents(0)
        self.ui.custom_root.setText(QDir.currentPath())
        self.set_root()

        header = self.ui.tree.header()
        header.setResizeMode(QHeaderView.ResizeToContents)
        #header.setStretchLastSection(True)
        #header.setSortIndicator(0, Qt.AscendingOrder)
        #header.setSortIndicatorShown(True)
        #header.setClickable(True)
        self.connect(self.ui.tree, QtCore.SIGNAL('doubleClicked(QModelIndex)'), self.open_file)
        self.connect(self.ui.ok_filter, QtCore.SIGNAL('clicked()'), self.set_filter)
        self.connect(self.ui.custom_filter, QtCore.SIGNAL('returnPressed()'), self.set_filter)
        self.connect(self.ui.ok_root, QtCore.SIGNAL('clicked()'), self.set_root)
        self.connect(self.ui.custom_root, QtCore.SIGNAL('returnPressed()'), self.set_root)
        self.open_file_signal = None

    def set_open_file_signal(self, signal):
        """ callback to signal file opening """
        self.open_file_signal = signal

    def set_root(self, root=None, use_common_prefix=True):
        """ set the root path of the widget """
        curr = str(self.ui.custom_root.text())
        if not root:
            use_common_prefix = False # input text box will override it.
            root = self.ui.custom_root.text()
        else:
            self.ui.custom_root.setText(root)
        idx = self.file_model.index(root)
        self.ui.tree.setExpanded(idx, True)
        if use_common_prefix and curr == os.path.commonprefix([root, curr]):
            return

        idx = self.file_model.setRootPath(root)
        if not idx.isValid():
            logging.warn('Invalid path')
            return
        self.ui.tree.setRootIndex(idx)
        self.ui.tree.setExpanded(idx, True)

    def set_filter(self):
        """ set filter by extension """
        filters = str(self.ui.custom_filter.text()).split(';')
        self.file_model.setNameFilters(filters)
        self.file_model.setNameFilterDisables(False)

    def open_file(self, idx):
        """ emit file opening signal """
        if self.file_model.isDir(idx):
            return
        fullpath = self.file_model.filePath(idx)
        if self.open_file_signal:
            self.open_file_signal.emit(str(fullpath), 0)

    def set_file_selected(self, tab_idx):
        """ slot to associate the file in active tab """
        filename = self.sender().tabToolTip(tab_idx)
        idx = self.file_model.index(filename)
        if idx.isValid():
            self.ui.tree.selectionModel().select(idx, QItemSelectionModel.ClearAndSelect)
예제 #14
0
class mainInitial(QtGui.QMainWindow):
  def  __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow() #treeview  UI
        self.ui.setupUi(self)
        self.showMaximized()
        self.home=os.getcwd()
        self.fileSystemModel = QFileSystemModel()


        #self.home=self.home + "/connections"
        #print (self.home)
        self.fillGrid2(self.home)
        #self.ui.treeWidget.isSortingEnabled()
        #self.ui.treeWidget.setSortingEnabled(True)
        self.ui.treeView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.connect(self.ui.treeView, QtCore.SIGNAL("customContextMenuRequested(const QPoint &)"), self.onclick)
        #self.connect(self.ui.treeView.selectionModel(),
        #    SIGNAL("customContextMenuRequested(pressed)"), self.onclick)


#  def eventFilter(self, obj, event):
#        if event.type() in (QtCore.QEvent.MouseButtonPress, QtCore.QEvent.MouseButtonDblClick):
#            if event.button() == QtCore.Qt.LeftButton:
#                print "left"
#                return True
#            elif event.button() == QtCore.Qt.RightButton:
#                print "Right"
#                return True
#        return super(mainInitial, self).eventFilter(obj, event)
#
#       #self.button2.clicked.connect(self.on_button_clicked)
#
#       #self.button1.installEventFilter(self)

  @QtCore.pyqtSlot(QtCore.QModelIndex)
  def onclick(self,selected):
      index=self.ui.treeView.indexAt(selected)
      #getSelected= self.ui.treeView.selectedItems()
      print (index)
      fileinfo = QtCore.QFileInfo(self.fileSystemModel.fileInfo(index) )
      print (fileinfo)
      path = self.fileSystemModel.filePath(index)
      #pathABS =self.fileSystemModel.rootPath(index)
      print path
      #print pathABS
      if self.fileSystemModel.isDir(index):
          print ("es directorio")
      else:
          print ("es archivo")

      menu=QtGui.QMenu(self)
      action_1=menu.addAction("crear coneccion")
      action_1.triggered.connect(self.action1)
      action_2=menu.addAction("borrar coneccion")
      action_3=menu.addAction("Modificar coneccion")
      action_4=menu.addAction("Crear Carpeta")
      menu.exec_(QtGui.QCursor.pos())
      #menu1=self.menu.addAction(u'algo')

      #menu1.triggered.connect(self.M1clear)
      #print ("determinar si esta vacio, es archivo o carpeta derecho")

  def action1(self, index):
      print "accion lanzada action_1"
      #self.fileSystemModel.mkdir()
      #print (self.ui.treeView.indexAt(index))

  def fillGrid2(self,home):
        print (QDir.currentPath())
        self.fileSystemModel.setRootPath(QDir.currentPath())
        self.ui.treeView.setModel(self.fileSystemModel)
        self.ui.treeView.setRootIndex(self.fileSystemModel.index(QDir.currentPath()))
        self.ui.treeView.hideColumn(1)
        self.ui.treeView.hideColumn(2)
        self.ui.treeView.hideColumn(3)