Search in sources :

Example 11 with Sequence

use of org.apache.pivot.collections.Sequence in project pivot by apache.

the class JSON method get.

/**
 * Returns the value at a given path.
 *
 * @param <T> The type of value to expect.
 * @param root The root object.
 * @param keys The path to the value as a sequence of keys.
 * @return The value at the given path.
 */
@SuppressWarnings("unchecked")
public static <T> T get(Object root, Sequence<String> keys) {
    Utils.checkNull(keys, "keys");
    Object value = root;
    for (int i = 0, n = keys.getLength(); i < n; i++) {
        if (value == null) {
            break;
        }
        String key = keys.get(i);
        Map<String, T> adapter = (Map<String, T>) (value instanceof java.util.Map ? new MapAdapter<>((java.util.Map<String, T>) value) : (value instanceof Map ? ((Map<String, T>) value) : new BeanAdapter(value)));
        if (adapter.containsKey(key)) {
            value = adapter.get(key);
        } else if (value instanceof Sequence<?>) {
            Sequence<Object> sequence = (Sequence<Object>) value;
            value = sequence.get(Integer.parseInt(key));
        } else if (value instanceof Dictionary<?, ?>) {
            Dictionary<String, Object> dictionary = (Dictionary<String, Object>) value;
            value = dictionary.get(key);
        } else {
            throw new IllegalArgumentException("Property \"" + key + "\" not found.");
        }
    }
    return (T) value;
}
Also used : Dictionary(org.apache.pivot.collections.Dictionary) Sequence(org.apache.pivot.collections.Sequence) BeanAdapter(org.apache.pivot.beans.BeanAdapter) Map(org.apache.pivot.collections.Map)

Example 12 with Sequence

use of org.apache.pivot.collections.Sequence in project pivot by apache.

the class BXMLSerializer method processEndElement.

