class ProjectTreeColumn(QDialog):

    def __init__(self, parent=None):
        super(ProjectTreeColumn, self).__init__(parent,
                                                Qt.WindowStaysOnTopHint)
        vbox = QVBoxLayout(self)
        vbox.setSizeConstraint(QVBoxLayout.SetDefaultConstraint)
        vbox.setContentsMargins(0, 0, 0, 0)
        self._buttons = []

        self._combo_project = QComboBox()
        self._combo_project.setMinimumHeight(30)
        self._combo_project.setContextMenuPolicy(Qt.CustomContextMenu)
        vbox.addWidget(self._combo_project)

        self._projects_area = QStackedLayout()
        logger.debug("This is the projects area")
        logger.debug(self._projects_area)
        vbox.addLayout(self._projects_area)

        self.projects = []

        self.connect(self._combo_project, SIGNAL("currentIndexChanged(int)"),
                     self._change_current_project)
        self.connect(self._combo_project, SIGNAL(
            "customContextMenuRequested(const QPoint &)"),
            self.context_menu_for_root)
        connections = (
            {'target': 'main_container',
             'signal_name': 'addToProject(QString)',
             'slot': self._add_file_to_project},
            {'target': 'main_container',
             'signal_name': 'showFileInExplorer(QString)',
             'slot': self._show_file_in_explorer},
        )
        IDE.register_service('projects_explorer', self)
        IDE.register_signals('projects_explorer', connections)
        ExplorerContainer.register_tab(translations.TR_TAB_PROJECTS, self)

        #FIXME: Should have a ninja settings object that stores tree state
        #FIXME: Or bettter, application data object
        #TODO: check this:
        #self.connect(ide, SIGNAL("goingDown()"),
            #self.tree_projects.shutdown)

        #def close_project_signal():
            #self.emit(SIGNAL("updateLocator()"))

    def install_tab(self):
        ide = IDE.get_service('ide')
        ui_tools.install_shortcuts(self, actions.PROJECTS_TREE_ACTIONS, ide)

        self.connect(ide, SIGNAL("goingDown()"), self.close)

    def load_session_projects(self, projects):
        for project in projects:
            if os.path.exists(project):
                self._open_project_folder(project)

    def open_project_folder(self, folderName=None):
        if settings.WORKSPACE:
            directory = settings.WORKSPACE
        else:
            directory = os.path.expanduser("~")

        if folderName is None:
            folderName = QFileDialog.getExistingDirectory(
                self, translations.TR_OPEN_PROJECT_DIRECTORY, directory)
            logger.debug("Choosing Foldername")
        if folderName:
            logger.debug("Opening %s" % folderName)
            self._open_project_folder(folderName)

    def _open_project_folder(self, folderName):
        ninjaide = IDE.get_service("ide")
        project = NProject(folderName)
        qfsm = ninjaide.filesystem.open_project(project)
        if qfsm:
            self.add_project(project)
            self.emit(SIGNAL("updateLocator()"))
            self.save_recent_projects(folderName)
            main_container = IDE.get_service('main_container')
            if main_container:
                main_container.show_editor_area()

    def _add_file_to_project(self, path):
        """Add the file for 'path' in the project the user choose here."""
        if self._active_project:
            pathProject = [self._active_project.project]
            addToProject = add_to_project.AddToProject(pathProject, self)
            addToProject.exec_()
            if not addToProject.pathSelected:
                return
            main_container = IDE.get_service('main_container')
            if not main_container:
                return
            editorWidget = main_container.get_current_editor()
            if not editorWidget.file_path:
                name = QInputDialog.getText(None,
                                            translations.TR_ADD_FILE_TO_PROJECT,
                                            translations.TR_FILENAME + ": ")[0]
                if not name:
                    QMessageBox.information(
                        self,
                        translations.TR_INVALID_FILENAME,
                        translations.TR_INVALID_FILENAME_ENTER_A_FILENAME)
                    return
            else:
                name = file_manager.get_basename(editorWidget.file_path)
            new_path = file_manager.create_path(addToProject.pathSelected, name)
            ide_srv = IDE.get_service("ide")
            old_file = ide_srv.get_or_create_nfile(path)
            new_file = old_file.save(editorWidget.get_text(), new_path)
            #FIXME: Make this file replace the original in the open tab
        else:
            pass
            # Message about no project

    def _show_file_in_explorer(self, path):
        '''Iterate through the list of available projects and show
        the current file in the explorer view for the first
        project that contains it (i.e. if the same file is
        included in multiple open projects, the path will be
        expanded for the first project only).
        Note: This slot is connected to the main container's
        "showFileInExplorer(QString)" signal.'''
        for project in self.projects:
            index = project.model().index(path)
            if index.isValid():
                # Show the explorer if it is currently hidden
                central = IDE.get_service('central_container')
                if central and not central.is_lateral_panel_visible():
                    central.change_lateral_visibility()
                # This highlights the index in the tree for us
                project.setCurrentIndex(index)
                # Loop through the parents to expand the tree
                # all the way up to the selected index.
                while index.isValid():
                    project.expand(index)
                    index = index.parent()
                break

    def add_project(self, project):
        if project not in self.projects:
            self._combo_project.addItem(project.name)
            ptree = TreeProjectsWidget(project)
            self._projects_area.addWidget(ptree)
            self.connect(ptree, SIGNAL("closeProject(PyQt_PyObject)"),
                         self._close_project)
            pmodel = project.model
            ptree.setModel(pmodel)
            pindex = pmodel.index(pmodel.rootPath())
            ptree.setRootIndex(pindex)
            self.projects.append(ptree)
            current_index = self._projects_area.count()
            self._projects_area.setCurrentIndex(current_index - 1)
            self._combo_project.setCurrentIndex(current_index - 1)

    def _close_project(self, widget):
        """Close the project related to the tree widget."""
        index = self._projects_area.currentIndex()
        self.projects.remove(widget)
        self._projects_area.takeAt(index)
        self._combo_project.removeItem(index)
        index = self._combo_project.currentIndex()
        self._projects_area.setCurrentIndex(index)
        ninjaide = IDE.get_service('ide')
        ninjaide.filesystem.close_project(widget.project.path)
        widget.deleteLater()

    def _change_current_project(self, index):
        self._projects_area.setCurrentIndex(index)

    def close_opened_projects(self):
        for project in reversed(self.projects):
            self._close_project(project)

    def save_project(self):
        """Save all the opened files that belongs to the actual project."""
        if self._active_project:
            path = self._projects_area.currentWidget().project.path
            main_container = IDE.get_service('main_container')
            if path and main_container:
                main_container.save_project(path)

    def create_new_project(self):
        wizard = new_project_manager.NewProjectManager(self)
        wizard.show()

    @property
    def current_project(self):
        if self._projects_area.count() > 0:
            return self._projects_area.currentWidget().project

    @property
    def current_tree(self):
        return self._projects_area.currentWidget()

    def save_recent_projects(self, folder):
        settings = IDE.data_settings()
        recent_project_list = settings.value('recentProjects', {})
        #if already exist on the list update the date time
        projectProperties = json_manager.read_ninja_project(folder)
        name = projectProperties.get('name', '')
        description = projectProperties.get('description', '')

        if name == '':
            name = file_manager.get_basename(folder)

        if description == '':
            description = translations.TR_NO_DESCRIPTION

        if folder in recent_project_list:
            properties = recent_project_list[folder]
            properties["lastopen"] = QDateTime.currentDateTime()
            properties["name"] = name
            properties["description"] = description
            recent_project_list[folder] = properties
        else:
            recent_project_list[folder] = {
                "name": name,
                "description": description,
                "isFavorite": False, "lastopen": QDateTime.currentDateTime()}
            #if the length of the project list it's high that 10 then delete
            #the most old
            #TODO: add the length of available projects to setting
            if len(recent_project_list) > 10:
                del recent_project_list[self.find_most_old_open(
                    recent_project_list)]
        settings.setValue('recentProjects', recent_project_list)

    def find_most_old_open(self, recent_project_list):
        listFounder = []
        for recent_project_path, content in list(recent_project_list.items()):
            listFounder.append((recent_project_path, int(
                content["lastopen"].toString("yyyyMMddHHmmzzz"))))
        listFounder = sorted(listFounder, key=lambda date: listFounder[1],
                             reverse=True)   # sort by date last used
        return listFounder[0][0]

    def reject(self):
        if self.parent() is None:
            self.emit(SIGNAL("dockWidget(PyQt_PyObject)"), self)

    def closeEvent(self, event):
        self.emit(SIGNAL("dockWidget(PyQt_PyObject)"), self)
        event.ignore()

    def context_menu_for_root(self):
        menu = QMenu(self)
        path = self.current_tree.project.path
        action_add_file = menu.addAction(QIcon(":img/new"),
                                         translations.TR_ADD_NEW_FILE)
        action_add_folder = menu.addAction(QIcon(
            ":img/openProj"), translations.TR_ADD_NEW_FOLDER)
        action_create_init = menu.addAction(translations.TR_CREATE_INIT)
        self.connect(action_add_file, SIGNAL("triggered()"),
                     lambda: self.current_tree._add_new_file(path))
        self.connect(action_add_folder, SIGNAL("triggered()"),
                     lambda: self.current_tree._add_new_folder(path))
        self.connect(action_create_init, SIGNAL("triggered()"),
                     lambda: self.current_tree._create_init(path))
        menu.addSeparator()
        actionRunProject = menu.addAction(QIcon(
            ":img/play"), translations.TR_RUN_PROJECT)
        self.connect(actionRunProject, SIGNAL("triggered()"),
                     self.current_tree._execute_project)
        if self.current_tree._added_to_console:
            actionRemoveFromConsole = menu.addAction(
                translations.TR_REMOVE_PROJECT_FROM_PYTHON_CONSOLE)
            self.connect(actionRemoveFromConsole, SIGNAL("triggered()"),
                         self.current_tree._remove_project_from_console)
        else:
            actionAdd2Console = menu.addAction(
                translations.TR_ADD_PROJECT_TO_PYTHON_CONSOLE)
            self.connect(actionAdd2Console, SIGNAL("triggered()"),
                         self.current_tree._add_project_to_console)
        actionShowFileSizeInfo = menu.addAction(translations.TR_SHOW_FILESIZE)
        self.connect(actionShowFileSizeInfo, SIGNAL("triggered()"),
                     self.current_tree.show_filesize_info)
        actionProperties = menu.addAction(QIcon(":img/pref"),
                                          translations.TR_PROJECT_PROPERTIES)
        self.connect(actionProperties, SIGNAL("triggered()"),
                     self.current_tree.open_project_properties)

        menu.addSeparator()
        action_close = menu.addAction(
            self.style().standardIcon(QStyle.SP_DialogCloseButton),
            translations.TR_CLOSE_PROJECT)
        self.connect(action_close, SIGNAL("triggered()"),
                     self.current_tree._close_project)
        #menu for the project
        for m in self.current_tree.extra_menus_by_scope['project']:
            if isinstance(m, QMenu):
                menu.addSeparator()
                menu.addMenu(m)

        #show the menu!
        menu.exec_(QCursor.pos())
