Exemplo n.º 1
0
    def build(self):

        # Define the user paths and home destination
        user_path = expanduser('~') + sep + 'Documents'
        browser = FileBrowser(select_string='Select',
                              favorites=[(user_path, 'Documents')])

        # Bind the action functions and load up the file browser
        browser.bind(
            on_success=self._fbrowser_success,
            on_canceled=self._fbrowser_canceled)
        return browser
	def __init__(self, engine, fileSelected, savefile=False, selectdir=False, extensions=('xml',), guixmlpath="gui/filebrowser.xml"):
		FileBrowser.__init__(self, engine, fileSelected, False, False, extensions, guixmlpath)
Exemplo n.º 3
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setStyleSheet("""
                color: white;
                background-color: #2c2c2c;
                selection-background-color: #3b5784
            """)

        self.HOME = os.path.dirname(__file__)
        self.setWindowIcon(QIcon(self.HOME + 'images/crosscobra.png'))
        self.fileBrowser = None

        self.initUI()
        self.centerOnScreen()

        helpAction = QAction(self)
        helpAction.setShortcut('F1')
        helpAction.triggered.connect(self.help)

        self.addAction(helpAction)

    def initUI(self):
        #
        #centralWidget = QWidget()

        self.setGeometry(300, 300, 1200, 600)
        self.setWindowTitle('CrossCobra - Python IDE')

        # splitters
        splitter1 = QSplitter(Qt.Vertical)
        splitter2 = QSplitter(Qt.Horizontal)

        # widgets
        self.notebook = TabWidget(self)
        self.codeView = CodeView(self, self.notebook)

        self.notebook.newTab(codeView=self.codeView)

        self.textPad = self.notebook.textPad

        self.fileBrowser = FileBrowser(self, self.textPad, self.notebook,
                                       self.codeView)
        self.textPad.fileBrowser = self.fileBrowser

        # add widgets to splitters
        splitter1.addWidget(self.fileBrowser)
        splitter1.addWidget(self.codeView)
        w = splitter1.width()
        splitter1.setSizes([w / 2, w / 2])

        splitter2.addWidget(splitter1)
        splitter2.addWidget(self.notebook)

        hbox = QHBoxLayout()
        hbox.addWidget(splitter2)

        splitter1.setStretchFactor(1, 1)
        splitter2.setStretchFactor(1, 10)

        self.setCentralWidget(splitter2)

        # actions
        newAction = QAction(QIcon(self.HOME + 'images/new.png'), 'New', self)

        newAction.setShortcut('Ctrl+N')
        newAction.triggered.connect(self.new)

        openAction = QAction(QIcon(self.HOME + 'images/open.png'), 'Open',
                             self)
        openAction.setShortcut('Ctrl+O')
        openAction.triggered.connect(self.open)

        saveAction = QAction(QIcon(self.HOME + 'images/save.png'), 'Save',
                             self)
        saveAction.setShortcut('Ctrl+S')
        saveAction.triggered.connect(self.save)

        saveAsAction = QAction(QIcon(self.HOME + 'images/saveAs.png'),
                               'Save As', self)
        saveAsAction.setShortcut('Ctrl+Shift+S')
        saveAsAction.triggered.connect(self.saveAs)

        printAction = QAction(QIcon(self.HOME + 'images/print.png'), 'Print',
                              self)
        printAction.setShortcut('Ctrl+P')
        printAction.triggered.connect(self.onPrint)

        undoAction = QAction(QIcon(self.HOME + 'images/undo.png'), 'Undo',
                             self)
        undoAction.setShortcut('Ctrl+Z')
        undoAction.triggered.connect(self.undo)

        redoAction = QAction(QIcon(self.HOME + 'images/redo.png'), 'Redo',
                             self)
        redoAction.setShortcut('Ctrl+Shift+Z')
        redoAction.triggered.connect(self.redo)

        zoomInAction = QAction(QIcon(self.HOME + 'images/zoomIn.png'),
                               'ZoomIn', self)
        zoomInAction.setShortcut('Ctrl++')
        zoomInAction.triggered.connect(self.zoomIn)

        zoomOutAction = QAction(QIcon(self.HOME + 'images/zoomOut.png'),
                                'ZoomOut', self)
        zoomOutAction.setShortcut('Ctrl+-')
        zoomOutAction.triggered.connect(self.zoomOut)

        settingsAction = QAction(QIcon(self.HOME + 'images/settings.png'),
                                 'Settings', self)
        settingsAction.setShortcut('F9')
        settingsAction.triggered.connect(self.showSettings)

        interpreterAction = QAction(
            QIcon(self.HOME + 'images/interpreter.png'),
            'Start Python Interpreter', self)
        interpreterAction.setShortcut('F10')
        interpreterAction.triggered.connect(self.interpreter)

        terminalAction = QAction(QIcon(self.HOME + 'images/terminal.png'),
                                 'Start Terminal', self)
        terminalAction.setShortcut('F11')
        terminalAction.triggered.connect(self.terminal)

        runAction = QAction(QIcon(self.HOME + 'images/run.png'), 'Run File',
                            self)
        runAction.setShortcut('F12')
        runAction.triggered.connect(self.run)

        searchShortcut = QShortcut(self)
        searchShortcut.setKey('Ctrl+F')
        searchShortcut.activated.connect(self.onSearch)

        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        # make toolbar
        self.toolbar = QToolBar()
        self.toolbar.setStyleSheet('''
            QToolButton::hover { background-color: darkgreen;}
        ''')

        self.toolbar.setContextMenuPolicy(Qt.PreventContextMenu)
        self.addToolBar(Qt.RightToolBarArea, self.toolbar)

        self.toolbar.addSeparator()
        self.toolbar.addAction(newAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(openAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(saveAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(saveAsAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(printAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(undoAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(redoAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(zoomInAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(zoomOutAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(settingsAction)
        self.toolbar.addSeparator()
        self.toolbar.addWidget(spacer)
        self.toolbar.addAction(interpreterAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(terminalAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(runAction)

        # make statusbar
        self.statusBar = QStatusBar()
        self.searchEdit = QLineEdit()
        spacer2 = QWidget()

        self.searchEdit.setStyleSheet('''
                background-color: white;
                color: black;
            ''')
        self.searchEdit.returnPressed.connect(self.onSearch)
        self.searchButton = QPushButton(QIcon(self.HOME + 'images/search.png'),
                                        'Search', self)
        self.searchButton.setStyleSheet('''
            QPushButton::hover { background-color: darkgreen;}
        ''')
        self.searchButton.clicked.connect(self.onSearch)
        self.statusBar.addPermanentWidget(spacer2)
        self.statusBar.addPermanentWidget(self.searchEdit)
        self.statusBar.addPermanentWidget(self.searchButton)
        self.setStatusBar(self.statusBar)
        # show all
        self.show()

    def new(self):
        editor = CodeEditor(parent=self)
        editor.filename = None

        self.notebook.newTab(editor)

        x = self.notebook.count()
        index = x - 1

        self.notebook.setCurrentIndex(index)
        self.textPad = editor
        self.notebook.textPad = editor
        self.mainWindow = self.textPad.mainWindow

    def open(self):
        dialog = QFileDialog(self)
        dialog.setViewMode(QFileDialog.List)
        dialog.setDirectory(os.getcwd())

        filename = dialog.getOpenFileName(self, "Save")

        if filename[0]:
            filePath = filename[0]

            try:
                with open(filePath, 'r') as f:
                    text = f.read()

                editor = CodeEditor(self)
                editor.setText(text)
                editor.filename = filePath

                self.notebook.newTab(editor)
                x = self.notebook.count()  # number of tabs
                index = x - 1
                self.notebook.setCurrentIndex(index)

                tabName = os.path.basename(editor.filename)
                self.notebook.setTabText(x, tabName)
                self.textPad = editor

            except Exception as e:
                self.statusBar.showMessage(str(e), 3000)

    def save(self):
        filename = self.textPad.filename
        index = self.notebook.currentIndex()
        tabText = self.notebook.tabText(index)

        if not filename:
            self.saveAs()

        else:
            text = self.textPad.text()
            try:
                with open(filename, 'w') as file:
                    file.write(text)
                    self.statusBar.showMessage(filename + " saved", 3000)

                    # remove '*' in tabText
                    fname = os.path.basename(filename)
                    self.notebook.setTabText(index, fname)

            except Exception as e:
                self.statusBar.showMessage(str(e), 3000)
                self.saveAs()

    def saveAs(self):
        ## to do ....
        dialog = QFileDialog(self)
        dialog.setViewMode(QFileDialog.List)
        dialog.setDirectory(os.getcwd())

        filename = dialog.getSaveFileName(self, "Save")

        if filename[0]:
            fullpath = filename[0]
            text = self.textPad.text()
            try:
                with open(fullpath, 'w') as file:
                    file.write(text)
                    self.statusBar.showMessage(fullpath + " saved", 3000)

                    # update all widgets

                    self.textPad.filename = fullpath
                    self.refresh(self.textPad)
                    self.fileBrowser.refresh()
                    fname = os.path.basename(fullpath)
                    index = self.notebook.currentIndex()
                    self.notebook.setTabText(index, fname)

            except Exception as e:
                self.statusBar.showMessage(str(e), 3000)

        else:
            self.statusBar.showMessage('File not saved !', 3000)

    def onPrint(self):
        doc = QsciPrinter()
        dialog = QPrintDialog(doc, self)
        dialog.setWindowTitle('Print')

        if (dialog.exec_() == QDialog.Accepted):
            self.textPad.setPythonPrintStyle()
            try:
                doc.printRange(self.textPad)
            except Exception as e:
                print(str(e))

        else:
            return

        self.textPad.setPythonStyle()

    def undo(self):
        self.textPad.undo()

    def redo(self):
        self.textPad.redo()

    def zoomIn(self):
        self.textPad.zoomIn()

    def zoomOut(self):
        self.textPad.zoomOut()

    def showSettings(self):
        dialog = SettingsDialog(self, self.textPad)
        dialog.setModal(False)
        dialog.exec_()

    def interpreter(self):
        c = Configuration()
        system = c.getSystem()
        command = c.getInterpreter(system)

        thread = RunThread(command)
        thread.start()

    def terminal(self):
        c = Configuration()
        system = c.getSystem()
        command = c.getTerminal(system)

        thread = RunThread(command)
        thread.start()

    def run(self):
        self.save()
        c = Configuration()
        system = c.getSystem()
        command = c.getRun(system).format(self.textPad.filename)

        if not self.textPad.filename:
            self.statusBar.showMessage("can't run without filename !", 3000)
            return

        thread = RunThread(command)
        thread.start()

    def onSearch(self):
        text = self.searchEdit.text()
        if text is '':
            self.statusBar.showMessage("can't start search without word", 3000)
            return
        else:
            x = self.textPad.findFirst(text, False, True, False, True,
                                       True)  # case sensitive

            if x == False:
                l = len(self.searchEdit.text())
                self.searchEdit.setSelection(0, l)
                self.searchEdit.setFocus()
                self.statusBar.showMessage('<' + text + '> not found', 3000)

    def refresh(self, textPad=None):
        if not textPad:
            return

        self.textPad = textPad

        if not self.textPad.filename:
            self.setWindowTitle('CrossCobra - Python IDE')
            return

        dir = os.path.dirname(self.textPad.filename)

        try:
            os.chdir(dir)
            self.setWindowTitle(self.textPad.filename)

        except Exception as e:
            self.statusBar.showMessage(str(e), 3000)

        self.fileBrowser.refresh(dir)
        self.codeView.refresh()

    def centerOnScreen(self):
        res = QDesktopWidget().screenGeometry()
        self.move((res.width() / 2) - (self.frameSize().width() / 2),
                  (res.height() / 2) - (self.frameSize().height() / 2))

    def help(self):
        helpdialog = HelpDialog(self)
        helpdialog.exec_()
Exemplo n.º 4
0
class SpriteViewerActivity(Activity):

    __interfaces__ = [FileOpenInterface]
    
    __fields__ = {"temp_file": File}
    
    def __init__(self):
    
        Activity.__init__(self)
        self.showing = "files"
        self.temp_file = None
    
    """We reimplement the `onCreate` method to provide a user interface for the
    application and to record how the application was started. If it was
    launched normally, it will show a file browser. If it was run as the result
    of opening a spritefile in a file manager application, it will show the
    sprites contained in that spritefile."""
    
    def onCreate(self, bundle):
    
        Activity.onCreate(self, bundle)
        
        self.resources = self.getResources()
        
        self.fileBrowser = FileBrowser(self)
        self.fileBrowser.setHandler(self)
        
        self.spriteBrowser = SpriteBrowser(self)
        self.registerForContextMenu(self.spriteBrowser.getGrid())
        
        self.setContentView(self.fileBrowser)
        
        # Obtain the intent that caused the activity to be started and define
        # the initial view to be displayed.
        intent = self.getIntent()
        
        self.initial_view = "files"
        
        # If the application was started with an intent requesting a view
        # action then we show the sprite browser instead of the file browser.
        if intent.getAction() == Intent.ACTION_VIEW:
        
            uri = intent.getData()
            
            if uri.getScheme() == "file":
                self.initial_view = "sprites"
                self.handleFileOpen(File(uri.getPath()))
    
    def onResume(self):
    
        Activity.onResume(self)
    
    def onPause(self):
    
        Activity.onPause(self)
    
    """The reimplementation of the `onStop` method checks for the presence of
    a temporary file and deletes it."""
    
    def onStop(self):
    
        Activity.onStop(self)
        
        if self.temp_file != None:
            self.temp_file.delete()
    
    """The following method is used to respond to configuration changes, such
    as those caused by an orientation change, calling a custom method in the
    sprite browser view."""
    
    def onConfigurationChanged(self, config):
    
        Activity.onConfigurationChanged(self, config)
        self.spriteBrowser.updateLayout(config.screenWidthDp)
    
    """We reimplement the `onBackPressed` method to change the usual behaviour
    of the interface. If the view being displayed is the same as the one shown
    when the application started then the standard behaviour is used. Otherwise
    we show the file browser."""
    
    def onBackPressed(self):
    
        # If showing the initial view then exit, otherwise show the file browser.
        if self.showing == self.initial_view:
            Activity.onBackPressed(self)
        else:
            self.showing = "files"
            self.fileBrowser.rescan()
            self.setContentView(self.fileBrowser)
    
    """The following method is used to handle file open requests from the
    file browser, responding to them by changing the current view and opening
    the selected file in the sprite browser."""
    
    def handleFileOpen(self, file):
    
        self.spriteBrowser.openFile(file)
        self.showing = "sprites"
        self.setContentView(self.spriteBrowser)
    
    """We support the creation of a context menu with the following method
    which defines two menu items, storing them for later checks when a menu
    item is selected by the user."""
    
    def onCreateContextMenu(self, menu, view, menuInfo):
    
        self.viewItem = menu.add(Menu.NONE, 1, Menu.NONE, "Show full size")
        self.saveItem = menu.add(Menu.NONE, 2, Menu.NONE, "Save as PNG")
    
    """When a menu item is selected, we check it against the two defined items
    and either show the current sprite in an external application or save it to
    a file, depending on which item was selected."""
    
    def onContextItemSelected(self, item):
    
        menuInfo = CAST(item.getMenuInfo(), AdapterView.AdapterContextMenuInfo)
        position = menuInfo.position
        
        if item.getItemId() == self.viewItem.getItemId():
            self.viewSprite(self.spriteBrowser.getSpriteBitmap(position))
            return True
        
        elif item.getItemId() == self.saveItem.getItemId():
            self.saveSprite(self.spriteBrowser.getSpriteFileName(),
                            self.spriteBrowser.getSpriteName(position),
                            self.spriteBrowser.getSpriteBitmap(position))
            return True
        
        return False
    
    """The following method is used to handle sprite view requests. It saves
    the `Bitmap` passed to the method to a PNG file in the device's external
    storage. Finally, it broadcasts an intent to request that the newly saved
    file be displayed by a suitable application."""
    
    @args(void, [Bitmap])
    def viewSprite(self, bitmap):
    
        self.temp_file = Files.createExternalFile(Environment.DIRECTORY_DOWNLOADS,
            "SpriteViewer", ".temp", "", ".png")
        
        stream = BufferedOutputStream(FileOutputStream(self.temp_file))
        bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream)
        stream.flush()
        # Closing the file with close() will cause an exception.
        
        intent = Intent()
        intent.setAction(Intent.ACTION_VIEW)
        intent.setDataAndType(Uri.parse("file://" + self.temp_file.getPath()), "image/png")
        self.startActivity(intent)
    
    """This method saves a PNG file to a subdirectory of the `SpriteViewer`
    directory in the device's external storage. It shows a transient message
    to indicate that it has saved a file."""
    
    @args(void, [String, String, Bitmap])
    def saveSprite(self, spritefileName, spriteName, bitmap):
    
        # Create a subdirectory of the SpriteViewer directory for the current
        # set of sprites.
        subDir = File(Environment.DIRECTORY_DOWNLOADS, "SpriteViewer")
        
        outputFile = Files.createExternalFile(subDir.getPath(),
            spritefileName, spriteName, "", ".png")
        
        stream = BufferedOutputStream(FileOutputStream(outputFile))
        bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream)
        stream.flush()
        
        Toast.makeText(self, "Saved " + outputFile.getPath(), Toast.LENGTH_LONG).show()
Exemplo n.º 5
0
class MainWindow(QMainWindow):
    """
    This class handles all of the UI elements and how they operate and connect to the logical pieces.
    """

    # CONSTRUCTOR ------------------------------------------------------------------------------------------------------

    def __init__(self, app):
        super(MainWindow, self).__init__()

        # Instance Variables
        self.ui = Ui_MainWindow()
        self.app = app
        self.fb = FileBrowser()
        self.collapser = Collapser()
        self.widgets = []

        # Sets up UI based on the auto-generated python file
        self.ui.setupUi(self)

        # Sets up all initial functionality for the program
        self.setup_functionality()

    # METHODS ----------------------------------------------------------------------------------------------------------

    def move_forward(self):
        """
        Navigates forwards visually in the file tree if only one folder is selected. If more than one folder is
        selected OR a regular file is selected, then nothing happens.
        """
        widgets = self.ui.systemTreeWidget.selectedItems()
        # if there is one item selected
        if len(widgets) == 1:
            widget = widgets[0]
            # If it is a folder, not a regular file
            if widget.text(2) == "Folder":
                # Updates current path in the filebrowser for the logical side of the file system
                current_path = self.fb.get_current_path()
                new_path = current_path + "/" + widget.text(0)
                self.update_path(new_path)

    def move_back(self):
        """
        Navigates backwards in the file tree to the parent directory visually.
        """
        new_path = self.fb.get_parent_path()
        self.update_path(new_path)

    def update_path(self, new_path):
        """
        This method handles everything that goes with changing the file path regardless of which direction the
        movement is happening in. It clears the trees containing the current files so the new ones can be displayed,
        clears the list of widgets, sets the text in the line edit, logically upadtes the path in the file browser,
        and lastly updates the visual file browser in the left tree.
        :param new_path: the new path to display
        """
        self.ui.systemTreeWidget.clear()
        self.ui.selectedTreeWidget.clear()
        clear_list(self.widgets)
        self.ui.pathLineEdit.setText(new_path)
        self.fb.set_current_path(new_path)
        self.populate_system_tree()

    def update_multi_select_option(self):
        """
        Method updates the type of selection when the user clicks the multi select checkbox. Either enables multi or
        single selection using helper methods.
        """
        if self.ui.multiCheckBox.isChecked():
            self.setup_multi_select()
        else:
            self.setup_single_select()

    def setup_functionality(self):
        """
        This method sets up all of the miscellaneous functionality that is not part of setupUI.
        """
        # Populates the left tree with the user's base folder
        self.populate_system_tree()
        # Sets the contents of the line edit to the the current path
        self.ui.pathLineEdit.setText(self.fb.get_current_path())
        # Connects all buttons and functionalities
        self.connect_buttons()
        # Sets up multi-select (multi-select is on by default)
        self.setup_multi_select()
        # Establishes connection between right tree and double click event
        self.ui.selectedTreeWidget.itemDoubleClicked.connect(
            self.on_double_click)
        # Sets the initial state of the multi-select checkbox to checked
        self.ui.multiCheckBox.setChecked(True)
        # Sets up connection between returnPressed and submitting the path change
        self.ui.pathLineEdit.returnPressed.connect(self.submit_path_change)

    def on_double_click(self):
        """
        This method handles a double click on a file in the righthand file browser. This opens a file or a folder
        in the operating system's default application.
        """
        # this should only be one since this widget only accepts one select
        items = self.ui.selectedTreeWidget.selectedItems()
        item_name = items[0].text(0)
        self.fb.open_file(item_name)

    def submit_path_change(self):
        """
        Submits the path change if it is made in the QLineEdit. Gets the value in the text edit and passes it into
        update_path to make all the necessary changes.
        """
        path = self.ui.pathLineEdit.text()
        self.update_path(path)

    def setup_multi_select(self):
        """
        This method enables multi selection on the lefthand file browser.
        """
        self.ui.systemTreeWidget.setSelectionMode(
            QtWidgets.QAbstractItemView.MultiSelection)

    def setup_single_select(self):
        """
        This method enables single selection on the lefthand file browser.
        """
        self.ui.systemTreeWidget.setSelectionMode(
            QtWidgets.QAbstractItemView.SingleSelection)

    def select_all(self):
        """
        Selects all files in the lefthand browser and updates the right widget
        """
        self.ui.systemTreeWidget.selectAll()
        self.update_right_widget()

    def deselect_all(self):
        """
        Deselects all files in the lefthand browser and updates the right widget
        """
        self.ui.systemTreeWidget.clearSelection()
        self.update_right_widget()

    def update_right_widget(self):
        """
        This function is called whenever there is a click event registered in the app. To ensure the list isn't being
        updated unnecessarily, the current widgets are stored and the selected ones are compared to that list. If those
        lists are different, then the right widget is updated.
        :return:
        """
        self.widgets.sort()
        new_widgets = self.ui.systemTreeWidget.selectedItems()
        new_widgets.sort()
        if not self.ui.multiCheckBox.isChecked(
        ) or not self.widgets == new_widgets:
            equalize_lists(self.widgets, new_widgets)
            self.populate_selected_tree()
            self.set_expansion()

    def connect_buttons(self):
        """
        Connects all buttons and other click events to their corresponding functions
        """
        self.ui.expandCollapseButton.clicked.connect(
            self.expand_collapsed_clicked)
        self.ui.selectAllButton.clicked.connect(self.select_all)
        self.ui.deselectButton.clicked.connect(self.deselect_all)
        self.ui.backButton.clicked.connect(self.move_back)
        self.ui.forwardButton.clicked.connect(self.move_forward)
        self.ui.multiCheckBox.clicked.connect(self.update_multi_select_option)
        self.ui.goButton.clicked.connect(self.submit_path_change)

    def expand_collapsed_clicked(self):
        """
        Function for when the expand collapsed/collapse files button is pressed. Handles everything that needs to
        happen when the user presses that button.
        """
        # Sets the button to using the correct text and other ui elements
        exp_coll = "Expand Collapsed"
        coll = "Collapse Files"
        cur = self.ui.expandCollapseButton.text()
        should_expand = True if cur == exp_coll else False
        new = coll if should_expand else exp_coll
        self.ui.expandCollapseButton.setText(new)

        # Handles what happens to the actual files
        if should_expand:
            self.expand_collapsed_items()
        else:
            self.collapse_items()

    def set_expansion(self):
        exp_coll = "Expand Collapsed"
        coll = "Collapse Files"
        cur = self.ui.expandCollapseButton.text()
        should_expand = True if cur == coll else False
        # Handles what happens to the actual files
        if should_expand:
            self.expand_collapsed_items()
        else:
            self.collapse_items()

    def expand_collapsed_items(self):
        """
        Function to take the collapsed items and uncollapse them.
        """
        num_items = self.ui.selectedTreeWidget.topLevelItemCount()
        results = []
        for i in range(0, num_items):
            widget = self.ui.selectedTreeWidget.topLevelItem(i)
            # If the current widget item indicates it is collapsed or collapsible
            if str_to_bool(widget.text(1)):
                # Get list of all file names gotten from the collapsed name
                names = Collapser.get_names_from_condensed(widget.text(0))
                for name in names:
                    new_widg = QtWidgets.QTreeWidgetItem()
                    new_widg.setText(0, name)
                    new_widg.setText(1, widget.text(1))
                    results.append(new_widg)
            else:
                new_widg = QtWidgets.QTreeWidgetItem()
                new_widg.setText(0, widget.text(0))
                new_widg.setText(1, widget.text(1))
                results.append(new_widg)
        results.sort()
        self.ui.selectedTreeWidget.clear()
        # Add all widgets to the tree
        self.ui.selectedTreeWidget.addTopLevelItems(results)

    def collapse_items(self):
        """
        Function to collapse the uncollapsed items.
        """
        self.populate_selected_tree()

    def populate_system_tree(self):
        """
        This method populates the visual file browser on the lefthand side of the ui based on the path stored in the
        file browser. Creates all of the widgets and adds them to the tree.
        """
        # gets all filenames from the current path
        files = self.fb.get_files_in_dir()
        self.collapser.make_final_list(files)
        collapsedFiles = self.collapser.get_result_files()
        collapsedTF = self.collapser.get_collapsed_list()
        widgets = []
        # Create widgets to add to the tree list
        for i in range(0, len(collapsedFiles)):
            widget = QtWidgets.QTreeWidgetItem()
            widget.setText(0, collapsedFiles[i])
            type = "Folder" if self.fb.is_dir(collapsedFiles[i]) else "File"
            widget.setText(2, type)
            collapsed = "Yes" if collapsedTF[i] else "No"
            widget.setText(1, collapsed)
            widgets.append(widget)
        # Add all widgets to the tree
        self.ui.systemTreeWidget.addTopLevelItems(widgets)

    def populate_selected_tree(self):
        """
        This method populates the righthand tree of files. This is called whenever a new file is selected or deselected.
        It creates new widgets based on the old and adds them to the other tree.
        """
        # Clears any old widgets so duplicates are not added
        self.ui.selectedTreeWidget.clear()
        new_widgets = []
        for widget in self.widgets:
            new_widg = QtWidgets.QTreeWidgetItem()
            name = widget.text(0)
            new_widg.setText(0, name)
            new_widg.setText(1, widget.text(1))
            new_widgets.append(new_widg)
        new_widgets.sort()
        # Add all widgets to the tree
        self.ui.selectedTreeWidget.addTopLevelItems(new_widgets)
Exemplo n.º 6
0
    def build(self):
        source_test = r"C:\Users\Nathan Longhurst\Documents\Git\kivy\files"
        source_test = r"C:\Users\Nathan Longhurst\Documents\UX\Image Test"
        #source_test = r"C:\Users\Nathan Longhurst\Documents\Windows Root\Harrisons Kivy Project\Actual Folder\Testing Images Folder\Harrison's Stock\Variants"
        #source_test = r"C:\Users\Nathan Longhurst\Documents\Windows Root\Harrisons Kivy Project\Actual Folder\Testing Images Folder\Harrison's Stock\36 images"
        source_test = r"C:\Users\Nathan Longhurst\Documents\Windows Root\Harrisons Kivy Project\Actual Folder\Testing Images Folder\Photoshop Template"

        # indexing starting at 1 because yolo

        width_of_file_browser = 270
        width_of_viewport = 270

        file_browser_1 = FileBrowser("Range",
                                     size_hint=(None, 1),
                                     width=width_of_file_browser)
        file_browser_1.populate(source_test)
        viewport_1 = Viewport(size_hint=(None, 1), width=width_of_viewport)

        file_browser_2 = FileBrowser("Range",
                                     size_hint=(None, 1),
                                     width=width_of_file_browser)
        file_browser_2.populate(source_test)
        viewport_2 = Viewport(size_hint=(None, 1), width=width_of_viewport)

        file_browser_3 = FileBrowser("Range",
                                     size_hint=(None, 1),
                                     width=width_of_file_browser)
        file_browser_3.populate(source_test)
        viewport_3 = Viewport(size_hint=(None, 1), width=width_of_viewport)

        #file_browser2 = FileBrowser("Variant", 270, 600)
        #file_browser2.populate(source_test)

        #file_browser3 = FileBrowser("Room", 270, 600)
        #file_browser3.populate(source_test)

        column_1 = BoxLayout(orientation="vertical",
                             size_hint=(None, 1),
                             width=width_of_file_browser + width_of_viewport)

        file_browser_viewport_row_1 = BoxLayout(
            orientation="horizontal",
            size_hint=(None, 1),
            width=width_of_file_browser + width_of_viewport
        )  # this seems gross, should I get it to calculate the width of its children?
        file_browser_viewport_row_1.add_widget(file_browser_1)
        file_browser_viewport_row_1.add_widget(viewport_1)

        file_browser_viewport_row_2 = BoxLayout(orientation="horizontal",
                                                size_hint=(None, 1),
                                                width=width_of_file_browser +
                                                width_of_viewport)
        file_browser_viewport_row_2.add_widget(file_browser_2)
        file_browser_viewport_row_2.add_widget(viewport_2)

        file_browser_viewport_row_3 = BoxLayout(orientation="horizontal",
                                                size_hint=(None, 1),
                                                width=width_of_file_browser +
                                                width_of_viewport)
        file_browser_viewport_row_3.add_widget(file_browser_3)
        file_browser_viewport_row_3.add_widget(viewport_3)

        column_1.add_widget(file_browser_viewport_row_1)
        column_1.add_widget(file_browser_viewport_row_2)
        column_1.add_widget(file_browser_viewport_row_3)

        column_2 = BoxLayout(orientation="vertical")

        a_big_viewport = BigViewport(
            size_hint=(1, 1))  # size_hint by default is 1, 1
        column_2.add_widget(a_big_viewport)

        housing_widget = BoxLayout(
            orientation="horizontal")  # size hint by default is 1, 1
        housing_widget.add_widget(column_1)
        housing_widget.add_widget(column_2)

        return housing_widget
Exemplo n.º 7
0
     solitaire.set_location(x, y)
     arcade.run()
 elif 'SRV_BROWSE' in event:
     browser = ServerBrowser(client, client.window['SRV_FOLDER'].get())
     srv_folder = browser.show()
     client.session.srv_folder = srv_folder
     browser.window.close()
 elif event == "Options Menu":
     opts = windows.options_window(client)
     while True:
         opt_event, opt_vals = opts.read()
         if opt_event in ["Exit", sG.WIN_CLOSED]:
             break
         if opt_event.startswith('BROWSE_'):
             prefix = opt_event.split('_')[1]
             browser = FileBrowser(opts[prefix + '_FOLDER'].get())
             folder = browser.show()
             opts[prefix + '_FOLDER'].update(value=folder)
             browser.window.close()
         if opt_event in client.options.dict.keys():
             client.options[opt_event] = opt_vals[opt_event]
         if 'SRV' in opt_event:
             server.opt_set(
                 opt_event.split('_')[1], opt_vals[opt_event])
         if opt_event == 'SERV_BROWSE':
             filetype = opts[opt_event].metadata
             browser = FileBrowser(client.options['HOST_FOLDER'])
             srv_folder = browser.show()
             opts['SRV_folder'].update(value=srv_folder)
             server.opt_set('folder', srv_folder)
             browser.window.close()
Exemplo n.º 8
0
class MultipleDataLayout(BoxLayout):
    doc_path = ""
    previous_date = None

    def open_date_picker(self):
        from kivymd.uix.picker import MDDatePicker

        if self.previous_date is not None:
            pd = self.previous_date
            try:
                MDDatePicker(self.set_previous_date, pd.year, pd.month,
                             pd.day).open()
            except AttributeError:
                MDDatePicker(self.set_previous_date).open()
        else:
            MDDatePicker(self.set_previous_date).open()

    def set_previous_date(self, date_obj):

        self.previous_date = date_obj
        self.ids.date.text = "-".join(str(date_obj).split("-")[::-1])

    def open_FileSelector(self, inst):

        if platform == "win":
            user_path = dirname(expanduser("~")) + sep + "Documents"
        else:
            user_path = expanduser("~") + sep + "Documents"
        self._fbrowser = FileBrowser(
            select_string="Select",
            favorites=[(user_path, "Documents")],
            filters=["*.pdf", "*.jpg", "*.jpeg", "*.png"],
        )
        self._fbrowser.bind(
            on_success=partial(self._fbrowser_success, inst),
            on_canceled=self._fbrowser_canceled,
        )

        self.fpopup = Popup(
            content=self._fbrowser,
            title_align="center",
            title="Select File",
            size_hint=(0.7, 0.9),
            auto_dismiss=False,
        )
        self.fpopup.open()

    def _fbrowser_canceled(self, instance):
        self.fpopup.dismiss()

    def _fbrowser_success(self, layoutins, instance):
        try:
            selected_path = instance.selection[0]
            if selected_path:
                layoutins.doc_path = selected_path
                layoutins.ids.docName.text = os.path.basename(selected_path)
                layoutins.ids.viewBtn.opacity = 1
                layoutins.ids.viewBtn.disabled = False
                Snackbar(text="File uploaded successfully!", duration=2).show()
            else:
                Snackbar(text="Error uploading file.", duration=2).show()
            self.fpopup.dismiss()

        except IndexError:
            Snackbar(text="Please specify a valid file path",
                     duration=2).show()

    def show_doc(self):
        import generate_fee_receipt

        generate_fee_receipt.show_doc(self.doc_path)

    def delete(self, root):
        if len(root.parent.children) > 1:
            if (root.ids.rem.text == "Late Fine"):
                root.parent.parent.parent.ids.lateCheckbox.active = False
            else:
                root.parent.height = 60 * (len(root.parent.children) - 1)
                root.parent.parent.parent.height = 60 * (
                    len(root.parent.children) - 1) + 230
                root.parent.remove_widget(root)