@SuppressWarnings("unchecked")
private void processEndElement() throws SerializationException {
    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    switch(element.type) {
        case INSTANCE:
        case INCLUDE:
        case REFERENCE:
            {
                // Apply attributes
                for (Attribute attribute : element.attributes) {
                    if (attribute.propertyClass == null) {
                        Dictionary<String, Object> dictionary;
                        if (element.value instanceof Dictionary<?, ?>) {
                            dictionary = (Dictionary<String, Object>) element.value;
                        } else {
                            dictionary = new BeanAdapter(element.value);
                        }
                        dictionary.put(attribute.name, attribute.value);
                    } else {
                        if (attribute.propertyClass.isInterface()) {
                            // The attribute represents an event listener
                            String listenerClassName = attribute.propertyClass.getName();
                            listenerClassName = listenerClassName.substring(listenerClassName.lastIndexOf('.') + 1);
                            String getListenerListMethodName = "get" + Character.toUpperCase(listenerClassName.charAt(0)) + listenerClassName.substring(1) + "s";
                            // Get the listener list
                            Method getListenerListMethod;
                            try {
                                Class<?> type = element.value.getClass();
                                getListenerListMethod = type.getMethod(getListenerListMethodName);
                            } catch (NoSuchMethodException exception) {
                                throw new SerializationException(exception);
                            }
                            Object listenerList;
                            try {
                                listenerList = getListenerListMethod.invoke(element.value);
                            } catch (InvocationTargetException exception) {
                                throw new SerializationException(exception);
                            } catch (IllegalAccessException exception) {
                                throw new SerializationException(exception);
                            }
                            // Create an invocation handler for this listener
                            AttributeInvocationHandler handler = new AttributeInvocationHandler(getEngineByName(language), attribute.name, (String) attribute.value);
                            Object listener = Proxy.newProxyInstance(classLoader, new Class<?>[] { attribute.propertyClass }, handler);
                            // Add the listener
                            Class<?> listenerListClass = listenerList.getClass();
                            Method addMethod;
                            try {
                                addMethod = listenerListClass.getMethod("add", Object.class);
                            } catch (NoSuchMethodException exception) {
                                throw new RuntimeException(exception);
                            }
                            try {
                                addMethod.invoke(listenerList, listener);
                            } catch (IllegalAccessException exception) {
                                throw new SerializationException(exception);
                            } catch (InvocationTargetException exception) {
                                throw new SerializationException(exception);
                            }
                        } else {
                            // The attribute represents a static setter
                            setStaticProperty(element.value, attribute.propertyClass, attribute.name, attribute.value);
                        }
                    }
                }
                if (element.parent != null) {
                    if (element.parent.type == Element.Type.WRITABLE_PROPERTY) {
                        // Set this as the property value; it will be applied
                        // later in the parent's closing tag
                        element.parent.value = element.value;
                    } else if (element.parent.value != null) {
                        // If the parent element has a default property, use it;
                        // otherwise, if the parent is a sequence, add the element to it.
                        Class<?> parentType = element.parent.value.getClass();
                        DefaultProperty defaultProperty = parentType.getAnnotation(DefaultProperty.class);
                        if (defaultProperty == null) {
                            if (element.parent.value instanceof Sequence<?>) {
                                Sequence<Object> sequence = (Sequence<Object>) element.parent.value;
                                sequence.add(element.value);
                            } else {
                                throw new SerializationException(element.parent.value.getClass() + " is not a sequence.");
                            }
                        } else {
                            String defaultPropertyName = defaultProperty.value();
                            BeanAdapter beanAdapter = new BeanAdapter(element.parent.value);
                            Object defaultPropertyValue = beanAdapter.get(defaultPropertyName);
                            if (defaultPropertyValue instanceof Sequence<?>) {
                                Sequence<Object> sequence = (Sequence<Object>) defaultPropertyValue;
                                try {
                                    sequence.add(element.value);
                                } catch (UnsupportedOperationException uoe) {
                                    beanAdapter.put(defaultPropertyName, element.value);
                                }
                            } else {
                                beanAdapter.put(defaultPropertyName, element.value);
                            }
                        }
                    }
                }
                break;
            }
        case READ_ONLY_PROPERTY:
            {
                Dictionary<String, Object> dictionary;
                if (element.value instanceof Dictionary<?, ?>) {
                    dictionary = (Dictionary<String, Object>) element.value;
                } else {
                    dictionary = new BeanAdapter(element.value);
                }
                // Process attributes looking for instance property setters
                for (Attribute attribute : element.attributes) {
                    if (attribute.propertyClass != null) {
                        throw new SerializationException("Static setters are not supported" + " for read-only properties.");
                    }
                    dictionary.put(attribute.name, attribute.value);
                }
                break;
            }
        case WRITABLE_PROPERTY:
            {
                if (element.propertyClass == null) {
                    Dictionary<String, Object> dictionary;
                    if (element.parent.value instanceof Dictionary) {
                        dictionary = (Dictionary<String, Object>) element.parent.value;
                    } else {
                        dictionary = new BeanAdapter(element.parent.value);
                    }
                    dictionary.put(element.name, element.value);
                } else {
                    if (element.parent == null) {
                        throw new SerializationException("Element does not have a parent.");
                    }
                    if (element.parent.value == null) {
                        throw new SerializationException("Parent value is null.");
                    }
                    setStaticProperty(element.parent.value, element.propertyClass, element.name, element.value);
                }
                break;
            }
        case LISTENER_LIST_PROPERTY:
            {
                // Evaluate the script
                String script = (String) element.value;
                // Get a new engine here in order to make the script function private to this object
                ScriptEngine scriptEngine = newEngineByName(language);
                try {
                    scriptEngine.eval(script);
                } catch (ScriptException exception) {
                    reportException(exception, script);
                    break;
                }
                // Create the listener and add it to the list
                BeanAdapter beanAdapter = new BeanAdapter(element.parent.value);
                ListenerList<?> listenerList = (ListenerList<?>) beanAdapter.get(element.name);
                Class<?> listenerListClass = listenerList.getClass();
                java.lang.reflect.Type[] genericInterfaces = listenerListClass.getGenericInterfaces();
                Class<?> listenerClass = (Class<?>) genericInterfaces[0];
                ElementInvocationHandler handler = new ElementInvocationHandler(scriptEngine);
                Method addMethod;
                try {
                    addMethod = listenerListClass.getMethod("add", Object.class);
                } catch (NoSuchMethodException exception) {
                    throw new RuntimeException(exception);
                }
                Object listener = Proxy.newProxyInstance(classLoader, new Class<?>[] { listenerClass }, handler);
                try {
                    addMethod.invoke(listenerList, listener);
                } catch (IllegalAccessException exception) {
                    throw new SerializationException(exception);
                } catch (InvocationTargetException exception) {
                    throw new SerializationException(exception);
                }
                break;
            }
        case SCRIPT:
            {
                String src = null;
                if (element.properties.containsKey(SCRIPT_SRC_ATTRIBUTE)) {
                    src = element.properties.get(SCRIPT_SRC_ATTRIBUTE);
                }
                if (src != null && src.charAt(0) == OBJECT_REFERENCE_PREFIX) {
                    src = src.substring(1);
                    if (src.length() > 0) {
                        if (!JSON.containsKey(namespace, src)) {
                            throw new SerializationException("Value \"" + src + "\" is not defined.");
                        }
                        String variableValue = JSON.get(namespace, src);
                        src = variableValue;
                    }
                }
                if (src != null) {
                    int i = src.lastIndexOf(".");
                    if (i == -1) {
                        throw new SerializationException("Cannot determine type of script \"" + src + "\".");
                    }
                    String extension = src.substring(i + 1);
                    ScriptEngine scriptEngine = getEngineByExtension(extension);
                    scriptEngine.setBindings(scriptEngineManager.getBindings(), ScriptContext.ENGINE_SCOPE);
                    try {
                        URL scriptLocation;
                        if (src.charAt(0) == SLASH_PREFIX) {
                            scriptLocation = classLoader.getResource(src.substring(1));
                            if (scriptLocation == null) {
                                // add a fallback
                                scriptLocation = new URL(location, src.substring(1));
                            }
                        } else {
                            scriptLocation = new URL(location, src);
                        }
                        BufferedReader scriptReader = null;
                        try {
                            scriptReader = new BufferedReader(new InputStreamReader(scriptLocation.openStream()));
                            scriptEngine.eval(NASHORN_COMPAT_SCRIPT);
                            scriptEngine.eval(scriptReader);
                        } catch (ScriptException exception) {
                            reportException(exception);
                        } finally {
                            if (scriptReader != null) {
                                scriptReader.close();
                            }
                        }
                    } catch (IOException exception) {
                        throw new SerializationException(exception);
                    }
                }
                if (element.value != null) {
                    // Evaluate the script
                    String script = (String) element.value;
                    ScriptEngine scriptEngine = getEngineByName(language);
                    scriptEngine.setBindings(scriptEngineManager.getBindings(), ScriptContext.ENGINE_SCOPE);
                    try {
                        scriptEngine.eval(NASHORN_COMPAT_SCRIPT);
                        scriptEngine.eval(script);
                    } catch (ScriptException exception) {
                        reportException(exception, script);
                    }
                }
                break;
            }
        case DEFINE:
            {
                // No-op
                break;
            }
        default:
            {
                break;
            }
    }
    // Move up the stack
    if (element.parent == null) {
        root = element.value;
    }
    element = element.parent;
}
Also used : ListenerList(org.apache.pivot.util.ListenerList) Dictionary(org.apache.pivot.collections.Dictionary) URL(java.net.URL) ScriptException(javax.script.ScriptException) SerializationException(org.apache.pivot.serialization.SerializationException) InputStreamReader(java.io.InputStreamReader) Method(java.lang.reflect.Method) Sequence(org.apache.pivot.collections.Sequence) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ScriptEngine(javax.script.ScriptEngine) BufferedReader(java.io.BufferedReader)