Beispiel #2
0
class ActionBar(QFrame):
    """
    SIGNALS:
    @changeCurrent(PyQt_PyObject)
    @runFile(QString)
    @reopenTab(QString)
    @recentTabsModified()
    """

    def __init__(self, main_combo=False):
        super(ActionBar, self).__init__()
        self.setObjectName("actionbar")
        hbox = QHBoxLayout(self)
        hbox.setContentsMargins(1, 1, 1, 1)
        hbox.setSpacing(1)

        self.lbl_checks = QLabel('')
        self.lbl_checks.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.lbl_checks.setFixedWidth(48)
        self.lbl_checks.setVisible(False)
        hbox.addWidget(self.lbl_checks)

        self.combo = QComboBox()
        self.combo.setIconSize(QSize(16, 16))
        #model = QStandardItemModel()
        #self.combo.setModel(model)
        #self.combo.view().setDragDropMode(QAbstractItemView.InternalMove)
        self.combo.setMaximumWidth(300)
        self.combo.setObjectName("combotab")
        self.connect(self.combo, SIGNAL("currentIndexChanged(int)"),
            self.current_changed)
        self.combo.setToolTip(translations.TR_COMBO_FILE_TOOLTIP)
        self.combo.setContextMenuPolicy(Qt.CustomContextMenu)
        self.connect(self.combo, SIGNAL(
            "customContextMenuRequested(const QPoint &)"),
            self._context_menu_requested)
        hbox.addWidget(self.combo)

        self.symbols_combo = QComboBox()
        self.symbols_combo.setIconSize(QSize(16, 16))
        self.symbols_combo.setObjectName("combo_symbols")
        self.connect(self.symbols_combo, SIGNAL("activated(int)"),
            self.current_symbol_changed)
        hbox.addWidget(self.symbols_combo)

        self.code_navigator = CodeNavigator()
        hbox.addWidget(self.code_navigator)

        self._pos_text = "Line: %d, Col: %d"
        self.lbl_position = QLabel(self._pos_text % (0, 0))
        self.lbl_position.setObjectName("position")
        self.lbl_position.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        hbox.addWidget(self.lbl_position)

        self.btn_close = QPushButton(
            self.style().standardIcon(QStyle.SP_DialogCloseButton), '')
        self.btn_close.setIconSize(QSize(16, 16))
        if main_combo:
            self.btn_close.setObjectName('navigation_button')
            self.btn_close.setToolTip(translations.TR_CLOSE_FILE)
            self.connect(self.btn_close, SIGNAL("clicked()"),
                self.about_to_close_file)
        else:
            self.btn_close.setObjectName('close_split')
            self.btn_close.setToolTip(translations.TR_CLOSE_SPLIT)
            self.connect(self.btn_close, SIGNAL("clicked()"),
                self.close_split)
        self.btn_close.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        hbox.addWidget(self.btn_close)

    def resizeEvent(self, event):
        super(ActionBar, self).resizeEvent(event)
        if event.size().width() < 350:
            self.symbols_combo.hide()
            self.code_navigator.hide()
            self.lbl_position.hide()
        else:
            self.symbols_combo.show()
            self.code_navigator.show()
            self.lbl_position.show()

    def add_item(self, text, neditable):
        """Add a new item to the combo and add the neditable data."""
        self.combo.addItem(text, neditable)
        self.combo.setCurrentIndex(self.combo.count() - 1)

    def get_editables(self):
        editables = []
        for index in range(self.combo.count()):
            neditable = self.combo.itemData(index)
            editables.append(neditable)
        return editables

    def add_symbols(self, symbols):
        """Add the symbols to the symbols's combo."""
        self.symbols_combo.clear()
        for symbol in symbols:
            data = symbol[1]
            if data[1] == 'f':
                icon = QIcon(":img/function")
            else:
                icon = QIcon(":img/class")
            self.symbols_combo.addItem(icon, data[0])

    def set_current_symbol(self, index):
        self.symbols_combo.setCurrentIndex(index)

    def update_item_icon(self, neditable, icon):
        index = self.combo.findData(neditable)
        self.combo.setItemIcon(index, icon)

    def update_item_text(self, neditable, text):
        index = self.combo.findData(neditable)
        self.combo.setItemText(index, text)

    def current_changed(self, index):
        """Change the current item in the combo."""
        neditable = self.combo.itemData(index)
        self.emit(SIGNAL("changeCurrent(PyQt_PyObject, int)"), neditable, index)

    def current_symbol_changed(self, index):
        """Change the current symbol in the combo."""
        self.emit(SIGNAL("goToSymbol(int)"), index)

    def update_line_col(self, line, col):
        """Update the line and column position."""
        self.lbl_position.setText(self._pos_text % (line, col))

    def _context_menu_requested(self, point):
        """Display context menu for the combo file."""
        if self.combo.count() == 0:
            # If there is not an Editor opened, don't show the menu
            return
        menu = QMenu()
        actionAdd = menu.addAction(translations.TR_ADD_TO_PROJECT)
        actionRun = menu.addAction(translations.TR_RUN_FILE)
        menuSyntax = menu.addMenu(translations.TR_CHANGE_SYNTAX)
        self._create_menu_syntax(menuSyntax)
        menu.addSeparator()
        actionClose = menu.addAction(translations.TR_CLOSE_FILE)
        actionCloseAll = menu.addAction(translations.TR_CLOSE_ALL_FILES)
        actionCloseAllNotThis = menu.addAction(
            translations.TR_CLOSE_OTHER_FILES)
        menu.addSeparator()
        actionSplitH = menu.addAction(translations.TR_SPLIT_VERTICALLY)
        actionSplitV = menu.addAction(translations.TR_SPLIT_HORIZONTALLY)
        menu.addSeparator()
        actionCopyPath = menu.addAction(
            translations.TR_COPY_FILE_PATH_TO_CLIPBOARD)
        actionReopen = menu.addAction(translations.TR_REOPEN_FILE)
        actionUndock = menu.addAction(translations.TR_UNDOCK_EDITOR)
        if len(settings.LAST_OPENED_FILES) == 0:
            actionReopen.setEnabled(False)
        #Connect actions
        self.connect(actionSplitH, SIGNAL("triggered()"),
            lambda: self._split(False))
        self.connect(actionSplitV, SIGNAL("triggered()"),
            lambda: self._split(True))
        self.connect(actionRun, SIGNAL("triggered()"),
            self._run_this_file)
        self.connect(actionAdd, SIGNAL("triggered()"),
            self._add_to_project)
        self.connect(actionClose, SIGNAL("triggered()"),
            self.about_to_close_file)
        self.connect(actionCloseAllNotThis, SIGNAL("triggered()"),
            self._close_all_files_except_this)
        self.connect(actionCloseAll, SIGNAL("triggered()"),
            self._close_all_files)
        self.connect(actionCopyPath, SIGNAL("triggered()"),
            self._copy_file_location)
        self.connect(actionReopen, SIGNAL("triggered()"),
            self._reopen_last_tab)
        self.connect(actionUndock, SIGNAL("triggered()"),
            self._undock_editor)

        menu.exec_(QCursor.pos())

    def _create_menu_syntax(self, menuSyntax):
        """Create Menu with the list of syntax supported."""
        syntax = list(settings.SYNTAX.keys())
        syntax.sort()
        for syn in syntax:
            menuSyntax.addAction(syn)
            self.connect(menuSyntax, SIGNAL("triggered(QAction*)"),
                self._reapply_syntax)

    def _reapply_syntax(self, syntaxAction):
        #TODO
        if [self.currentIndex(), syntaxAction] != self._resyntax:
            self._resyntax = [self.currentIndex(), syntaxAction]
            self.emit(SIGNAL("syntaxChanged(QWidget, QString)"),
                self.currentWidget(), syntaxAction.text())

    def set_current_file(self, neditable):
        index = self.combo.findData(neditable)
        self.combo.setCurrentIndex(index)

    def set_current_by_index(self, index):
        self.combo.setCurrentIndex(index)

    def about_to_close_file(self, index=None):
        """Close the NFile object."""
        if index is None:
            index = self.combo.currentIndex()
        neditable = self.combo.itemData(index)
        if neditable:
            neditable.nfile.close()

    def close_split(self):
        self.emit(SIGNAL("closeSplit()"))

    def close_file(self, neditable):
        """Receive the confirmation to close the file."""
        index = self.combo.findData(neditable)
        self.combo.removeItem(index)
        return index

    def _run_this_file(self):
        """Execute the current file."""
        neditable = self.combo.itemData(self.combo.currentIndex())
        self.emit(SIGNAL("runFile(QString)"), neditable.file_path)

    def _add_to_project(self):
        """Emit a signal to let someone handle the inclusion of the file
        inside a project."""
        neditable = self.combo.itemData(self.combo.currentIndex())
        self.emit(SIGNAL("addToProject(QString)"), neditable.file_path)

    def _reopen_last_tab(self):
        self.emit(SIGNAL("reopenTab(QString)"),
            settings.LAST_OPENED_FILES.pop())
        self.emit(SIGNAL("recentTabsModified()"))

    def _undock_editor(self):
        self.emit(SIGNAL("undockEditor()"))

    def _split(self, orientation):
        self.emit(SIGNAL("splitEditor(bool)"), orientation)

    def _copy_file_location(self):
        """Copy the path of the current opened file to the clipboard."""
        neditable = self.combo.itemData(self.combo.currentIndex())
        QApplication.clipboard().setText(neditable.file_path,
            QClipboard.Clipboard)

    def _close_all_files(self):
        """Close all the files opened."""
        for i in range(self.combo.count()):
            self.about_to_close_file(0)

    def _close_all_files_except_this(self):
        """Close all the files except the current one."""
        neditable = self.combo.itemData(self.combo.currentIndex())
        for i in reversed(list(range(self.combo.count()))):
            ne = self.combo.itemData(i)
            if ne is not neditable:
                self.about_to_close_file(i)
Beispiel #3
0
class AnalogConfigLayout(QFormLayout):
    rangeChanged = pyqtSignal()

    def __init__(self, showSampleRateSb=False, settings=None, parent=None):
        super(AnalogConfigLayout, self).__init__(parent)
        self.deviceCombo = QComboBox()
        self.deviceCombo.setObjectName('deviceCombo')
        self.addRow('&Device', self.deviceCombo)
        self.channelCombo = QComboBox()
        self.channelCombo.setObjectName('channelCombo')
        self.addRow('&Channel', self.channelCombo)
        self.rangeCombo = QComboBox()
        self.rangeCombo.setObjectName('rangeCombo')
        self.addRow('&Range', self.rangeCombo)
        if showSampleRateSb:
            self.sampleRateSb = QDoubleSpinBox()
            self.sampleRateSb.setSuffix(' kHz')
            self.sampleRateSb.setMinimum(0.001)
            self.sampleRateSb.setDecimals(3)
            self.sampleRateSb.setValue(1)

            self.sampleRateSb.setObjectName('sampleRateSb')
            self.addRow('&Sample rate', self.sampleRateSb)
        else:
            self.sampleRateSb = None

        self._ranges = []
        self.deviceCombo.currentIndexChanged.connect(self.deviceChanged)
        self.populateDevices()
        self.rangeCombo.currentIndexChanged.connect(self.rangeChanged)
        self.deviceCombo.setContextMenuPolicy(Qt.CustomContextMenu)
        self.deviceCombo.customContextMenuRequested.connect(self.contextMenu)

    def contextMenu(self, point):
        globalPos = self.deviceCombo.mapToGlobal(point)
        menu = QMenu()
        refreshAction = QAction("&Refresh", menu)
        menu.addAction(refreshAction)
        selected = menu.exec_(globalPos)

        if selected == refreshAction:
            self.populateDevices()

    def populateDevices(self):
        self.deviceCombo.clear()
        system = daq.System()
        devices = system.findDevices()
        for dev in devices:
            self.deviceCombo.addItem(dev)

    def deviceChanged(self):
        self.channelCombo.clear()
        for channel in self.channels():
            self.channelCombo.addItem(channel)
        self.rangeCombo.clear()
        self._ranges = self.ranges()
        for r in self._ranges:
            self.rangeCombo.addItem('%+.2f -> %+.2f V' % (r.min, r.max))
        if self.sampleRateSb is not None:
            fmax = self.maxSampleRate()
            self.sampleRateSb.setMaximum(1E-3 * fmax)

    def maxSampleRate(self):
        raise NotImplementedError

    def device(self):
        t = self.deviceCombo.currentText()
        if len(t):
            return str(t)
        else:
            return None

    def channel(self):
        return str(self.channelCombo.currentText())

    def voltageRange(self):
        i = self.rangeCombo.currentIndex()
        return None if i < 0 else self._ranges[i]

    def restoreSettings(self, s=None):
        if s is None:
            s = QSettings()
        try:
            device = s.value('device', '', type=str)
            i = self.deviceCombo.findText(device)
            self.deviceCombo.setCurrentIndex(i)
        except:
            pass

        channel = s.value('channel', '', type=str)
        i = self.channelCombo.findText(channel)
        self.channelCombo.setCurrentIndex(i)
        voltageRange = s.value('range', '', type=str)
        i = self.rangeCombo.findText(voltageRange)
        self.rangeCombo.setCurrentIndex(i)

    def saveSettings(self, s=None):
        if s is None:
            s = QSettings()
        s.setValue('device', self.device())
        s.setValue('channel', self.channel())
        s.setValue('range', self.rangeCombo.currentText())
Beispiel #4
0
class ActionBar(QFrame):
    """
    SIGNALS:
    @changeCurrent(PyQt_PyObject)
    @runFile(QString)
    @reopenTab(QString)
    @recentTabsModified()
    """
    def __init__(self, main_combo=False):
        super(ActionBar, self).__init__()
        self.setObjectName("actionbar")
        hbox = QHBoxLayout(self)
        hbox.setContentsMargins(1, 1, 1, 1)
        hbox.setSpacing(1)

        self.lbl_checks = QLabel('')
        self.lbl_checks.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.lbl_checks.setFixedWidth(48)
        self.lbl_checks.setVisible(False)
        hbox.addWidget(self.lbl_checks)

        self.combo = QComboBox()
        #model = QStandardItemModel()
        #self.combo.setModel(model)
        #self.combo.view().setDragDropMode(QAbstractItemView.InternalMove)
        self.combo.setMaximumWidth(300)
        self.combo.setObjectName("combotab")
        self.connect(self.combo, SIGNAL("currentIndexChanged(int)"),
                     self.current_changed)
        self.combo.setToolTip(translations.TR_COMBO_FILE_TOOLTIP)
        self.combo.setContextMenuPolicy(Qt.CustomContextMenu)
        self.connect(self.combo,
                     SIGNAL("customContextMenuRequested(const QPoint &)"),
                     self._context_menu_requested)
        hbox.addWidget(self.combo)

        self.symbols_combo = QComboBox()
        self.symbols_combo.setObjectName("combo_symbols")
        self.connect(self.symbols_combo, SIGNAL("activated(int)"),
                     self.current_symbol_changed)
        hbox.addWidget(self.symbols_combo)

        self.code_navigator = CodeNavigator()
        hbox.addWidget(self.code_navigator)

        self._pos_text = "Line: %d, Col: %d"
        self.lbl_position = QLabel(self._pos_text % (0, 0))
        self.lbl_position.setObjectName("position")
        self.lbl_position.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        hbox.addWidget(self.lbl_position)

        self.btn_close = QPushButton(
            self.style().standardIcon(QStyle.SP_DialogCloseButton), '')
        if main_combo:
            self.btn_close.setObjectName('navigation_button')
            self.btn_close.setToolTip(translations.TR_CLOSE_FILE)
            self.connect(self.btn_close, SIGNAL("clicked()"),
                         self.about_to_close_file)
        else:
            self.btn_close.setObjectName('close_split')
            self.btn_close.setToolTip(translations.TR_CLOSE_SPLIT)
            self.connect(self.btn_close, SIGNAL("clicked()"), self.close_split)
        self.btn_close.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        hbox.addWidget(self.btn_close)

    def resizeEvent(self, event):
        super(ActionBar, self).resizeEvent(event)
        if event.size().width() < 350:
            self.symbols_combo.hide()
            self.code_navigator.hide()
            self.lbl_position.hide()
        else:
            self.symbols_combo.show()
            self.code_navigator.show()
            self.lbl_position.show()

    def add_item(self, text, neditable):
        """Add a new item to the combo and add the neditable data."""
        self.combo.addItem(text, neditable)
        self.combo.setCurrentIndex(self.combo.count() - 1)

    def get_editables(self):
        editables = []
        for index in range(self.combo.count()):
            neditable = self.combo.itemData(index)
            editables.append(neditable)
        return editables

    def add_symbols(self, symbols):
        """Add the symbols to the symbols's combo."""
        self.symbols_combo.clear()
        for symbol in symbols:
            data = symbol[1]
            if data[1] == 'f':
                icon = QIcon(":img/function")
            else:
                icon = QIcon(":img/class")
            self.symbols_combo.addItem(icon, data[0])

    def set_current_symbol(self, index):
        self.symbols_combo.setCurrentIndex(index)

    def update_item_icon(self, neditable, icon):
        index = self.combo.findData(neditable)
        self.combo.setItemIcon(index, icon)

    def update_item_text(self, neditable, text):
        index = self.combo.findData(neditable)
        self.combo.setItemText(index, text)

    def current_changed(self, index):
        """Change the current item in the combo."""
        neditable = self.combo.itemData(index)
        self.emit(SIGNAL("changeCurrent(PyQt_PyObject, int)"), neditable,
                  index)

    def current_symbol_changed(self, index):
        """Change the current symbol in the combo."""
        self.emit(SIGNAL("goToSymbol(int)"), index)

    def update_line_col(self, line, col):
        """Update the line and column position."""
        self.lbl_position.setText(self._pos_text % (line, col))

    def _context_menu_requested(self, point):
        """Display context menu for the combo file."""
        if self.combo.count() == 0:
            # If there is not an Editor opened, don't show the menu
            return
        menu = QMenu()
        actionAdd = menu.addAction(translations.TR_ADD_TO_PROJECT)
        actionRun = menu.addAction(translations.TR_RUN_FILE)
        menuSyntax = menu.addMenu(translations.TR_CHANGE_SYNTAX)
        self._create_menu_syntax(menuSyntax)
        menu.addSeparator()
        actionClose = menu.addAction(translations.TR_CLOSE_FILE)
        actionCloseAll = menu.addAction(translations.TR_CLOSE_ALL_FILES)
        actionCloseAllNotThis = menu.addAction(
            translations.TR_CLOSE_OTHER_FILES)
        menu.addSeparator()
        actionSplitH = menu.addAction(translations.TR_SPLIT_VERTICALLY)
        actionSplitV = menu.addAction(translations.TR_SPLIT_HORIZONTALLY)
        menu.addSeparator()
        actionCopyPath = menu.addAction(
            translations.TR_COPY_FILE_PATH_TO_CLIPBOARD)
        actionReopen = menu.addAction(translations.TR_REOPEN_FILE)
        actionUndock = menu.addAction(translations.TR_UNDOCK_EDITOR)
        if len(settings.LAST_OPENED_FILES) == 0:
            actionReopen.setEnabled(False)
        #Connect actions
        self.connect(actionSplitH, SIGNAL("triggered()"),
                     lambda: self._split(False))
        self.connect(actionSplitV, SIGNAL("triggered()"),
                     lambda: self._split(True))
        self.connect(actionRun, SIGNAL("triggered()"), self._run_this_file)
        self.connect(actionAdd, SIGNAL("triggered()"), self._add_to_project)
        self.connect(actionClose, SIGNAL("triggered()"),
                     self.about_to_close_file)
        self.connect(actionCloseAllNotThis, SIGNAL("triggered()"),
                     self._close_all_files_except_this)
        self.connect(actionCloseAll, SIGNAL("triggered()"),
                     self._close_all_files)
        self.connect(actionCopyPath, SIGNAL("triggered()"),
                     self._copy_file_location)
        self.connect(actionReopen, SIGNAL("triggered()"),
                     self._reopen_last_tab)
        self.connect(actionUndock, SIGNAL("triggered()"), self._undock_editor)

        menu.exec_(QCursor.pos())

    def _create_menu_syntax(self, menuSyntax):
        """Create Menu with the list of syntax supported."""
        syntax = list(settings.SYNTAX.keys())
        syntax.sort()
        for syn in syntax:
            menuSyntax.addAction(syn)
            self.connect(menuSyntax, SIGNAL("triggered(QAction*)"),
                         self._reapply_syntax)

    def _reapply_syntax(self, syntaxAction):
        #TODO
        if [self.currentIndex(), syntaxAction] != self._resyntax:
            self._resyntax = [self.currentIndex(), syntaxAction]
            self.emit(SIGNAL("syntaxChanged(QWidget, QString)"),
                      self.currentWidget(), syntaxAction.text())

    def set_current_file(self, neditable):
        index = self.combo.findData(neditable)
        self.combo.setCurrentIndex(index)

    def set_current_by_index(self, index):
        self.combo.setCurrentIndex(index)

    def about_to_close_file(self, index=None):
        """Close the NFile object."""
        if index is None:
            index = self.combo.currentIndex()
        neditable = self.combo.itemData(index)
        if neditable:
            neditable.nfile.close()

    def close_split(self):
        self.emit(SIGNAL("closeSplit()"))

    def close_file(self, neditable):
        """Receive the confirmation to close the file."""
        index = self.combo.findData(neditable)
        self.combo.removeItem(index)
        return index

    def _run_this_file(self):
        """Execute the current file."""
        neditable = self.combo.itemData(self.combo.currentIndex())
        self.emit(SIGNAL("runFile(QString)"), neditable.file_path)

    def _add_to_project(self):
        """Emit a signal to let someone handle the inclusion of the file
        inside a project."""
        neditable = self.combo.itemData(self.combo.currentIndex())
        self.emit(SIGNAL("addToProject(QString)"), neditable.file_path)

    def _reopen_last_tab(self):
        self.emit(SIGNAL("reopenTab(QString)"),
                  settings.LAST_OPENED_FILES.pop())
        self.emit(SIGNAL("recentTabsModified()"))

    def _undock_editor(self):
        self.emit(SIGNAL("undockEditor()"))

    def _split(self, orientation):
        self.emit(SIGNAL("splitEditor(bool)"), orientation)

    def _copy_file_location(self):
        """Copy the path of the current opened file to the clipboard."""
        neditable = self.combo.itemData(self.combo.currentIndex())
        QApplication.clipboard().setText(neditable.file_path,
                                         QClipboard.Clipboard)

    def _close_all_files(self):
        """Close all the files opened."""
        for i in range(self.combo.count()):
            self.about_to_close_file(0)

    def _close_all_files_except_this(self):
        """Close all the files except the current one."""
        neditable = self.combo.itemData(self.combo.currentIndex())
        for i in reversed(list(range(self.combo.count()))):
            ne = self.combo.itemData(i)
            if ne is not neditable:
                self.about_to_close_file(i)