Example 13 with Sequence

use of org.apache.pivot.collections.Sequence in project pivot by apache.

the class TerraVFSBrowserSheetSkin method install.

@Override
public void install(Component component) {
    super.install(component);
    final VFSBrowserSheet fileBrowserSheet = (VFSBrowserSheet) component;
    fileBrowserSheet.setMinimumWidth(360);
    fileBrowserSheet.setMinimumHeight(180);
    // Load the sheet content
    BXMLSerializer bxmlSerializer = new BXMLSerializer();
    Component content;
    try {
        content = (Component) bxmlSerializer.readObject(TerraVFSBrowserSheetSkin.class, "terra_vfs_browser_sheet_skin.bxml", true);
    } catch (IOException exception) {
        throw new RuntimeException(exception);
    } catch (SerializationException exception) {
        throw new RuntimeException(exception);
    }
    fileBrowserSheet.setContent(content);
    bxmlSerializer.bind(this, TerraVFSBrowserSheetSkin.class);
    // set the same rootDirectory as the component
    try {
        FileObject rootDirectory = fileBrowserSheet.getRootDirectory();
        fileBrowser.setRootDirectory(rootDirectory);
        setHostLabel(rootDirectory);
    } catch (FileSystemException fse) {
        throw new RuntimeException(fse);
    }
    // set the same homeDirectory as the component
    try {
        fileBrowser.setHomeDirectory(fileBrowserSheet.getHomeDirectory());
    } catch (FileSystemException fse) {
        throw new RuntimeException(fse);
    }
    saveAsTextInput.getTextInputContentListeners().add(new TextInputContentListener() {

        @Override
        public void textChanged(TextInput textInput) {
            Form.clearFlag(saveAsBoxPane);
            updateOKButtonState();
        }
    });
    fileBrowser.getFileBrowserListeners().add(new VFSBrowserListener() {

        @Override
        public void rootDirectoryChanged(VFSBrowser fileBrowserArgument, FileObject previousRootDirectory) {
            updatingSelection = true;
            try {
                FileObject rootDirectory = fileBrowserArgument.getRootDirectory();
                fileBrowserSheet.setRootDirectory(rootDirectory);
                setHostLabel(rootDirectory);
            } catch (FileSystemException fse) {
                throw new RuntimeException(fse);
            }
            updatingSelection = false;
            selectedDirectoryCount = 0;
            updateOKButtonState();
        }

        @Override
        public void homeDirectoryChanged(VFSBrowser fileBrowserArgument, FileObject previousHomeDirectory) {
            updatingSelection = true;
            try {
                fileBrowserSheet.setHomeDirectory(fileBrowserArgument.getHomeDirectory());
            } catch (FileSystemException fse) {
                throw new RuntimeException(fse);
            }
            updatingSelection = false;
        }

        @Override
        public void selectedFileAdded(VFSBrowser fileBrowserArgument, FileObject file) {
            if (file.getName().getType() == FileType.FOLDER) {
                selectedDirectoryCount++;
            }
            updateOKButtonState();
        }

        @Override
        public void selectedFileRemoved(VFSBrowser fileBrowserArgument, FileObject file) {
            if (file.getName().getType() == FileType.FOLDER) {
                selectedDirectoryCount--;
            }
            updateOKButtonState();
        }

        @Override
        public void selectedFilesChanged(VFSBrowser fileBrowserArgument, Sequence<FileObject> previousSelectedFiles) {
            selectedDirectoryCount = 0;
            Sequence<FileObject> selectedFiles = fileBrowserArgument.getSelectedFiles();
            for (int i = 0, n = selectedFiles.getLength(); i < n; i++) {
                FileObject selectedFile = selectedFiles.get(i);
                if (selectedFile.getName().getType() == FileType.FOLDER) {
                    selectedDirectoryCount++;
                }
            }
            if (!fileBrowserArgument.isMultiSelect()) {
                FileObject selectedFile = fileBrowserArgument.getSelectedFile();
                if (selectedFile != null && selectedFile.getName().getType() != FileType.FOLDER) {
                    saveAsTextInput.setText(selectedFile.getName().getPath());
                }
            }
            updateOKButtonState();
        }
    });
    fileBrowser.getComponentMouseButtonListeners().add(new ComponentMouseButtonListener() {

        private FileObject file = null;

        @Override
        public boolean mouseClick(Component componentArgument, Mouse.Button button, int x, int y, int count) {
            boolean consumed = false;
            VFSBrowserSheet.Mode mode = fileBrowserSheet.getMode();
            if (count == 1) {
                file = fileBrowser.getFileAt(x, y);
            } else if (count == 2) {
                FileObject fileLocal = fileBrowser.getFileAt(x, y);
                if (fileLocal != null && this.file != null && fileLocal.equals(this.file) && fileBrowser.isFileSelected(fileLocal)) {
                    if (mode == VFSBrowserSheet.Mode.OPEN || mode == VFSBrowserSheet.Mode.OPEN_MULTIPLE) {
                        if (fileLocal.getName().getType() != FileType.FOLDER) {
                            fileBrowserSheet.close(true);
                            consumed = true;
                        }
                    }
                }
            }
            return consumed;
        }
    });
    okButton.getButtonPressListeners().add(new ButtonPressListener() {

        @Override
        public void buttonPressed(Button button) {
            fileBrowserSheet.close(true);
        }
    });
    cancelButton.getButtonPressListeners().add(new ButtonPressListener() {

        @Override
        public void buttonPressed(Button button) {
            fileBrowserSheet.close(false);
        }
    });
    // Add this as a file browser sheet listener
    fileBrowserSheet.getFileBrowserSheetListeners().add(this);
    modeChanged(fileBrowserSheet, null);
    homeDirectoryChanged(fileBrowserSheet, null);
    rootDirectoryChanged(fileBrowserSheet, null);
    selectedFilesChanged(fileBrowserSheet, null);
}
Also used : SerializationException(org.apache.pivot.serialization.SerializationException) VFSBrowserListener(org.apache.pivot.wtk.VFSBrowserListener) IOException(java.io.IOException) Sequence(org.apache.pivot.collections.Sequence) ButtonPressListener(org.apache.pivot.wtk.ButtonPressListener) FileSystemException(org.apache.commons.vfs2.FileSystemException) TextInputContentListener(org.apache.pivot.wtk.TextInputContentListener) VFSBrowserSheet(org.apache.pivot.wtk.VFSBrowserSheet) Mouse(org.apache.pivot.wtk.Mouse) PushButton(org.apache.pivot.wtk.PushButton) Button(org.apache.pivot.wtk.Button) ComponentMouseButtonListener(org.apache.pivot.wtk.ComponentMouseButtonListener) FileObject(org.apache.commons.vfs2.FileObject) Component(org.apache.pivot.wtk.Component) TextInput(org.apache.pivot.wtk.TextInput) BXMLSerializer(org.apache.pivot.beans.BXMLSerializer) VFSBrowser(org.apache.pivot.wtk.VFSBrowser)