Beispiel #5
0
class ComboContainer(QWidget):

    def __init__(self, parent=None):
        super(ComboContainer, self).__init__()
        self._editor_widget = parent
        box = QHBoxLayout(self)
        box.setContentsMargins(0, 0, 0, 0)
        box.setSpacing(0)
        self._lines_symbols = []

        # Basado en la GUI de Qt Creator
        # Combo archivos
        self.combo_file = QComboBox()
        self.combo_file.setIconSize(QSize(14, 14))
        self.combo_file.setContextMenuPolicy(Qt.CustomContextMenu)
        box.addWidget(self.combo_file)
        # Botón cerrar
        btn_close_editor = QToolButton()
        btn_close_editor.setFixedSize(25, 22)
        btn_close_editor.setObjectName("combo-button")
        btn_close_editor.setToolTip(self.tr("Cerrar archivo"))
        btn_close_editor.setIcon(QIcon(":image/close"))
        btn_close_editor.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        box.addWidget(btn_close_editor)
        # Combo símbolos
        self.combo_symbols = QComboBox()
        self.combo_symbols.setIconSize(QSize(14, 14))
        box.addWidget(self.combo_symbols)
        # Label número de línea y columna
        self.label_line_row = QToolButton()
        self.label_line_row.mousePressEvent = self._show_dialog_go_to_line
        self.label_line_row.setObjectName("combo-lines-button")
        self.line_row = "Lin: %s, Col: %s - %s"
        self.label_line_row.setText(self.line_row % (0, 0, 0))
        self.label_line_row.setToolTip(
            self.tr("Click para ir a una línea y/o columna específica"))
        box.addWidget(self.label_line_row)

        output = Edis.get_component("output")

        # Conexiones
        self.connect(btn_close_editor, SIGNAL("clicked()"),
                     self._close_current_file)
        self.connect(output.salida_, SIGNAL("updateSyntaxCheck(bool)"),
                     self._show_icon_checker)
        self.connect(self.combo_symbols, SIGNAL("activated(int)"),
                     self._go_to_symbol)
        self.connect(self.combo_file,
                     SIGNAL("customContextMenuRequested(const QPoint)"),
                     self._load_menu_combo_file)

    def update_cursor_position(self, line, row, lines):
        self.label_line_row.setText(self.line_row % (line, row, lines))

    def _show_dialog_go_to_line(self, event):
        if event.button() == Qt.LeftButton:
            editor_container = Edis.get_component("principal")
            editor_container.show_go_to_line()

    def _load_menu_combo_file(self, point):
        """ Muestra el menú """

        menu = QMenu()
        editor_container = Edis.get_component("principal")
        save_as_action = menu.addAction(QIcon(":image/save-as"),
                                        self.tr("Guardar como..."))
        reload_action = menu.addAction(QIcon(":image/reload"),
                                       self.tr("Recargar"))
        menu.addSeparator()
        compile_action = menu.addAction(QIcon(":image/build"),
                                        self.tr("Compilar"))
        execute_action = menu.addAction(QIcon(":image/run"),
                                        self.tr("Ejecutar"))
        menu.addSeparator()
        close_action = menu.addAction(QIcon(":image/close"),
                                      self.tr("Cerrar archivo"))

        # Conexiones
        self.connect(save_as_action, SIGNAL("triggered()"),
                     editor_container.save_file_as)
        self.connect(reload_action, SIGNAL("triggered()"),
                     editor_container.reload_file)
        self.connect(compile_action, SIGNAL("triggered()"),
                     editor_container.build_source_code)
        self.connect(execute_action, SIGNAL("triggered()"),
                     editor_container.run_binary)
        self.connect(close_action, SIGNAL("triggered()"),
                     editor_container.close_file)

        menu.exec_(self.mapToGlobal(point))

    def _go_to_symbol(self, index):
        editor_container = Edis.get_component("principal")
        line = self._lines_symbols[index]
        editor_container.go_to_line(line)

    def _show_icon_checker(self, value):
        index = self._editor_widget.current_index()
        icon = QIcon()
        if not value:
            icon = QIcon(":image/bug")
            self.combo_file.setItemIcon(index, icon)
        else:
            self.combo_file.setItemIcon(index, icon)

    def _close_current_file(self):
        current_editor = self._editor_widget.current_widget()
        current_index = self._editor_widget.current_index()
        self._editor_widget.remove_widget(current_editor, current_index)

    def set_modified(self, weditor, index, modified):
        if modified:
            text = " \u2022"  # Bullet caracter
            current_text = self.combo_file.currentText()
            self.combo_file.setItemText(index, current_text + text)
        else:
            text = weditor.filename
            self.combo_file.setItemText(index, text)

    def add_symbols_combo(self, symbols):
        """ Agrega símbolos al combo """

        self.combo_symbols.clear()
        self.combo_symbols.addItem(self.tr("<Selecciona un Símbolo>"))
        lines = [1]
        for symbol in symbols:

            lines.append(symbol[0])
            to_combo = symbol[1][0]
            if symbol[1][1] == 'function':
                icon = QIcon(":image/function")
            elif symbol[1][1] == 'struct':
                icon = QIcon(":image/struct")
            self.combo_symbols.addItem(icon, to_combo)
        self._lines_symbols = lines

    def move_to_symbol(self, line):
        line += 1
        index = bisect.bisect(self._lines_symbols, line)
        self.combo_symbols.setCurrentIndex(index - 1)
Beispiel #6
0
class ParamSpinBox(QAbstractSpinBox):
    def __init__(self, parent):
        QAbstractSpinBox.__init__(self, parent)

        self._minimum = 0.0
        self._maximum = 1.0
        self._default = 0.0
        self._value = None
        self._step = 0.0
        self._step_small = 0.0
        self._step_large = 0.0

        self._read_only = False
        self._scalepoints = None
        self._have_scalepoints = False

        self.bar = ParamProgressBar(self)
        self.bar.setContextMenuPolicy(Qt.NoContextMenu)
        self.bar.show()

        self.lineEdit().setVisible(False)

        self.connect(self.bar, SIGNAL("valueChangedFromBar(double)"), self.handleValueChangedFromBar)
        self.connect(self, SIGNAL("customContextMenuRequested(QPoint)"), self.showCustomMenu)

        QTimer.singleShot(0, self, SLOT("slot_updateBarGeometry()"))

    def force_plastique_style(self):
        self.setStyle(QPlastiqueStyle)

    def set_minimum(self, value):
        self._minimum = value
        self.bar.set_minimum(value)

    def set_maximum(self, value):
        self._maximum = value
        self.bar.set_maximum(value)

    def set_default(self, value):
        value = fix_value(value, self._minimum, self._maximum)
        self._default = value

    def set_value(self, value, send=True):
        value = fix_value(value, self._minimum, self._maximum)
        if self._value != value:
            self._value = value
            self.bar.set_value(value)

            if self._have_scalepoints:
                self.set_scalepoint_value(value)

            if send:
                self.emit(SIGNAL("valueChanged(double)"), value)

            self.update()

            return True

        else:
            return False

    def set_step(self, value):
        if value == 0.0:
            self._step = 0.001
        else:
            self._step = value

    def set_step_small(self, value):
        if value == 0.0:
            self._step_small = 0.0001
        else:
            self._step_small = value

    def set_step_large(self, value):
        if value == 0.0:
            self._step_large = 0.1
        else:
            self._step_large = value

    def set_label(self, label):
        self.bar.set_label(label)

    def set_text_call(self, textCall):
        self.bar.set_text_call(textCall)

    def set_read_only(self, yesno):
        self.setButtonSymbols(QAbstractSpinBox.UpDownArrows if yesno else QAbstractSpinBox.NoButtons)
        self._read_only = yesno
        self.setReadOnly(yesno)

    def set_scalepoints(self, scalepoints, use_scalepoints):
        if len(scalepoints) > 0:
            self._scalepoints = scalepoints
            self._have_scalepoints = use_scalepoints

            if use_scalepoints:
                # Hide ProgressBar and create a ComboBox
                self.bar.close()
                self.box = QComboBox(self)
                self.box.setContextMenuPolicy(Qt.NoContextMenu)
                self.box.show()
                self.slot_updateBarGeometry()

                for scalepoint in scalepoints:
                    self.box.addItem("%f - %s" % (scalepoint['value'], scalepoint['label']))

                if self._value != None:
                    self.set_scalepoint_value(self._value)

                self.connect(self.box, SIGNAL("currentIndexChanged(QString)"), self.handleValueChangedFromBox)

        else:
            self._scalepoints = None

    def set_scalepoint_value(self, value):
        value = self.get_nearest_scalepoint(value)
        for i in range(self.box.count()):
            if float(self.box.itemText(i).split(" - ", 1)[0] == value):
                self.box.setCurrentIndex(i)
                break

    def get_nearest_scalepoint(self, real_value):
        final_value = 0.0
        for i in range(len(self._scalepoints)):
            scale_value = self._scalepoints[i]['value']
            if i == 0:
                final_value = scale_value
            else:
                srange1 = abs(real_value - scale_value)
                srange2 = abs(real_value - final_value)

                if srange2 > srange1:
                    final_value = scale_value

        return final_value

    def handleValueChangedFromBar(self, value):
        if self._read_only:
            return

        step = int(0.5 + ((value - self._minimum) / self._step))
        real_value = self._minimum + (step * self._step)

        self.set_value(real_value)

    def handleValueChangedFromBox(self, box_text):
        if self._read_only:
            return

        value = float(box_text.split(" - ", 1)[0])
        last_scale_value = self._scalepoints[len(self._scalepoints) - 1]['value']

        if value == last_scale_value:
            value = self._maximum

        self.set_value(value)

    def showCustomMenu(self, pos):
        menu = QMenu(self)
        act_x_reset = menu.addAction(self.tr("Reset (%f)" % self._default))
        menu.addSeparator()
        act_x_copy = menu.addAction(self.tr("Copy (%f)" % self._value))
        if False and not self._read_only:
            act_x_paste = menu.addAction(self.tr("Paste (%s)" % "TODO"))
        else:
            act_x_paste = menu.addAction(self.tr("Paste"))
            act_x_paste.setEnabled(False)
        menu.addSeparator()
        act_x_set = menu.addAction(self.tr("Set value..."))

        if self._read_only:
            act_x_reset.setEnabled(False)
            act_x_paste.setEnabled(False)
            act_x_set.setEnabled(False)

        # TODO - NOT IMPLEMENTED YET
        act_x_copy.setEnabled(False)

        act_x_sel = menu.exec_(QCursor.pos())

        if act_x_sel == act_x_set:
            dialog = CustomInputDialog(self, self.parent().label.text(), self._value, self._minimum, self._maximum, self._step, self._scalepoints)
            if dialog.exec_():
                value = dialog.ret_value
                self.set_value(value)

        elif act_x_sel == act_x_copy:
            pass

        elif act_x_sel == act_x_paste:
            pass

        elif act_x_sel == act_x_reset:
            self.set_value(self._default)

    def stepBy(self, steps):
        if steps == 0 or self._value == None:
            return

        value = self._value + (steps * self._step)

        if value < self._minimum:
            value = self._minimum
        elif value > self._maximum:
            value = self._maximum

        self.set_value(value)

    def stepEnabled(self):
        if self._read_only or self._value == None:
            return QAbstractSpinBox.StepNone
        elif self._value <= self._minimum:
            return QAbstractSpinBox.StepUpEnabled
        elif self._value >= self._maximum:
            return QAbstractSpinBox.StepDownEnabled
        else:
            return QAbstractSpinBox.StepUpEnabled | QAbstractSpinBox.StepDownEnabled

    def updateAll(self):
        self.update()
        self.bar.update()
        if self._have_scalepoints:
            self.box.update()

    @pyqtSlot()
    def slot_updateBarGeometry(self):
        self.bar.setGeometry(self.lineEdit().geometry())
        if self._have_scalepoints:
            self.box.setGeometry(self.lineEdit().geometry())

    def resizeEvent(self, event):
        QTimer.singleShot(0, self, SLOT("slot_updateBarGeometry()"))
        QAbstractSpinBox.resizeEvent(self, event)
class ProjectTreeColumn(QDialog):
    def __init__(self, parent=None):
        super(ProjectTreeColumn, self).__init__(parent,
                                                Qt.WindowStaysOnTopHint)
        vbox = QVBoxLayout(self)
        vbox.setSizeConstraint(QVBoxLayout.SetDefaultConstraint)
        vbox.setContentsMargins(0, 0, 0, 0)
        self._buttons = []

        self._combo_project = QComboBox()
        self._combo_project.setMinimumHeight(30)
        self._combo_project.setContextMenuPolicy(Qt.CustomContextMenu)
        vbox.addWidget(self._combo_project)

        self._projects_area = QStackedLayout()
        logger.debug("This is the projects area")
        logger.debug(self._projects_area)
        vbox.addLayout(self._projects_area)

        self.projects = []

        self.connect(self._combo_project, SIGNAL("currentIndexChanged(int)"),
                     self._change_current_project)
        self.connect(self._combo_project,
                     SIGNAL("customContextMenuRequested(const QPoint &)"),
                     self.context_menu_for_root)
        connections = (
            {
                'target': 'main_container',
                'signal_name': 'addToProject(QString)',
                'slot': self._add_file_to_project
            },
            {
                'target': 'main_container',
                'signal_name': 'showFileInExplorer(QString)',
                'slot': self._show_file_in_explorer
            },
        )
        IDE.register_service('projects_explorer', self)
        IDE.register_signals('projects_explorer', connections)
        ExplorerContainer.register_tab(translations.TR_TAB_PROJECTS, self)

        #FIXME: Should have a ninja settings object that stores tree state
        #FIXME: Or bettter, application data object
        #TODO: check this:
        #self.connect(ide, SIGNAL("goingDown()"),
        #self.tree_projects.shutdown)

        #def close_project_signal():
        #self.emit(SIGNAL("updateLocator()"))

    def install_tab(self):
        ide = IDE.get_service('ide')
        ui_tools.install_shortcuts(self, actions.PROJECTS_TREE_ACTIONS, ide)

        self.connect(ide, SIGNAL("goingDown()"), self.close)

    def load_session_projects(self, projects):
        for project in projects:
            if os.path.exists(project):
                self._open_project_folder(project)

    def open_project_folder(self, folderName=None):
        if settings.WORKSPACE:
            directory = settings.WORKSPACE
        else:
            directory = os.path.expanduser("~")

        if folderName is None:
            folderName = QFileDialog.getExistingDirectory(
                self, translations.TR_OPEN_PROJECT_DIRECTORY, directory)
            logger.debug("Choosing Foldername")
        if folderName:
            logger.debug("Opening %s" % folderName)
            self._open_project_folder(folderName)

    def _open_project_folder(self, folderName):
        ninjaide = IDE.get_service("ide")
        project = NProject(folderName)
        qfsm = ninjaide.filesystem.open_project(project)
        if qfsm:
            self.add_project(project)
            self.emit(SIGNAL("updateLocator()"))
            self.save_recent_projects(folderName)
            main_container = IDE.get_service('main_container')
            if main_container:
                main_container.show_editor_area()

    def _add_file_to_project(self, path):
        """Add the file for 'path' in the project the user choose here."""
        if self._active_project:
            pathProject = [self._active_project.project]
            addToProject = add_to_project.AddToProject(pathProject, self)
            addToProject.exec_()
            if not addToProject.pathSelected:
                return
            main_container = IDE.get_service('main_container')
            if not main_container:
                return
            editorWidget = main_container.get_current_editor()
            if not editorWidget.file_path:
                name = QInputDialog.getText(
                    None, translations.TR_ADD_FILE_TO_PROJECT,
                    translations.TR_FILENAME + ": ")[0]
                if not name:
                    QMessageBox.information(
                        self, translations.TR_INVALID_FILENAME,
                        translations.TR_INVALID_FILENAME_ENTER_A_FILENAME)
                    return
            else:
                name = file_manager.get_basename(editorWidget.file_path)
            new_path = file_manager.create_path(addToProject.pathSelected,
                                                name)
            ide_srv = IDE.get_service("ide")
            old_file = ide_srv.get_or_create_nfile(path)
            new_file = old_file.save(editorWidget.get_text(), new_path)
            #FIXME: Make this file replace the original in the open tab
        else:
            pass
            # Message about no project

    def _show_file_in_explorer(self, path):
        '''Iterate through the list of available projects and show
        the current file in the explorer view for the first
        project that contains it (i.e. if the same file is
        included in multiple open projects, the path will be
        expanded for the first project only).
        Note: This slot is connected to the main container's
        "showFileInExplorer(QString)" signal.'''
        for project in self.projects:
            index = project.model().index(path)
            if index.isValid():
                # Show the explorer if it is currently hidden
                central = IDE.get_service('central_container')
                if central and not central.is_lateral_panel_visible():
                    central.change_lateral_visibility()
                # This highlights the index in the tree for us
                project.setCurrentIndex(index)
                # Loop through the parents to expand the tree
                # all the way up to the selected index.
                while index.isValid():
                    project.expand(index)
                    index = index.parent()
                break

    def add_project(self, project):
        if project not in self.projects:
            self._combo_project.addItem(project.name)
            ptree = TreeProjectsWidget(project)
            self._projects_area.addWidget(ptree)
            self.connect(ptree, SIGNAL("closeProject(PyQt_PyObject)"),
                         self._close_project)
            pmodel = project.model
            ptree.setModel(pmodel)
            pindex = pmodel.index(pmodel.rootPath())
            ptree.setRootIndex(pindex)
            self.projects.append(ptree)
            current_index = self._projects_area.count()
            self._projects_area.setCurrentIndex(current_index - 1)
            self._combo_project.setCurrentIndex(current_index - 1)

    def _close_project(self, widget):
        """Close the project related to the tree widget."""
        index = self._projects_area.currentIndex()
        self.projects.remove(widget)
        self._projects_area.takeAt(index)
        self._combo_project.removeItem(index)
        index = self._combo_project.currentIndex()
        self._projects_area.setCurrentIndex(index)
        ninjaide = IDE.get_service('ide')
        ninjaide.filesystem.close_project(widget.project.path)
        widget.deleteLater()

    def _change_current_project(self, index):
        self._projects_area.setCurrentIndex(index)

    def close_opened_projects(self):
        for project in reversed(self.projects):
            self._close_project(project)

    def save_project(self):
        """Save all the opened files that belongs to the actual project."""
        if self._active_project:
            path = self._projects_area.currentWidget().project.path
            main_container = IDE.get_service('main_container')
            if path and main_container:
                main_container.save_project(path)

    def create_new_project(self):
        wizard = new_project_manager.NewProjectManager(self)
        wizard.show()

    @property
    def current_project(self):
        if self._projects_area.count() > 0:
            return self._projects_area.currentWidget().project

    @property
    def current_tree(self):
        return self._projects_area.currentWidget()

    def save_recent_projects(self, folder):
        settings = IDE.data_settings()
        recent_project_list = settings.value('recentProjects', {})
        #if already exist on the list update the date time
        projectProperties = json_manager.read_ninja_project(folder)
        name = projectProperties.get('name', '')
        description = projectProperties.get('description', '')

        if name == '':
            name = file_manager.get_basename(folder)

        if description == '':
            description = translations.TR_NO_DESCRIPTION

        if folder in recent_project_list:
            properties = recent_project_list[folder]
            properties["lastopen"] = QDateTime.currentDateTime()
            properties["name"] = name
            properties["description"] = description
            recent_project_list[folder] = properties
        else:
            recent_project_list[folder] = {
                "name": name,
                "description": description,
                "isFavorite": False,
                "lastopen": QDateTime.currentDateTime()
            }
            #if the length of the project list it's high that 10 then delete
            #the most old
            #TODO: add the length of available projects to setting
            if len(recent_project_list) > 10:
                del recent_project_list[self.find_most_old_open(
                    recent_project_list)]
        settings.setValue('recentProjects', recent_project_list)

    def find_most_old_open(self, recent_project_list):
        listFounder = []
        for recent_project_path, content in list(recent_project_list.items()):
            listFounder.append(
                (recent_project_path,
                 int(content["lastopen"].toString("yyyyMMddHHmmzzz"))))
        listFounder = sorted(listFounder,
                             key=lambda date: listFounder[1],
                             reverse=True)  # sort by date last used
        return listFounder[0][0]

    def reject(self):
        if self.parent() is None:
            self.emit(SIGNAL("dockWidget(PyQt_PyObject)"), self)

    def closeEvent(self, event):
        self.emit(SIGNAL("dockWidget(PyQt_PyObject)"), self)
        event.ignore()

    def context_menu_for_root(self):
        menu = QMenu(self)
        path = self.current_tree.project.path
        action_add_file = menu.addAction(QIcon(":img/new"),
                                         translations.TR_ADD_NEW_FILE)
        action_add_folder = menu.addAction(QIcon(":img/openProj"),
                                           translations.TR_ADD_NEW_FOLDER)
        action_create_init = menu.addAction(translations.TR_CREATE_INIT)
        self.connect(action_add_file, SIGNAL("triggered()"),
                     lambda: self.current_tree._add_new_file(path))
        self.connect(action_add_folder, SIGNAL("triggered()"),
                     lambda: self.current_tree._add_new_folder(path))
        self.connect(action_create_init, SIGNAL("triggered()"),
                     lambda: self.current_tree._create_init(path))
        menu.addSeparator()
        actionRunProject = menu.addAction(QIcon(":img/play"),
                                          translations.TR_RUN_PROJECT)
        self.connect(actionRunProject, SIGNAL("triggered()"),
                     self.current_tree._execute_project)
        if self.current_tree._added_to_console:
            actionRemoveFromConsole = menu.addAction(
                translations.TR_REMOVE_PROJECT_FROM_PYTHON_CONSOLE)
            self.connect(actionRemoveFromConsole, SIGNAL("triggered()"),
                         self.current_tree._remove_project_from_console)
        else:
            actionAdd2Console = menu.addAction(
                translations.TR_ADD_PROJECT_TO_PYTHON_CONSOLE)
            self.connect(actionAdd2Console, SIGNAL("triggered()"),
                         self.current_tree._add_project_to_console)
        actionShowFileSizeInfo = menu.addAction(translations.TR_SHOW_FILESIZE)
        self.connect(actionShowFileSizeInfo, SIGNAL("triggered()"),
                     self.current_tree.show_filesize_info)
        actionProperties = menu.addAction(QIcon(":img/pref"),
                                          translations.TR_PROJECT_PROPERTIES)
        self.connect(actionProperties, SIGNAL("triggered()"),
                     self.current_tree.open_project_properties)

        menu.addSeparator()
        action_close = menu.addAction(
            self.style().standardIcon(QStyle.SP_DialogCloseButton),
            translations.TR_CLOSE_PROJECT)
        self.connect(action_close, SIGNAL("triggered()"),
                     self.current_tree._close_project)
        #menu for the project
        for m in self.current_tree.extra_menus_by_scope['project']:
            if isinstance(m, QMenu):
                menu.addSeparator()
                menu.addMenu(m)

        #show the menu!
        menu.exec_(QCursor.pos())