Example 14 with Sequence

use of org.apache.pivot.collections.Sequence in project pivot by apache.

the class TerraVFSBrowserSkin method install.

@Override
public void install(Component component) {
    super.install(component);
    final VFSBrowser fileBrowser = (VFSBrowser) component;
    BXMLSerializer bxmlSerializer = new BXMLSerializer();
    try {
        content = (Component) bxmlSerializer.readObject(TerraVFSBrowserSkin.class, "terra_vfs_browser_skin.bxml", true);
    } catch (IOException exception) {
        throw new RuntimeException(exception);
    } catch (SerializationException exception) {
        throw new RuntimeException(exception);
    }
    fileBrowser.add(content);
    bxmlSerializer.bind(this, TerraVFSBrowserSkin.class);
    // Notify all the renderers of which component they are dealing with
    ((FileRenderer) pathListButton.getDataRenderer()).setFileBrowser(fileBrowser);
    ((FileRenderer) pathListButton.getItemRenderer()).setFileBrowser(fileBrowser);
    for (TableView.Column col : fileTableView.getColumns()) {
        ((FileRenderer) col.getCellRenderer()).setFileBrowser(fileBrowser);
    }
    homeDirectory = fileBrowser.getHomeDirectory();
    driveListButton.getListButtonSelectionListeners().add(new ListButtonSelectionListener() {

        @Override
        public void selectedItemChanged(ListButton listButton, Object previousSelectedItem) {
            if (previousSelectedItem != null) {
                FileObject drive = (FileObject) listButton.getSelectedItem();
                try {
                    if (drive.isReadable()) {
                        fileBrowser.setRootDirectory(drive);
                    } else {
                        refreshRoots = true;
                        listButton.setSelectedItem(previousSelectedItem);
                    }
                } catch (FileSystemException fse) {
                    throw new RuntimeException(fse);
                }
            }
        }
    });
    pathListButton.getListButtonSelectionListeners().add(new ListButtonSelectionListener() {

        @Override
        public void selectedItemChanged(ListButton listButton, Object previousSelectedItem) {
            FileObject ancestorDirectory = (FileObject) listButton.getSelectedItem();
            if (ancestorDirectory != null) {
                try {
                    fileBrowser.setRootDirectory(ancestorDirectory);
                } catch (FileSystemException fse) {
                    throw new RuntimeException(fse);
                }
            }
        }
    });
    goUpButton.getButtonPressListeners().add(new ButtonPressListener() {

        @Override
        public void buttonPressed(Button button) {
            try {
                FileObject rootDirectory = fileBrowser.getRootDirectory();
                FileObject parentDirectory = rootDirectory.getParent();
                fileBrowser.setRootDirectory(parentDirectory);
            } catch (FileSystemException fse) {
                throw new RuntimeException(fse);
            }
        }
    });
    newFolderButton.getButtonPressListeners().add(new ButtonPressListener() {

        @Override
        public void buttonPressed(Button button) {
        // TODO
        }
    });
    goHomeButton.getButtonPressListeners().add(new ButtonPressListener() {

        @Override
        public void buttonPressed(Button button) {
            try {
                fileBrowser.setRootDirectory(fileBrowser.getHomeDirectory());
            } catch (FileSystemException fse) {
                throw new RuntimeException(fse);
            }
        }
    });
    /**
     * {@link KeyCode#DOWN DOWN} Transfer focus to the file list and select
     * the first item.<br> {@link KeyCode#ESCAPE ESCAPE} Clear the search
     * field.
     */
    searchTextInput.getComponentKeyListeners().add(new ComponentKeyListener() {

        @Override
        public boolean keyPressed(Component componentArgument, int keyCode, Keyboard.KeyLocation keyLocation) {
            boolean consumed = false;
            if (keyCode == Keyboard.KeyCode.ESCAPE) {
                searchTextInput.setText("");
                consumed = true;
            } else if (keyCode == Keyboard.KeyCode.DOWN) {
                if (fileTableView.getTableData().getLength() > 0) {
                    fileTableView.setSelectedIndex(0);
                    fileTableView.requestFocus();
                }
            }
            return consumed;
        }
    });
    searchTextInput.getTextInputContentListeners().add(new TextInputContentListener() {

        @Override
        public void textChanged(TextInput textInput) {
            refreshFileList();
        }
    });
    fileTableView.getTableViewSelectionListeners().add(new TableViewSelectionListener() {

        @Override
        public void selectedRangeAdded(TableView tableView, int rangeStart, int rangeEnd) {
            if (!updatingSelection) {
                updatingSelection = true;
                try {
                    for (int i = rangeStart; i <= rangeEnd; i++) {
                        @SuppressWarnings("unchecked") List<FileObject> files = (List<FileObject>) fileTableView.getTableData();
                        FileObject file = files.get(i);
                        fileBrowser.addSelectedFile(file);
                    }
                } catch (FileSystemException fse) {
                    throw new RuntimeException(fse);
                }
                updatingSelection = false;
            }
        }

        @Override
        public void selectedRangeRemoved(TableView tableView, int rangeStart, int rangeEnd) {
            if (!updatingSelection) {
                updatingSelection = true;
                for (int i = rangeStart; i <= rangeEnd; i++) {
                    @SuppressWarnings("unchecked") List<FileObject> files = (List<FileObject>) fileTableView.getTableData();
                    FileObject file = files.get(i);
                    fileBrowser.removeSelectedFile(file);
                }
                updatingSelection = false;
            }
        }

        @Override
        public void selectedRangesChanged(TableView tableView, Sequence<Span> previousSelectedRanges) {
            if (!updatingSelection && previousSelectedRanges != null) {
                updatingSelection = true;
                @SuppressWarnings("unchecked") Sequence<FileObject> files = (Sequence<FileObject>) tableView.getSelectedRows();
                for (int i = 0, n = files.getLength(); i < n; i++) {
                    FileObject file = files.get(i);
                    files.update(i, file);
                }
                try {
                    fileBrowser.setSelectedFiles(files);
                } catch (FileSystemException fse) {
                    throw new RuntimeException(fse);
                }
                updatingSelection = false;
            }
        }

        @Override
        public void selectedRowChanged(TableView tableView, Object previousSelectedRow) {
        // No-op
        }
    });
    fileTableView.getTableViewSortListeners().add(new TableViewSortListener() {

        @Override
        public void sortChanged(TableView tableView) {
            TableView.SortDictionary sort = fileTableView.getSort();
            if (!sort.isEmpty()) {
                Dictionary.Pair<String, SortDirection> pair = fileTableView.getSort().get(0);
                @SuppressWarnings("unchecked") List<FileObject> files = (List<FileObject>) fileTableView.getTableData();
                files.setComparator(getFileComparator(pair.key, pair.value));
            }
        }
    });
    fileTableView.getComponentMouseButtonListeners().add(new ComponentMouseButtonListener() {

        private int index = -1;

        @Override
        public boolean mouseClick(Component componentArgument, Mouse.Button button, int x, int y, int count) {
            boolean consumed = false;
            if (count == 1) {
                index = fileTableView.getRowAt(y);
            } else if (count == 2) {
                int indexLocal = fileTableView.getRowAt(y);
                if (indexLocal != -1 && indexLocal == this.index && fileTableView.isRowSelected(indexLocal)) {
                    FileObject file = (FileObject) fileTableView.getTableData().get(indexLocal);
                    try {
                        if (file.getName().getType() == FileType.FOLDER) {
                            fileBrowser.setRootDirectory(file);
                            consumed = true;
                        }
                    } catch (FileSystemException fse) {
                        throw new RuntimeException(fse);
                    }
                }
            }
            return consumed;
        }
    });
    fileBrowser.setFocusTraversalPolicy(new IndexFocusTraversalPolicy() {

        @Override
        public Component getNextComponent(Container container, Component componentArgument, FocusTraversalDirection direction) {
            Component nextComponent;
            if (componentArgument == null) {
                nextComponent = fileTableView;
            } else {
                nextComponent = super.getNextComponent(container, componentArgument, direction);
            }
            return nextComponent;
        }
    });
    fileTableView.setSort(TableViewFileRenderer.NAME_KEY, SortDirection.ASCENDING);
    fileTableView.getComponentTooltipListeners().add(new ComponentTooltipListener() {

        @Override
        public void tooltipTriggered(Component comp, int x, int y) {
            // Check that we are on the first column.
            if (fileTableView.getColumnAt(x) != 0) {
                return;
            }
            // Gets the underlying file
            int row = fileTableView.getRowAt(y);
            if (row < 0) {
                return;
            }
            FileObject file = (FileObject) fileTableView.getTableData().get(row);
            // Construct and show the tooltip.
            final Tooltip tooltip = new Tooltip();
            String text = null;
            if (file != null) {
                text = file.getName().getBaseName();
            }
            if (text == null || text.isEmpty()) {
                return;
            }
            TextArea toolTipTextArea = new TextArea();
            toolTipTextArea.setText(text);
            toolTipTextArea.getStyles().put(Style.wrapText, true);
            toolTipTextArea.getStyles().put(Style.backgroundColor, null);
            tooltip.setContent(toolTipTextArea);
            Point location = comp.getDisplay().getMouseLocation();
            x = location.x;
            y = location.y;
            // Ensure that the tooltip stays on screen
            Display display = comp.getDisplay();
            int tooltipHeight = tooltip.getPreferredHeight();
            if (y + tooltipHeight > display.getHeight()) {
                y -= tooltipHeight;
            }
            int tooltipXOffset = 16;
            int padding = 15;
            toolTipTextArea.setMaximumWidth(display.getWidth() - (x + tooltipXOffset + padding));
            tooltip.setLocation(x + tooltipXOffset, y);
            tooltip.open(comp.getWindow());
        }
    });
    rootDirectoryChanged(fileBrowser, null);
    selectedFilesChanged(fileBrowser, null);
}
Also used : FocusTraversalDirection(org.apache.pivot.wtk.FocusTraversalDirection) ComponentTooltipListener(org.apache.pivot.wtk.ComponentTooltipListener) TextArea(org.apache.pivot.wtk.TextArea) ListButtonSelectionListener(org.apache.pivot.wtk.ListButtonSelectionListener) TableViewSortListener(org.apache.pivot.wtk.TableViewSortListener) Span(org.apache.pivot.wtk.Span) ButtonPressListener(org.apache.pivot.wtk.ButtonPressListener) FileSystemException(org.apache.commons.vfs2.FileSystemException) TextInputContentListener(org.apache.pivot.wtk.TextInputContentListener) Container(org.apache.pivot.wtk.Container) PushButton(org.apache.pivot.wtk.PushButton) ListButton(org.apache.pivot.wtk.ListButton) Button(org.apache.pivot.wtk.Button) ArrayList(org.apache.pivot.collections.ArrayList) List(org.apache.pivot.collections.List) FileObject(org.apache.commons.vfs2.FileObject) Component(org.apache.pivot.wtk.Component) TextInput(org.apache.pivot.wtk.TextInput) TableViewSelectionListener(org.apache.pivot.wtk.TableViewSelectionListener) VFSBrowser(org.apache.pivot.wtk.VFSBrowser) BXMLSerializer(org.apache.pivot.beans.BXMLSerializer) TableView(org.apache.pivot.wtk.TableView) SerializationException(org.apache.pivot.serialization.SerializationException) Keyboard(org.apache.pivot.wtk.Keyboard) Tooltip(org.apache.pivot.wtk.Tooltip) IOException(java.io.IOException) Sequence(org.apache.pivot.collections.Sequence) Point(org.apache.pivot.wtk.Point) Point(org.apache.pivot.wtk.Point) ListButton(org.apache.pivot.wtk.ListButton) ComponentKeyListener(org.apache.pivot.wtk.ComponentKeyListener) Mouse(org.apache.pivot.wtk.Mouse) FileObject(org.apache.commons.vfs2.FileObject) ComponentMouseButtonListener(org.apache.pivot.wtk.ComponentMouseButtonListener) Display(org.apache.pivot.wtk.Display)