Beispiel #8
0
class typicalWindow(QtGui.QMainWindow):
	def __init__(self):
		QtGui.QMainWindow.__init__(self)
		
		#window
		
		self.setWindowTitle(winTitle)
		self.central_widget=QWidget(self)
		self.setCentralWidget(self.central_widget)
		self.masterLayout=QGridLayout(self.central_widget)
		self.masterLayout.setAlignment(QtCore.Qt.AlignTop)
		
		#mainlayout
		self.vertical_order_layout=QtGui.QBoxLayout(2)
		self.vertical_order_layout.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignVCenter)
		self.masterLayout.addLayout(self.vertical_order_layout, 0,0,1,1)
		
		self.topDivideLayout=QGridLayout()
		self.botDivideLayout=QGridLayout()
		self.upper_layout=QGridLayout()
		
		
		self.topDivideLayout.addLayout(self.upper_layout, 0,0,1,1)
		
		self.lower_layout=QGridLayout()
		self.lower_layout.setAlignment(QtCore.Qt.AlignTop)
		self.botDivideLayout.addLayout(self.lower_layout, 0,0,1,1)
		
		self.midLayout=QGridLayout()
		self.midLayout.setAlignment(QtCore.Qt.AlignTop)
		
		self.base_layout=QGridLayout()
		self.base_layout.setAlignment(QtCore.Qt.AlignTop)
		self.botDivideLayout.addLayout(self.base_layout, 4,0,1,1)
		
		sshFile=open(os.path.join(__location__, styleSheetFile+".stylesheet"), 'r')
		self.styleData=sshFile.read()
		sshFile.close
		
		self.setStyleSheet(self.styleData)
		self.top=QtGui.QFrame(self)
		self.top.setFrameShape(QtGui.QFrame.StyledPanel)
		self.top.setLayout(self.topDivideLayout)
		
		self.bottom=QtGui.QFrame(self)
		self.bottom.setFrameShape(QtGui.QFrame.StyledPanel)
		self.bottom.setLayout(self.botDivideLayout)
		
		self.splitPlane=QtGui.QSplitter(QtCore.Qt.Vertical)
		self.splitPlane.addWidget(self.top)
		self.splitPlane.addWidget(self.bottom)
		self.splitPlane.setSizes([650, 650])
		self.vertical_order_layout.addWidget(self.splitPlane)
		
		#layouts
		self.window_layer_00=QGridLayout()
		self.upper_layout.addLayout(self.window_layer_00, 0,0,1,1)
		
		self.window_layer_01=QGridLayout()
		self.upper_layout.addLayout(self.window_layer_01,1,0,1,1)
		
		self.window_layer_02=QGridLayout()
		self.upper_layout.addLayout(self.window_layer_02, 2,0,1,1)
		
		self.window_layer_03=QGridLayout()
		self.upper_layout.addLayout(self.window_layer_03,3,0,1,1)
		
		self.window_layer_04=QGridLayout()
		self.upper_layout.addLayout(self.window_layer_04, 4,0,1,1)
		
		self.window_layer_05=QGridLayout()
		self.upper_layout.addLayout(self.window_layer_05,5,0,1,1)
		
		self.window_layer_06=QGridLayout()
		self.midLayout.addLayout(self.window_layer_06, 6,0,1,1)
		
		self.frame_layout=QGridLayout()
		self.frame_layout.setAlignment(QtCore.Qt.AlignTop)
		self.lower_layout.addLayout(self.frame_layout, 0,0,1,1)
		
		
		self.frameWidget=QtGui.QGridLayout()
		self.frameWidget.setContentsMargins(5,10,5,10)
		self.frameOverride=QtGui.QFrame()
		self.frameOverride.setStyleSheet("background-color: #434343; border-style: solid; border-width: 2px; border-color:#434343;border-radius:8px;")
		self.frameOverride.setFixedHeight(100)
		self.frame_layout.addLayout(self.frameWidget, 0,0,1,1)
		self.frame_layout.addWidget(self.frameOverride, 0,0,1,1)
		
		
		self.frame_title_layout=QGridLayout()
		self.frameWidget.addLayout(self.frame_title_layout, 0,0,1,1)
		self.frame_radio_layout=QGridLayout()
		self.frameWidget.addLayout(self.frame_radio_layout, 1,0,1,1)
		self.frame_btn_layout=QGridLayout()
		self.frameWidget.addLayout(self.frame_btn_layout, 2,0,1,1)
	
		self.btm_btn_layout=QtGui.QGridLayout()
		self.btm_btn_layout.setAlignment(QtCore.Qt.AlignTop)
		self.btm_btn_layout.setContentsMargins(5,10,5,10)	
		self.wbFrame=QtGui.QFrame()
		self.wbFrame.setStyleSheet("background-color: #434343; border-style: solid; border-width: 2px; border-color:#434343;border-radius:8px;")
		self.btm_over_layout=QtGui.QGridLayout()
		self.btm_over_layout.setAlignment(QtCore.Qt.AlignTop)
		self.btm_over_layout.addLayout(self.btm_btn_layout, 0,0,1,1)
		self.btm_over_layout.addWidget(self.wbFrame, 0,0,1,1)
		
		self.pkt_layout= QGridLayout()
		self.pkt_layout.setAlignment(QtCore.Qt.AlignTop)
		self.pkt_widget=QGridLayout()
		self.pkt_widget.setContentsMargins(5,5,5,5)	
		self.pkt_frame=QFrame()
		self.pkt_frame.setMinimumWidth(650)
		self.pkt_frame.setStyleSheet("background-color: #434343; border-style: solid; border-width: 2px; border-color:#434343;border-radius:8px;")
		self.base_layout.addLayout(self.pkt_layout, 0,0,1,1)
		
		self.wndw_layer_pkt=QtGui.QGridLayout()
		self.wndw_layer_pkt.setAlignment(QtCore.Qt.AlignTop)
		self.pkt_widget.addLayout(self.wndw_layer_pkt, 0,0,1,1)
		
		self.park_btn_pkt=QtGui.QBoxLayout(2)
		self.park_btn_pkt.setAlignment(QtCore.Qt.AlignTop)
		self.park_btn_pkt.setContentsMargins(5,2,5,8)
		self.wndw_layer_pkt.addLayout(self.park_btn_pkt, 0,0,1,1)
		self.park_frame=QtGui.QFrame()
		self.park_frame.setStyleSheet("background-color: #434343; border-style: solid; border-width: 2px; border-color:#434343;border-radius:8px;")
		
		
		#widgets
		self.drop_lbl_01=QLabel()
		self.drop_lbl_01.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
		self.drop_lbl_01.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.window_layer_01.addWidget(self.drop_lbl_01, 0,0,1,1)
		
		self.drop_01=QComboBox()
		self.window_layer_01.addWidget(self.drop_01, 0,1,1,1)
		QtCore.QObject.connect(self.drop_01, SIGNAL("currentIndexChanged(QString)"),
								self.on_drop_01_changed)
		self.drop_01.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.connect(self.drop_lbl_01, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick)
		
		self.drop_lbl_02=QLabel()
		self.drop_lbl_02.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
		self.drop_lbl_02.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.window_layer_01.addWidget(self.drop_lbl_02, 0,2,1,1)
		
		self.drop_02=QComboBox()
		self.window_layer_01.addWidget(self.drop_02, 0,3,1,1)
		QtCore.QObject.connect(self.drop_02, SIGNAL("currentIndexChanged(QString)"),
								self.on_drop_01_changed)
		self.drop_02.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.connect(self.drop_lbl_01, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick)
		
		self.button_01=QPushButton("Set")
		self.button_01.setToolTip("set")
		self.connect(self.button_01, SIGNAL('clicked()'), self.connectButton01)
		self.window_layer_01.addWidget(self.button_01, 0,4,1,1)
		
		self.button_02=QPushButton("Set2")
		self.button_02.setToolTip("set2")
		self.connect(self.button_02, SIGNAL('clicked()'), self.connectButton01)
		self.window_layer_01.addWidget(self.button_02, 0,5,1,1)

		self.drop_lbl_03=QLabel()
		self.drop_lbl_03.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
		self.drop_lbl_03.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.window_layer_02.addWidget(self.drop_lbl_03, 0,0,1,1)
		
		self.drop_03=QComboBox()
		self.window_layer_02.addWidget(self.drop_03, 0,1,1,1)
		QtCore.QObject.connect(self.drop_03, SIGNAL("currentIndexChanged(QString)"),
								self.on_drop_01_changed)
		self.drop_03.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.connect(self.drop_03, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick)

		self.button_03=QPushButton("button_03")
		self.button_03.setToolTip("button_03")
		self.connect(self.button_03, SIGNAL('clicked()'), self.connectButton01)
		self.window_layer_02.addWidget(self.button_03, 0,2,1,1)
		
		self.button_04=QPushButton("button_04")
		self.button_04.setToolTip("button_04")
		self.connect(self.button_04, SIGNAL('clicked()'), self.connectButton01)
		self.window_layer_02.addWidget(self.button_04, 0,3,1,1)
		
		self.button_05=QPushButton("button_05")
		self.button_05.setToolTip("button_05")
		self.connect(self.button_05, SIGNAL('clicked()'), self.connectButton01)
		self.window_layer_02.addWidget(self.button_05, 0,4,1,1)

		self.drop_04=QComboBox()
		self.window_layer_04.addWidget(self.drop_04, 0,2,1,1)
		QtCore.QObject.connect(self.drop_04, SIGNAL("currentIndexChanged(QString)"),
								self.on_drop_01_changed)
		self.drop_04.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.connect(self.drop_04, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick)

		self.list_frame=QFrame()
		self.list_frame.setStyleSheet("color: rgb"+str(buttonColoursDict.get("red")))
		self.list_layout=QHBoxLayout()
		self.list_frame.setLayout(self.list_layout)
		
		self.drop_list_builder_05=QComboBox()
		self.drop_list_builder_05.addItems(alist)
		QtCore.QObject.connect(self.drop_list_builder_05, SIGNAL("currentIndexChanged(QString)"),
								self.build)
		self.drop_list_builder_05.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.connect(self.drop_list_builder_05, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick)
		self.list_layout.addWidget(self.drop_list_builder_05)
		self.window_layer_04.addWidget(self.list_frame, 0,3,1,1)

		self.drop_list_06=QComboBox()
		QtCore.QObject.connect(self.drop_list_06, SIGNAL("currentIndexChanged(QString)"),
								self.load)
		self.drop_list_06.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.connect(self.drop_list_06, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick)
		if len(pres)<1:
			self.drop_list_06.setEnabled(0)
		else:
			self.drop_list_06.setEnabled(1)
		self.drop_list_06.addItems(alist2)
		self.list_layout.addWidget(self.drop_list_06)
		
		self.type_list_drop=QComboBox()
		self.type_list_drop.addItems(typesOfStuffInList)
		QtCore.QObject.connect(self.type_list_drop, SIGNAL("currentIndexChanged(QString)"),
								self.on_drop_01_changed)
		self.window_layer_04.addWidget(self.type_list_drop, 0,5,1,1)
		
		self.button_06=QPushButton("button_06")
		self.button_06.setToolTip("button_06")
		self.connect(self.button_06, SIGNAL('clicked()'), self.connectButton01)	
		self.window_layer_04.addWidget(self.button_06, 0,6,0,1)
		
		self.listWidg=QtGui.QTableWidget()
		self.listWidg.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.listWidg.customContextMenuRequested.connect(self.RightClick)
		self.connect(self.listWidg, SIGNAL("itemClicked(QTableWidgetItem *)"), self.clicked)
		self.connect(self.listWidg, SIGNAL("itemDoubleClicked(QTableWidgetItem *)"), self.dclicked)
		self.window_layer_05.addWidget(self.listWidg, 0,2,1,1)
		
		self.status_lbl=QLabel()
		self.status_lbl.setStyleSheet('background-color:transparent')
		self.status_lbl.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter)
		self.frame_title_layout.addWidget(self.status_lbl, 0,2,1,1)

		self.spaceHold=QLabel()
		self.spaceHold.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.spaceHold.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter)
		self.frame_title_layout.addWidget(self.spaceHold, 0,0,1,1)


		self.checkbox=QCheckBox("add")
		self.checkbox.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.checkbox.setContentsMargins(5,0,0,0)
		self.checkbox.setChecked(1)
		self.frame_title_layout.addWidget(self.checkbox, 0,1,1,1)
		
		self.radiobox=QGridLayout()

		self.radio=QRadioButton("radio")
		self.radio.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.radio.setChecked(1)
		self.radiobox.addWidget(self.radio, 0,0,1,1)
		
		
		self.newradio=QRadioButton("newradio")
		self.newradio.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.radiobox.addWidget(self.newradio, 0,1,1,1)
		
		self.frame_len_layout=QGridLayout()
		self.frame_len_layout.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter)
		#self.frame_title_layout.addWidget(self.frame_len_layout, 1,3,1,1)
		
		self.spaceHold=QLabel()
		self.spaceHold.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.spaceHold.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter)
		self.frame_title_layout.addWidget(self.spaceHold, 0,0,1,1)
		
		self.over=QRadioButton("over")
		self.over.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.radiobox.addWidget(self.over, 1,1,1,1)
		
		self.head_lbl=QLabel("from")
		self.head_lbl.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.radiobox.addWidget(self.head_lbl, 1, 4,1,1)
		
		self.head_field=QTextEdit("")
		self.head_field.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.radiobox.addWidget(self.head_field, 1, 5,1,1)
		
		self.toe_lbl=QLabel("til")
		self.toe_lbl.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.radiobox.addWidget(self.toe_lbl, 1, 6,1,1)
		
		self.toe_field=QTextEdit("")
		self.toe_field.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.radiobox.addWidget(self.toe_field, 1, 7,1,1)
		
		self.fieldBox=QLineEdit()
		self.fieldBox.setVisible(0)
		self.fieldBox.setText(defaultText)
		
		self.go_btn=QPushButton("go")
		self.connect(self.go_btn, SIGNAL('clicked()'), self.go)
		self.frame_btn_layout.addWidget(self.go_btn, 0,0,0,1)
		
		self.look_btn=QPushButton("look")
		self.connect(self.look_btn, SIGNAL('clicked()'), self.go)
		self.frame_btn_layout.addWidget(self.look_btn, 0,1, 0,1)


		self.link_btn=QPushButton("link")
		self.connect(self.link_btn, SIGNAL('clicked()'), self.go)
		self.frame_btn_layout.addWidget(self.link_btn, 0,2,1,1)
		
		self.create_btn=QPushButton("create_btn")
		self.connect(self.create_btn, SIGNAL('clicked()'), self.go)
		self.frame_btn_layout.addWidget(self.create_btn, 0,3, 1,1)
		
		self.pocketTitle=QPushButton("title")
		self.pocketTitle.setObjectName('label')
		self.pocketTitle.setStyleSheet("QPushButton#label{font-weight:500; color: rgb"str(buttonColorDict).get("yello"))+"; button-color: rgba(255,255,255,0); font-size: 10pt; border-width: 0px; font-style: bold;}")
		self.connect(self.pocketTitle, SIGNAL('clicked()'), self.send)
		self.connect(self.pocketTitle, SIGNAL('customContextMenuRequested(QPoint)'), lambda: self.send())
		self.park_btn_pkt.addWidget(self.pocketTitle)

		self.a_btn=QPushButton("a_btn")
		self.a_btn.setStyleSheet("background-color: rgb"str(buttonColorDict).get("yello")))
		self.connect(self.a_btn, SIGNAL('clicked()'), self.go)
		self.park_btn_pkt.addWidget(self.a_btn)
		
		self.card_menu=QMenu("card")
		self.card_menuBar=self.menuBar()
		self.card_menuBar.addMenu(self.card_menu)
		self.park_btn_pkt.addWidget(self.card_menuBar)
		buttonGrp.append(self.card_menuBar)
		
		self.card_btn=QToolButton()
		self.card_btn.setPopupMode(QToolButton.MenuButtonPopup)
		self.card_btn.setMenu(self.card_menu)
		self.card_special_btn=QPushButton("card special")
		self.connect(self.card_special_btn, SIGNAL('clicked()'), self.card_special_callup)
		action=QtGui.QWidgetAction(self.card_btn)
		action.setDefaultWidget(self.card_special_btn)
		self.card_btn.menu().addAction(action)

		self.B_card_btn=QToolButton()
		self.B_card_btn.setPopupMode(QToolButton.MenuButtonPopup)
		self.B_card_btn.setMenu(self.card_menu)
		self.B_card_special_btn=QPushButton("card special")
		self.connect(self.B_card_special_btn, SIGNAL('clicked()'),self.B_card_special_callup)
		action=QtGui.QWidgetAction(self.B_card_btn)
		action.setDefaultWidget(self.B_card_special_btn)
		self.B_card_btn.menu().addAction(action)

	def buttonToggle(self):
		get_a_layout=self.park_btn_pkt
		get_size=get_a_layout.getContentsMargine()
		if get_size==(0,0,0,0):
			self.setvisible()
		else:
			self.setinvisible()
			
	def setinvisible(self):
		for each in buttonGrp:
			each.setVisible(0)
		self.park_btn_pkt.setContentsMargine(0,0,0,0)
		
	def setvisible(self):
		for each in buttonGrp:
			each.setVisible(1)
		self.park_btn_pkt.setContentsMargine(5,8,5,8)
		
	def onRightClick(self):
		path='//'
		command="xdg-open '%s'"%path
		subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
		
	def on_drop_01_changed(self):
		newcol1=self.listWidg.columnWidth(0)
		newcol2=self.listWidg.columnWidth(1)
		newcol3=self.listWidg.columnWidth(2)
		if newcol1==0:
			col1, col1, col1= 240, 160, 500
		else:
			col1, col1, col1= newcol1, newcol2, newcol3
		getPath='//'
		get_items=os.listdir(get_items)
		self.listWidg.clear()
		self.status_lbl.clear()
		self.drop_03.addItems(get_items)
		model, countdata, listArray	=self.get_listStuff()	
		if self.on_drop_01=="item1":
			buildListPath=pathList.get("listpathtype").replace(getUser, newUser)
			self.makeList(listpath, newUser, self.listWidg, model, stat_lab, listtype)
		elif self.on_drop_01=="item2":
			buildListPath=pathList.get("listpathtype2").replace(getUser, newUser)
			self.makeList(listpath, newUser, self.listWidg, model, stat_lab, listtype)
			
	def clicked(self):
		print "hi"
		
	def dclicked(self):
		print "hello"
		
	def get_listStuff(self):
		listArray=self.listWidg
		countdata=listArray.rowCount()
		model=listArray.model()
		return model, countdata, listArray
		
	def getListWidgetData(self):
		model, countdata, listArray	=self.get_listStuff()	
		dataInListWidget=[]
		for row in range(model.rowCount()):
			dataInListWidget.append([])
			for column in range(model.columnCount()):
				index = model.index(row, column)
				dataInListWidet[row].append(str(model.data(index).toString()))
		return dataInListWidget, countdata
		
	def listCreate(self):
		directory='//'
		getUser='******'
		(dataInListWidget, countdata)=self.getListWidgetData()
		self.listWidg.setRowCount(0)
		self.listWidg.setColumnCount(0)
		try:
			getFiles=[os.path.join(directory, o) for o in os.listdir(directory) if os.path.isdir(os.path.join(directory, o))]
			pass
		except:
			print "nothing found"
			return
		getFile=[(each) for each in getFiles if getpwuid(stat(each).st_uid).pw_name==getUser]
		getFiles.sort(key=lambda x: os.path.getmtime(x))
		fileDict=[]
		for each in getFiles:
			statbuf=os.stat(each)
			timeFormat=time.strftime('%m/%d/%Y', time.gmtime(os.path.getctime(each)))
			getAccTime=time.ctime(os.path.getmtime(each))
			if "  " in str(getAccTime):
				getAccTime=getAccTime.split("  ")
				getAccTime=getAccTime[1].split(" ")[1]
			else:
				getAccTime=getAccTime.split("  ")[3]
			timeFormat=timeFormat+"  "+getAccTime
			makeDict=(each, timeFormat)
			fileDict.append(makeDict)
		count=len(fileDict)
		fileDict=reversed(fileDict)
		dictItems=fileDict
		col1, col1, col1= 240, 160, 500
		headerLabels=["Name", "Date", "Path"]
		self.listWidg.setRowCount(count)
		self.listWidg.clear()
		self.listWidg.setSortingEnabled(True)
		self.listWidg.setColumnWidth(3)
		self.listWidg.setColumnWidth(0, col1)
		self.listWidg.setColumnWidth(1, col2)
		self.listWidg.setColumnWidth(2, col3)
		self.listWidg.setHorizontalHeaderLabels(headerLabels)
		getVerticalHeader=self.listWidg.verticalHeader()
		getVerticalHeader.setDefaultSelectionSize(20)
		self.listWidg.setSelectionBehavior(QAbstractItemView.SelectRows)
		self.listWidg.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.listWidg.horizontalHeaderItem(0).setTextAlignment(QtCore.Qt.AlignLeft)
		self.listWidg.horizontalHeaderItem(1).setTextAlignment(QtCore.Qt.AlignLeft)
		self.listWidg.horizontalHeaderItem(2).setTextAlignment(QtCore.Qt.AlignLeft)
		for row, item in enumerate(dictItems):
			key=item[0].split('/')[-1]
			path='/'.join(item[0].split('/')[-1])
			path="/"+path
			value=item[1]
			getTable=self.listWidg
			name=QtGui.QTableWidgetItem(key)
			name.setFlage(QtCore.Qt.ItemIsEnabled|QtCore.Qt.ItemIsSelectable)
			self.listWidg.setItem(row, 0, name)
			timeStamp=QtGui.QTableWidgetItem(value)
			self.listWidg.setItem(row, 1, timeStamp)
			location=QtGui.QTableWidgetItem(path)
			self.listWidg.setItem(row, 2, location)
		self.status_lbl.setText(grabText)
		self.status_lbl.setObjectName('non_plan_label')
		self.status_lbl.setStyleSheet('QLabel#non_plan_label{font-weight: 500; color: orange; background-color: rgba(255,255,255,0);font-size: 9pt}')
	
	def is_listWid_item_selected(self):
		listW=self.listWidg
		(dataInListWidget, countdata)=self.getListWidgetData()
		get_string_id=[]
		for index in xrange(countdata):
			get=listW.item(index, 0).isSelected()
			if get==True:
				getObj=listW.item(index, 2).text()
				getObj=str(getObj)
				get_string_id.append(getObj)
			else:
				get=listW.item(index, 1).isSelected()
				if get==True:
					getObj=listW.item(index, 2).text()
					getObj=str(getObj)
					get_string_id.append(getObj)
				else:
					get=listW.item(index, 2).isSelected()
					if get==True:
						getObj=listW.item(index, 2).text()
						getObj=str(getObj)
						get_string_id.append(getObj)
		return get_string_id
		
	def build(self):
		list_build=self.drop_list_builder_05
		list_build_function=list_build.currentText()
		selected_in_list=self.is_listWid_item_selected()
		allthePaths=('//', '//')
		allthePathsDic={"firstPath":'//', "secondPath":'//'}
		#drop_list_builder_05
		getlisttype=self.type_list_drop
		listtype=getlisttype.currentText()
		if selected_in_list>1:
			getItems=[(each) for each in selected_in_list]
			nameToSave=' '.join(getItems)
			if listtype=="firstPath":
				suffixAppend="first"
				path=allthePathsDic.get("firstPath")
			if listtype=="secondPath":
				suffixAppend="second"
				path=allthePathsDic.get("secondPath")
		compareBucket=[]
		getitems=[(suffixAppend+":"+each.split("/")[-1]) for each in selected_in_list]
		name_to_save=' '.join(getitems)
		if list_build_function==list_build[1]:
			prompt="name of list:"
			getcomment=self.makeBody(prompt)
			if getComment==None:
				print "needs name"
				return
			else:
				pass
			getComment=getComment.replace(' ', '_')
			shotList=suffixAppend+"_"+getComment+"storedText.txt"
			fileBuild=path+shotList
			copyfilemessage="creating in "+fileBuild
			replay = QtGui.QMessageBox.question(None, 'Message' ,copyfilemessage, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
			if reply == QtGui.QMessageBox.Yes:
				if os.path.isfile(fileBuild)==True:
					cmessage="create over "+fileBuild
					replay = QtGui.QMessageBox.question(None, 'Message', cmessage, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
					if reply == QtGui.QMessageBox.Yes:
						inp=open(fileBuild, "w+")
						inp.write(name_to_save)
						inp.close()
						print "created "+fileBuild
					else:
						print "cancelled"
						return
				else:
					inp=open(fileBuild, "w+")
					inp.write(name_to_save)
					inp.close()
					print "created "+fileBuild
			else:
				print "cancelled"
				return
		elif list_build_function==list_build[2]:
			fileDict, list=self.getAllLists(allthePaths)
					
	def getAllLists(self, stuff):
		fileDict={}
		for each in stuff:
			getList, getnamesdic=self.obtain_presets(each)
			getnames=getnamesdic.keys()
			for eachp in eachn in map(None, getList, getnames):
				dictlist={eachn:eachp}
				fileDict.update(dictlist)
		return fileDict, getList
			
	def obtain_presets(self, morestuff):
		preset=False
		format=".txt"
		getpreset=[os.path.join(dirpath, name) for dirpath, dirnames, files in os.walk(morestuff) for name in files if name.lower().endswith(format)]
		preset=[(each) for each in getpreset if "storedText" in each]
		getlistnames={}
		for each in preset:
			getName=each.split("/")[-1]
			nam=getName.split("_")
			getpletename='_'.join(nam[:-1])
			diction={getpletename:nam[0]}
			getlistnames.update(diction)
		return preset, getlistnames
		
	# def obtain_files(self, stuff):
	# 	preset_name=[]
	# 	if presetis!=False:
	# 		for each in presetis:
	# 			pathsplit=each.split("/")[-1]
	# 			namefind=pathsplit.split("_")[0]
	# 			preset_name.append(namefind)
	# 	else:
	# 		preset_name=False
	# 	return preset_name
		
	def makeBody(self, prompt):
		text, ok=QtGui.QInputDialog.getText(None, 'Intput Dialog', prompt)
		if ok:
			project=(str(text))
		else:
			return
		return project
		
	def makeBodyFilled(self, prompt, message):
		text, ok=QtGui.QInputDialog.getText(None, 'Intput Dialog', prompt, QtGui.QLineEdit.Normal, message)
		if ok and text:
			project=(str(text))
		else:
			return
		return project

	def load(self):
		list_load=self.drop_list_06
		list_load_function=list_build.currentText()
		allthePaths=('//', '//')
		allthePathsDic={"firstPath":'//', "secondPath":'//'}
		# getlisttype=self.type_list_drop
		# listtype=getlisttype.currentText()
		# if selected_in_list>1:
		# 	getItems=[(each) for each in selected_in_list]
		# 	nameToSave=' '.join(getItems)
		# 	if listtype=="firstPath"
		# 		suffixAppend="first"
		# 		path=allthePathsDic.get("firstPath")
		# 	if listtype=="secondPath"
		# 		suffixAppend="second"
		# 		path=allthePathsDic.get("secondPath")
		# compareBucket=[]
		# getitems=[(suffixAppend+":"+each.split("/")[-1]) for each in selected_in_list]
		# name_to_save=' '.join(getitems)
		if list_load_function==presetlist[0]:
			prompt="name of list:"
			getcomment=self.makeBody(prompt)
			if getComment==None:
				print "needs name"
				return
			else:
				pass
			getComment=getComment.replace(' ', '_')
			shotList=suffixAppend+"_"+getComment+"storedText.txt"
			fileBuild=path+shotList
			copyfilemessage="creating in "+fileBuild
			replay = QtGui.QMessageBox.question(None, 'Message', copyfilemessage, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
			if reply == QtGui.QMessageBox.Yes:
				if os.path.isfile(fileBuild)==True:
					cmessage="create over "+fileBuild
					replay = QtGui.QMessageBox.question(None, 'Message' ,cmessage, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
					if reply == QtGui.QMessageBox.Yes:
						inp=open(fileBuild, "w+")
						inp.write(name_to_save)
						inp.close()
						print "created "+fileBuild
					else:
						print "cancelled"
						return
				else:
					inp=open(fileBuild, "w+")
					inp.write(name_to_save)
					inp.close()
					print "created "+fileBuild
			else:
				print "cancelled"
				return
		elif list_build_function==list_build[2]:
			fileDict, list=self.getAllLists(allthePaths)
			
	def reset_callup(self):
		allthePaths=('//', '//')
		allthePathsDic={"firstPath":'//', "secondPath":'//'}
		getlisttype=self.type_list_drop
		listtype=getlisttype.currentText()
		if listtype=="firstPath":
			directory=allthePathsDic.get("firstPath")
		getUser=getUser
		self.directory_for_taking(getUser, directory)
		
	def directory_for_taking(self, getUser, directory):
		model, countdata, listArray	=self.get_listStuff()
		# self.status_lbl

	def connectButton01(self):
		print "hi"
	def RightClick(self):
		print "hello"
	def go(self):
		print "go"
	def send(self):
		print "end"

	def card_special_callup(self):
		print "card_special_callup"
		
	def Bcard_special_callup(self):
		print "B_card_special_callup"

		
	def B_card_special_callup(self):
		print "B_card_special_callup"
Beispiel #9
0
class ParamSpinBox(QAbstractSpinBox):
    def __init__(self, parent):
        QAbstractSpinBox.__init__(self, parent)

        self.fMinimum = 0.0
        self.fMaximum = 1.0
        self.fDefault = 0.0
        self.fValue   = None
        self.fStep    = 0.0
        self.fStepSmall = 0.0
        self.fStepLarge = 0.0

        self.fReadOnly = False
        self.fScalePoints = None
        self.fHaveScalePoints = False

        self.fBar = ParamProgressBar(self)
        self.fBar.setContextMenuPolicy(Qt.NoContextMenu)
        self.fBar.show()

        self.fName = ""

        self.lineEdit().setVisible(False)

        self.connect(self, SIGNAL("customContextMenuRequested(QPoint)"), SLOT("slot_showCustomMenu()"))
        self.connect(self.fBar, SIGNAL("valueChanged(double)"), SLOT("slot_progressBarValueChanged(double)"))

        QTimer.singleShot(0, self, SLOT("slot_updateProgressBarGeometry()"))

    def setDefault(self, value):
        value = fixValue(value, self.fMinimum, self.fMaximum)
        self.fDefault = value

    def setMinimum(self, value):
        self.fMinimum = value
        self.fBar.setMinimum(value)

    def setMaximum(self, value):
        self.fMaximum = value
        self.fBar.setMaximum(value)

    def setValue(self, value, send=True):
        value = fixValue(value, self.fMinimum, self.fMaximum)

        if self.fValue == value:
            return False

        self.fValue = value
        self.fBar.setValue(value)

        if self.fHaveScalePoints:
            self._setScalePointValue(value)

        if send:
            self.emit(SIGNAL("valueChanged(double)"), value)

        self.update()

        return True

    def setStep(self, value):
        if value == 0.0:
            self.fStep = 0.001
        else:
            self.fStep = value

        if self.fStepSmall > value:
            self.fStepSmall = value
        if self.fStepLarge < value:
            self.fStepLarge = value

    def setStepSmall(self, value):
        if value == 0.0:
            self.fStepSmall = 0.0001
        elif value > self.fStep:
            self.fStepSmall = self.fStep
        else:
            self.fStepSmall = value

    def setStepLarge(self, value):
        if value == 0.0:
            self.fStepLarge = 0.1
        elif value < self.fStep:
            self.fStepLarge = self.fStep
        else:
            self.fStepLarge = value

    def setLabel(self, label):
        self.fBar.setLabel(label)

    def setName(self, name):
        self.fName = name

    def setTextCallback(self, textCall):
        self.fBar.setTextCall(textCall)

    def setReadOnly(self, yesNo):
        self.setButtonSymbols(QAbstractSpinBox.UpDownArrows if yesNo else QAbstractSpinBox.NoButtons)
        self.fReadOnly = yesNo
        QAbstractSpinBox.setReadOnly(self, yesNo)

    def setScalePoints(self, scalePoints, useScalePoints):
        if len(scalePoints) == 0:
            self.fScalePoints     = None
            self.fHaveScalePoints = False
            return

        self.fScalePoints     = scalePoints
        self.fHaveScalePoints = useScalePoints

        if useScalePoints:
            # Hide ProgressBar and create a ComboBox
            self.fBar.close()
            self.fBox = QComboBox(self)
            self.fBox.setContextMenuPolicy(Qt.NoContextMenu)
            self.fBox.show()
            self.slot_updateProgressBarGeometry()

            for scalePoint in scalePoints:
                self.fBox.addItem("%f - %s" % (scalePoint['value'], scalePoint['label']))

            if self.fValue != None:
                self._setScalePointValue(self.fValue)

            self.connect(self.fBox, SIGNAL("currentIndexChanged(QString)"), SLOT("slot_comboBoxIndexChanged(QString)"))

    def stepBy(self, steps):
        if steps == 0 or self.fValue is None:
            return

        value = self.fValue + (self.fStep * steps)

        if value < self.fMinimum:
            value = self.fMinimum
        elif value > self.fMaximum:
            value = self.fMaximum

        self.setValue(value)

    def stepEnabled(self):
        if self.fReadOnly or self.fValue is None:
            return QAbstractSpinBox.StepNone
        if self.fValue <= self.fMinimum:
            return QAbstractSpinBox.StepUpEnabled
        if self.fValue >= self.fMaximum:
            return QAbstractSpinBox.StepDownEnabled
        return (QAbstractSpinBox.StepUpEnabled | QAbstractSpinBox.StepDownEnabled)

    def updateAll(self):
        self.update()
        self.fBar.update()
        if self.fHaveScalePoints:
            self.fBox.update()

    def resizeEvent(self, event):
        QTimer.singleShot(0, self, SLOT("slot_updateProgressBarGeometry()"))
        QAbstractSpinBox.resizeEvent(self, event)

    @pyqtSlot(str)
    def slot_comboBoxIndexChanged(self, boxText):
        if self.fReadOnly:
            return

        value          = float(boxText.split(" - ", 1)[0])
        lastScaleValue = self.fScalePoints[-1]["value"]

        if value == lastScaleValue:
            value = self.fMaximum

        self.setValue(value)

    @pyqtSlot(float)
    def slot_progressBarValueChanged(self, value):
        if self.fReadOnly:
            return

        step      = int((value - self.fMinimum) / self.fStep + 0.5)
        realValue = self.fMinimum + (step * self.fStep)

        self.setValue(realValue)

    @pyqtSlot()
    def slot_showCustomMenu(self):
        menu     = QMenu(self)
        actReset = menu.addAction(self.tr("Reset (%f)" % self.fDefault))
        menu.addSeparator()
        actCopy  = menu.addAction(self.tr("Copy (%f)" % self.fValue))

        clipboard  = QApplication.instance().clipboard()
        pasteText  = clipboard.text()
        pasteValue = None

        if pasteText:
            try:
                pasteValue = float(pasteText)
            except:
                pass

        if pasteValue is None:
            actPaste = menu.addAction(self.tr("Paste"))
        else:
            actPaste = menu.addAction(self.tr("Paste (%s)" % pasteValue))

        menu.addSeparator()

        actSet = menu.addAction(self.tr("Set value..."))

        if self.fReadOnly:
            actReset.setEnabled(False)
            actPaste.setEnabled(False)
            actSet.setEnabled(False)

        actSel = menu.exec_(QCursor.pos())

        if actSel == actSet:
            dialog = CustomInputDialog(self, self.fName, self.fValue, self.fMinimum, self.fMaximum, self.fStep, self.fScalePoints)
            if dialog.exec_():
                value = dialog.returnValue()
                self.setValue(value)

        elif actSel == actCopy:
            clipboard.setText("%f" % self.fValue)

        elif actSel == actPaste:
            self.setValue(pasteValue)

        elif actSel == actReset:
            self.setValue(self.fDefault)

    @pyqtSlot()
    def slot_updateProgressBarGeometry(self):
        self.fBar.setGeometry(self.lineEdit().geometry())
        if self.fHaveScalePoints:
            self.fBox.setGeometry(self.lineEdit().geometry())

    def _getNearestScalePoint(self, realValue):
        finalValue = 0.0

        for i in range(len(self.fScalePoints)):
            scaleValue = self.fScalePoints[i]["value"]
            if i == 0:
                finalValue = scaleValue
            else:
                srange1 = abs(realValue - scaleValue)
                srange2 = abs(realValue - finalValue)

                if srange2 > srange1:
                    finalValue = scaleValue

        return finalValue

    def _setScalePointValue(self, value):
        value = self._getNearestScalePoint(value)

        for i in range(self.fBox.count()):
            if float(self.fBox.itemText(i).split(" - ", 1)[0]) == value:
                self.fBox.setCurrentIndex(i)
                break