Aggregations

Sequence (org.apache.pivot.collections.Sequence)14 Component (org.apache.pivot.wtk.Component)7 IOException (java.io.IOException)6 Button (org.apache.pivot.wtk.Button)6 ButtonPressListener (org.apache.pivot.wtk.ButtonPressListener)6 BXMLSerializer (org.apache.pivot.beans.BXMLSerializer)5 Dictionary (org.apache.pivot.collections.Dictionary)5 SerializationException (org.apache.pivot.serialization.SerializationException)5 PushButton (org.apache.pivot.wtk.PushButton)5 Span (org.apache.pivot.wtk.Span)5 BeanAdapter (org.apache.pivot.beans.BeanAdapter)4 ComponentKeyListener (org.apache.pivot.wtk.ComponentKeyListener)4 ComponentMouseButtonListener (org.apache.pivot.wtk.ComponentMouseButtonListener)4 Keyboard (org.apache.pivot.wtk.Keyboard)4 Mouse (org.apache.pivot.wtk.Mouse)4 TextInput (org.apache.pivot.wtk.TextInput)4 TextInputContentListener (org.apache.pivot.wtk.TextInputContentListener)4 File (java.io.File)3 List (org.apache.pivot.collections.List)3 Map (org.apache.pivot.collections.Map)3