file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
VerticalScrollablePanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/loading/VerticalScrollablePanel.java | package org.esa.snap.ui.loading;
import java.awt.Rectangle;
import javax.swing.Scrollable;
import javax.swing.SwingConstants;
import javax.swing.JPanel;
import java.awt.LayoutManager;
import java.awt.Dimension;
/**
* Created by jcoravu on 23/9/2019.
*/
public class VerticalScrollablePanel extends JPanel implements Scrollable {
private final int maximumUnitIncrement;
public VerticalScrollablePanel(LayoutManager layoutManager) {
super(layoutManager);
this.maximumUnitIncrement = 10;
}
@Override
public Dimension getPreferredScrollableViewportSize() {
return getPreferredSize();
}
@Override
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
int currentPosition = 0;
if (orientation == SwingConstants.HORIZONTAL) {
currentPosition = visibleRect.x;
} else {
currentPosition = visibleRect.y;
}
if (direction < 0) {
int newPosition = currentPosition - (currentPosition / this.maximumUnitIncrement) * this.maximumUnitIncrement;
return (newPosition == 0) ? this.maximumUnitIncrement : newPosition;
}
return ((currentPosition / this.maximumUnitIncrement) + 1) * this.maximumUnitIncrement - currentPosition;
}
@Override
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
if (orientation == SwingConstants.HORIZONTAL) {
return visibleRect.width - this.maximumUnitIncrement;
}
return visibleRect.height - this.maximumUnitIncrement;
}
@Override
public boolean getScrollableTracksViewportWidth() {
return true;
}
@Override
public boolean getScrollableTracksViewportHeight() {
return false;
}
}
| 1,837 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
GenericRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/loading/GenericRunnable.java | package org.esa.snap.ui.loading;
/**
* Created by jcoravu on 29/3/2019.
*/
public abstract class GenericRunnable<ItemType> implements Runnable {
private final ItemType item;
public GenericRunnable(ItemType item) {
this.item = item;
}
protected abstract void execute(ItemType item);
@Override
public void run() {
execute(this.item);
}
}
| 387 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ComponentsEnabled.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/loading/ComponentsEnabled.java | package org.esa.snap.ui.loading;
/**
* Created by jcoravu on 28/12/2018.
*/
public interface ComponentsEnabled {
public void setComponentsEnabled(boolean enabled);
}
| 174 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LoadingIndicatorPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/loading/LoadingIndicatorPanel.java | package org.esa.snap.ui.loading;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import java.awt.*;
/**
* Created by jcoravu on 28/12/2018.
*/
public class LoadingIndicatorPanel extends JPanel implements LoadingIndicator {
private final Object lockObject;
private final ComponentsEnabled componentsEnabled;
private final CircularProgressIndicatorLabel circularProgressLabel;
private final JLabel messageLabel;
private boolean isRunning;
private int currentThreadId;
public LoadingIndicatorPanel() {
this(null);
}
public LoadingIndicatorPanel(ComponentsEnabled componentsEnabled) {
super(new GridBagLayout());
this.componentsEnabled = componentsEnabled;
this.circularProgressLabel = new CircularProgressIndicatorLabel();
GridBagConstraints c = SwingUtils.buildConstraints(0, 0, GridBagConstraints.NONE, GridBagConstraints.CENTER, 1, 1, new Insets(1, 1, 1, 1));
add(this.circularProgressLabel, c);
this.messageLabel = new JLabel();
c = SwingUtils.buildConstraints(0, 1, GridBagConstraints.NONE, GridBagConstraints.CENTER, 1, 1, new Insets(1, 3, 1, 3));
add(this.messageLabel, c);
super.setBorder(new LineBorder(Color.gray, 1, false));
super.setOpaque(true); // the loading indicator panel is not transparent
stopAndHide();
this.isRunning = false;
this.lockObject = new Object();
this.currentThreadId = 0;
}
@Override
public final void setOpaque(boolean aIsOpaque) {
// do nothing
}
@Override
public final void setBorder(Border aBorder) {
// do nothing
}
@Override
public final void removeNotify() {
setRunningAndIncreaseThreadId(false);
super.removeNotify();
}
@Override
public final Color getBackground() {
return Color.white;
}
@Override
public final boolean isRunning(int threadId) {
synchronized (this.lockObject) {
return this.isRunning && (this.currentThreadId == threadId);
}
}
@Override
public final boolean onDisplay(int threadId, String messageToDisplay) {
if (isRunning(threadId)) {
try {
setEnabledControls(false);
} finally {
showAndStart(threadId, messageToDisplay);
}
return true;
}
return false;
}
@Override
public boolean onHide(int threadId) {
if (isRunning(threadId)) {
stopRunningAndHide();
return true;
}
return false;
}
public final int getNewCurrentThreadId() {
return setRunningAndIncreaseThreadId(true);
}
public void stopRunningAndHide() {
setRunningAndIncreaseThreadId(false);
try {
setEnabledControls(true);
} finally {
stopAndHide();
}
}
private void showAndStart(int threadId, String messageToDisplay) {
boolean visibleMessage = (messageToDisplay != null && messageToDisplay.trim().length() > 0);
this.messageLabel.setText(messageToDisplay);
this.messageLabel.setVisible(visibleMessage);
Runnable action = new IntRunnable(threadId) {
@Override
protected void run(int inputThreadId) {
if (isRunning(inputThreadId)) {
circularProgressLabel.setRunning(true);
setVisible(true);
}
}
};
SwingUtilities.invokeLater(action);
}
private int setRunningAndIncreaseThreadId(boolean value) {
synchronized (this.lockObject) {
this.isRunning = value;
return ++this.currentThreadId;
}
}
private void stopAndHide() {
this.circularProgressLabel.setRunning(false);
setVisible(false);
}
private void setEnabledControls(boolean enabled) {
if (this.componentsEnabled != null) {
this.componentsEnabled.setComponentsEnabled(enabled);
}
}
private static abstract class IntRunnable implements Runnable {
private final int value;
IntRunnable(int value) {
this.value = value;
}
protected abstract void run(int value);
@Override
public void run() {
run(this.value);
}
}
}
| 4,454 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CustomFileChooser.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/loading/CustomFileChooser.java | package org.esa.snap.ui.loading;
import org.apache.commons.lang3.StringUtils;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.UIManager;
import javax.swing.filechooser.FileFilter;
import javax.swing.text.JTextComponent;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* Created by jcoravu on 11/1/2019.
*/
public class CustomFileChooser extends JFileChooser {
public static final String FILE_CHOOSER_READ_ONLY_KEY = "FileChooser.readOnly";
private final boolean previousReadOnlyFlag;
private final PropertyChangeListener propertyChangeListener;
private JTextComponent textField;
public CustomFileChooser(boolean previousReadOnlyFlag) {
super();
this.previousReadOnlyFlag = previousReadOnlyFlag;
this.propertyChangeListener = event -> {
if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equalsIgnoreCase(event.getPropertyName())) {
if (getFileSelectionMode() == JFileChooser.FILES_ONLY) {
resetSelectedFile();
}
} else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equalsIgnoreCase(event.getPropertyName())
|| JFileChooser.SELECTED_FILES_CHANGED_PROPERTY.equalsIgnoreCase(event.getPropertyName())) {
if (getFileSelectionMode() == JFileChooser.FILES_ONLY && event.getNewValue() == null) {
resetSelectedFile();
}
}
};
}
private static List<JComboBox<?>> findComboBoxes(Container root) {
List<JComboBox<?>> comboBoxes = new ArrayList<>();
Stack<Container> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
Container container = stack.pop();
Component[] components = container.getComponents();
for (Component component : components) {
if (component instanceof JComboBox<?>) {
comboBoxes.add((JComboBox<?>) component);
} else if (component instanceof Container) {
stack.push((Container) component);
}
}
}
return comboBoxes;
}
@Override
public int showDialog(Component parent, String approveButtonText) throws HeadlessException {
int returnCode = super.showDialog(parent, approveButtonText);
UIManager.getDefaults().put(FILE_CHOOSER_READ_ONLY_KEY, this.previousReadOnlyFlag);
return returnCode;
}
public Path getSelectedPath() {
File file = super.getSelectedFile();
return Paths.get(file.toURI());
}
public void setCurrentDirectoryPath(Path directoryPath) {
super.setCurrentDirectory(directoryPath.toFile());
}
public void setSelectedPath(Path path) {
super.setSelectedFile(path.toFile());
}
private void resetSelectedFile() {
removePropertyChangeListener(this.propertyChangeListener);
try {
setSelectedFile(null);
setSelectedFiles(null);
if (this.textField != null) {
this.textField.setText("");
}
} finally {
addPropertyChangeListener(this.propertyChangeListener);
}
}
private static JTextComponent findTextField(Container root) {
Component[] components = root.getComponents();
for (Component component : components) {
if (component instanceof JTextComponent) {
return (JTextComponent) component;
}
if (component instanceof Container) {
JTextComponent filePane = findTextField((Container) component);
if (filePane != null) {
return filePane;
}
}
}
return null;
}
@Override
protected JDialog createDialog(Component parent) throws HeadlessException {
JDialog dialog = super.createDialog(parent);
dialog.setMinimumSize(new Dimension(450, 350));
addPropertyChangeListener(this.propertyChangeListener);
this.textField = findTextField(this);
List<JComboBox<?>> comboBoxes = findComboBoxes(this);
if (this.textField != null && comboBoxes.size() > 0) {
Dimension preferredTextFieldSize = this.textField.getPreferredSize();
int maximumHeight = preferredTextFieldSize.height;
for (JComboBox<?> box : comboBoxes) {
Dimension preferredComboBoxSize = box.getPreferredSize();
maximumHeight = Math.max(maximumHeight, preferredComboBoxSize.height);
}
preferredTextFieldSize.height = maximumHeight;
this.textField.setPreferredSize(preferredTextFieldSize);
for (JComboBox<?> comboBox : comboBoxes) {
Dimension preferredComboBoxSize = comboBox.getPreferredSize();
preferredComboBoxSize.height = maximumHeight;
comboBox.setPreferredSize(preferredComboBoxSize);
}
}
return dialog;
}
public static FileFilter buildFileFilter(String extension, String description) {
return new CustomFileFilter(extension, description);
}
public static CustomFileChooser buildFileChooser(String dialogTitle, boolean multiSelectionEnabled, int fileSelectionMode) {
return buildFileChooser(dialogTitle, multiSelectionEnabled, fileSelectionMode, true);
}
public static CustomFileChooser buildFileChooser(String dialogTitle, boolean multiSelectionEnabled, int fileSelectionMode, boolean readOnly) {
boolean previousReadOnlyFlag = UIManager.getDefaults().getBoolean(CustomFileChooser.FILE_CHOOSER_READ_ONLY_KEY);
UIManager.getDefaults().put(CustomFileChooser.FILE_CHOOSER_READ_ONLY_KEY, readOnly);
CustomFileChooser fileChooser = new CustomFileChooser(previousReadOnlyFlag);
fileChooser.setDialogTitle(dialogTitle);
fileChooser.setMultiSelectionEnabled(multiSelectionEnabled);
fileChooser.setFileSelectionMode(fileSelectionMode);
return fileChooser;
}
private static class CustomFileFilter extends FileFilter {
private final String extension;
private final String description;
private CustomFileFilter(String extension, String description) {
if (StringUtils.isBlank(extension)) {
throw new NullPointerException("The extension is null or empty.");
}
if (StringUtils.isBlank(description)) {
throw new NullPointerException("The description is null or empty.");
}
this.extension = extension;
this.description = description;
}
@Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
}
return StringUtils.endsWithIgnoreCase(file.getName(), this.extension);
}
@Override
public String getDescription() {
return this.description;
}
}
}
| 7,370 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LoadingIndicator.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/loading/LoadingIndicator.java | package org.esa.snap.ui.loading;
/**
* Created by jcoravu on 31/12/2018.
*/
public interface LoadingIndicator {
public boolean isRunning(int threadId);
public boolean onDisplay(int threadId, String messageToDisplay);
public boolean onHide(int threadId);
}
| 274 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractModalDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/loading/AbstractModalDialog.java | package org.esa.snap.ui.loading;
import org.esa.snap.ui.AbstractDialog;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import javax.swing.WindowConstants;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Stack;
/**
* Created by jcoravu on 18/12/2018.
*/
public abstract class AbstractModalDialog extends AbstractDialog implements MessageDialog {
private LoadingIndicatorPanel loadingIndicatorPanel;
private java.util.List<JComponent> componentsAllwaysEnabled;
protected AbstractModalDialog(Window parent, String title, boolean isModal, String helpID) {
super(new JDialogExtended(parent, Dialog.ModalityType.MODELESS), 0, null, helpID);
JDialogExtended dialog = (JDialogExtended)getJDialog();
dialog.setTitle(title);
dialog.setModal(isModal);
dialog.setLayoutRunnable(new Runnable() {
@Override
public void run() {
centerLoadingIndicatorPanel();
}
});
}
protected abstract JPanel buildContentPanel(int gapBetweenColumns, int gapBetweenRows);
protected abstract JPanel buildButtonsPanel(ActionListener cancelActionListener);
@Override
public void close() {
getJDialog().dispose();
}
@Override
public final int show() {
JDialog dialog = getJDialog();
if (!dialog.isShowing()) {
this.componentsAllwaysEnabled = new ArrayList<JComponent>();
ActionListener cancelActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
close();
}
};
registerEscapeKey(cancelActionListener);
ComponentsEnabled componentsEnabled = new ComponentsEnabled() {
@Override
public void setComponentsEnabled(boolean enabled) {
setEnabledComponentsWhileLoading(enabled);
}
};
this.loadingIndicatorPanel = new LoadingIndicatorPanel(componentsEnabled);
dialog.getLayeredPane().add(this.loadingIndicatorPanel, JLayeredPane.MODAL_LAYER);
int gapBetweenColumns = getDefaultGapBetweenColumns();
int gapBetweenRows = getDefaultGapBetweenRows();
JPanel contentPanel = buildContentPanel(gapBetweenColumns, gapBetweenRows);
JPanel buttonsPanel = buildButtonsPanel(cancelActionListener);
JPanel dialogContentPanel = new JPanel(new BorderLayout(0, getDefaultGapBetweenContentAndButtonPanels()));
dialogContentPanel.add(contentPanel, BorderLayout.CENTER);
dialogContentPanel.add(buttonsPanel, BorderLayout.SOUTH);
Border dialogBorder = buildDialogBorder(getDefaultContentPanelMargins());
dialogContentPanel.setBorder(dialogBorder);
dialog.setContentPane(dialogContentPanel);
dialog.setResizable(true);
dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
dialog.setUndecorated(false);
dialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent aEvent) {
close();
}
});
dialog.pack();
dialog.setLocationRelativeTo(dialog.getParent());
onAboutToShow();
dialog.setVisible(true);
}
return 0;
}
protected int getDefaultGapBetweenContentAndButtonPanels() {
return 7;
}
protected int getDefaultContentPanelMargins() {
return 7;
}
protected int getDefaultGapBetweenRows() {
return 5;
}
protected int getDefaultGapBetweenColumns() {
return 5;
}
protected final Insets buildDefaultTextFieldMargins() {
return new Insets(3, 2, 3, 2);
}
protected final Insets buildDefaultListItemMargins() {
return new Insets(3, 2, 3, 2);
}
protected final void addComponentToAllwaysEnabledList(JComponent component) {
this.componentsAllwaysEnabled.add(component);
}
protected final JPanel buildButtonsPanel(String finishButtonText, ActionListener finishActionListener, String cancelButtonText, ActionListener cancelActionListener) {
JButton finishButton = buildDialogButton(finishButtonText);
finishButton.addActionListener(finishActionListener);
JButton cancelButton = buildDialogButton(cancelButtonText);
cancelButton.addActionListener(cancelActionListener);
this.componentsAllwaysEnabled.add(cancelButton);
JPanel buttonsGridPanel = new JPanel(new GridLayout(1, 2, 5, 0));
buttonsGridPanel.add(finishButton);
buttonsGridPanel.add(cancelButton);
JPanel buttonsPanel = new JPanel(new BorderLayout());
buttonsPanel.add(buttonsGridPanel, BorderLayout.EAST);
return buttonsPanel;
}
protected void setEnabledComponentsWhileLoading(boolean enabled) {
JDialog dialog = getJDialog();
JPanel dialogContentPanel = (JPanel)dialog.getContentPane();
Stack<JComponent> stack = new Stack<JComponent>();
stack.push(dialogContentPanel);
while (!stack.isEmpty()) {
JComponent component = stack.pop();
component.setEnabled(enabled);
int childrenCount = component.getComponentCount();
for (int i=0; i<childrenCount; i++) {
Component child = component.getComponent(i);
if (child instanceof JComponent) {
JComponent childComponent = (JComponent) child;
boolean found = false;
for (int k=0; k<this.componentsAllwaysEnabled.size(); k++) {
if (childComponent == this.componentsAllwaysEnabled.get(k)) {
found = true;
}
}
if (!found) {
// add the component in the stack to be enabled/disabled
stack.push(childComponent);
}
}
}
}
}
protected final LoadingIndicator getLoadingIndicator() {
return this.loadingIndicatorPanel;
}
protected final int getNewCurrentThreadId() {
return this.loadingIndicatorPanel.getNewCurrentThreadId();
}
protected void onAboutToShow() {
}
protected Border buildDialogBorder(int margins) {
return new EmptyBorder(margins, margins, margins, margins);
}
protected void registerEscapeKey(ActionListener cancelActionListener) {
JRootPane rootPane = getJDialog().getRootPane();
KeyStroke escapeKey = getEscapeKeyPressed();
rootPane.registerKeyboardAction(cancelActionListener, escapeKey, JComponent.WHEN_IN_FOCUSED_WINDOW);
}
private KeyStroke getEscapeKeyPressed() {
int noModifiers = 0;
return KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, noModifiers, false); // 'false' => when <Escape> key is pressed
}
private void centerLoadingIndicatorPanel() {
JDialog dialog = getJDialog();
Rectangle layeredPaneBounds = dialog.getLayeredPane().getBounds();
Dimension size = this.loadingIndicatorPanel.getPreferredSize();
int x = layeredPaneBounds.width / 2 - size.width / 2;
int y = layeredPaneBounds.height / 2 - size.height / 2;
this.loadingIndicatorPanel.setBounds(x, y, size.width, size.height);
}
protected final JButton buildDialogButton(String buttonText) {
JButton button = new JButton(buttonText);
button.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent event) {
getJDialog().requestFocusInWindow();
}
});
Dimension size = button.getPreferredSize();
size.width = 75;
button.setPreferredSize(size);
return button;
}
protected static void computePanelFirstColumn(JPanel contentPanel) {
int rootPanelComponentCount = contentPanel.getComponentCount();
int maximumLabelWidth = 0;
for (int i=0; i<rootPanelComponentCount; i++) {
Component component = contentPanel.getComponent(i);
if (component instanceof JPanel) {
JPanel childPanel = (JPanel)component;
int childPanelComponentCount = childPanel.getComponentCount();
for (int k=0; k<childPanelComponentCount; k++) {
Component subComponent = childPanel.getComponent(k);
if (subComponent instanceof JLabel) {
int labelWidth = subComponent.getPreferredSize().width;
if (maximumLabelWidth < labelWidth) {
maximumLabelWidth = labelWidth;
}
}
}
} else if (component instanceof JLabel) {
int labelWidth = component.getPreferredSize().width;
if (maximumLabelWidth < labelWidth) {
maximumLabelWidth = labelWidth;
}
}
}
for (int i=0; i<rootPanelComponentCount; i++) {
Component component = contentPanel.getComponent(i);
if (component instanceof JPanel) {
JPanel childPanel = (JPanel)component;
int childPanelComponentCount = childPanel.getComponentCount();
for (int k=0; k<childPanelComponentCount; k++) {
Component subComponent = childPanel.getComponent(k);
if (subComponent instanceof JLabel) {
setLabelSize((JLabel)subComponent, maximumLabelWidth);
}
}
} else if (component instanceof JLabel) {
setLabelSize((JLabel)component, maximumLabelWidth);
}
}
}
private static void setLabelSize(JLabel label, int maximumLabelWidth) {
Dimension labelSize = label.getPreferredSize();
labelSize.width = maximumLabelWidth;
label.setPreferredSize(labelSize);
label.setMinimumSize(labelSize);
}
private static class JDialogExtended extends JDialog {
private Runnable layoutRunnable;
private JDialogExtended(Window owner, ModalityType modalityType) {
super(owner, modalityType);
}
@Override
protected final JRootPane createRootPane() {
JRootPane rp = new JRootPane() {
@Override
public void doLayout() {
super.doLayout();
layoutRunnable.run();
}
};
rp.setOpaque(true);
return rp;
}
public final void setLayoutRunnable(Runnable layoutRunnable) {
this.layoutRunnable = layoutRunnable;
}
}
}
| 11,724 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CustomButton.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/loading/CustomButton.java | package org.esa.snap.ui.loading;
import javax.swing.*;
import java.awt.*;
public class CustomButton extends JButton {
private final int preferredHeight;
public CustomButton(String text, int preferredHeight) {
super(text);
if (preferredHeight <= 0) {
throw new IllegalArgumentException("The preferred size " + preferredHeight + " must be > 0.");
}
this.preferredHeight = preferredHeight;
}
@Override
public void setBounds(int x, int y, int width, int height) {
super.setBounds(x, y, width, this.preferredHeight);
}
@Override
public Dimension getMinimumSize() {
Dimension size = super.getMinimumSize();
size.height = this.preferredHeight;
return size;
}
@Override
public Dimension getMaximumSize() {
Dimension size = super.getMaximumSize();
size.height = this.preferredHeight;
return size;
}
@Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.height = this.preferredHeight;
return size;
}
}
| 1,131 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CustomComboBox.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/loading/CustomComboBox.java | package org.esa.snap.ui.loading;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
* Created by jcoravu on 10/2/2020.
*/
public class CustomComboBox<ItemType> extends JComboBox<ItemType> {
private final int preferredHeight;
public CustomComboBox(ItemRenderer<ItemType> itemRenderer, int preferredHeight, boolean isEditable, Color backgroundColor) {
this(itemRenderer, preferredHeight, isEditable);
if (backgroundColor == null) {
throw new NullPointerException("The background color is null.");
}
setBackground(backgroundColor);
}
public CustomComboBox(ItemRenderer<ItemType> itemRenderer, int preferredHeight, boolean isEditable) {
super();
if (preferredHeight <= 0) {
throw new IllegalArgumentException("The preferred size " + preferredHeight + " must be > 0.");
}
this.preferredHeight = preferredHeight;
setBorder(SwingUtils.LINE_BORDER);
setMaximumRowCount(5); // the maximum number of visible items in the popup
setEditable(true); // set the combo box as editable
ComboBoxEditorComponent<ItemType> comboBoxEditorComponent = new ComboBoxEditorComponent<ItemType>(itemRenderer);
JTextField editorTextField = comboBoxEditorComponent.getEditorComponent();
editorTextField.setBorder(SwingUtils.EDIT_TEXT_BORDER);
editorTextField.setOpaque(false); // set the editor text transparent
if (!isEditable) {
comboBoxEditorComponent.getEditorComponent().setEditable(false); // set the editor component read only
}
setEditor(comboBoxEditorComponent);
editorTextField.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent mouseEvent) {
if (isEnabled() && SwingUtilities.isLeftMouseButton(mouseEvent)) {
if (isPopupVisible()) {
hidePopup();
} else {
showPopup();
}
}
}
});
LabelListCellRenderer<ItemType> listCellRenderer = new LabelListCellRenderer<ItemType>(this.preferredHeight, itemRenderer) {
@Override
public JLabel getListCellRendererComponent(JList<? extends ItemType> list, ItemType value, int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (!isSelected) {
label.setBackground(CustomComboBox.this.getBackground());
}
return label;
}
};
listCellRenderer.setBorder(SwingUtils.EDIT_TEXT_BORDER);
setRenderer(listCellRenderer);
}
@Override
protected final void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
graphics.setColor(getBackground());
graphics.fillRect(0, 0, getWidth(), getHeight());
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
if (getEditor() != null && getEditor().getEditorComponent() != null) {
getEditor().getEditorComponent().setEnabled(enabled);
}
}
@Override
public void setBounds(int x, int y, int width, int height) {
super.setBounds(x, y, width, this.preferredHeight);
}
@Override
public Dimension getMinimumSize() {
Dimension size = super.getMinimumSize();
size.height = this.preferredHeight;
return size;
}
@Override
public Dimension getMaximumSize() {
Dimension size = super.getMaximumSize();
size.height = this.preferredHeight;
return size;
}
@Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.height = this.preferredHeight;
return size;
}
private static class ComboBoxEditorComponent<ItemType> implements ComboBoxEditor {
private final ItemRenderer<ItemType> itemRenderer;
private final JTextField editorTextField;
private ItemType item;
private ComboBoxEditorComponent(ItemRenderer<ItemType> itemRenderer) {
this.itemRenderer = itemRenderer;
this.editorTextField = new JTextField("", 9);
this.editorTextField.setBorder(null); // no border for editor text field
}
@Override
public JTextField getEditorComponent() {
return this.editorTextField;
}
@Override
public void setItem(Object item) {
this.item = (ItemType)item;
String text;
if (this.item == null) {
text = "";
} else {
text = this.itemRenderer.getItemDisplayText(this.item);
}
this.editorTextField.setText(text);
}
@Override
public Object getItem() {
String newValue = this.editorTextField.getText();
if (this.item != null && !(this.item instanceof String)) {
// the item is not a string
if (newValue.equals(this.itemRenderer.getItemDisplayText(this.item))) {
return this.item;
}
}
return newValue;
}
@Override
public void selectAll() {
// do nothing
}
@Override
public void addActionListener(ActionListener listener) {
this.editorTextField.addActionListener(listener);
}
@Override
public void removeActionListener(ActionListener listener) {
this.editorTextField.removeActionListener(listener);
}
}
}
| 5,985 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SwingUtils.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/loading/SwingUtils.java | package org.esa.snap.ui.loading;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.net.URL;
/**
* Created by jcoravu on 10/1/2019.
*/
public class SwingUtils {
public static final Color TRANSPARENT_COLOR = new Color(255, 255, 255, 0);
public static final LineBorder LINE_BORDER = new LineBorder(Color.GRAY, 1);
public static final EmptyBorder EDIT_TEXT_BORDER = new EmptyBorder(0, 2, 0, 0);
private SwingUtils() {
}
public static ImageIcon loadImage(String resourceImagePath) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL imageURL = classLoader.getResource(resourceImagePath);
if (imageURL == null) {
throw new NullPointerException("The image '"+resourceImagePath+"' does not exist into the sources.");
}
return new ImageIcon(imageURL);
}
public static ImageIcon loadImage(String resourceImagePath, Dimension buttonSize, Integer scaledImagePadding) {
ImageIcon icon = loadImage(resourceImagePath);
if (scaledImagePadding != null && scaledImagePadding.intValue() >= 0) {
Image scaledImage = getScaledImage(icon.getImage(), buttonSize.width, buttonSize.height, scaledImagePadding.intValue());
icon = new ImageIcon(scaledImage);
}
return icon;
}
public static JButton buildButton(String resourceImagePath, ActionListener buttonListener, Dimension buttonSize, Integer scaledImagePadding) {
ImageIcon icon = loadImage(resourceImagePath, buttonSize, scaledImagePadding);
JButton button = new JButton(icon);
button.setFocusable(false);
button.addActionListener(buttonListener);
button.setPreferredSize(buttonSize);
button.setMinimumSize(buttonSize);
button.setMaximumSize(buttonSize);
return button;
}
private static Image getScaledImage(Image srcImg, int destinationImageWidth, int destinationImageHeight, int padding) {
BufferedImage resizedImg = new BufferedImage(destinationImageWidth, destinationImageHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(srcImg, padding, padding, destinationImageWidth-padding, destinationImageHeight-padding, 0, 0, srcImg.getWidth(null), srcImg.getHeight(null), null);
g2.dispose();
return resizedImg;
}
public static JComboBox<String> buildComboBox(String[] values, String valueToSelect, int textFieldPreferredHeight, boolean isEditable) {
ItemRenderer<String> itemRenderer = new ItemRenderer<String>() {
@Override
public String getItemDisplayText(String item) {
return (item == null) ? " " : item;
}
};
JComboBox<String> comboBox = new CustomComboBox(itemRenderer, textFieldPreferredHeight, isEditable);
if (values != null) {
for (int i = 0; i < values.length; i++) {
comboBox.addItem(values[i]);
}
}
if (valueToSelect != null) {
for (int i=0; i<values.length; i++) {
if (valueToSelect.equals(values[i])) {
comboBox.setSelectedIndex(i);
break;
}
}
}
return comboBox;
}
public static JButton buildBrowseButton(ActionListener actionListener, int textFieldPreferredHeight) {
JButton browseButton = new JButton("...");
browseButton.setFocusable(false);
browseButton.addActionListener(actionListener);
Dimension preferredSize = new Dimension(textFieldPreferredHeight, textFieldPreferredHeight);
browseButton.setPreferredSize(preferredSize);
browseButton.setMinimumSize(preferredSize);
browseButton.setMaximumSize(preferredSize);
return browseButton;
}
public static GridBagConstraints buildConstraints(int columnIndex, int rowIndex, int fillType, int anchorType, int columnSpan, int rowSpan, Insets aMargins) {
GridBagConstraints constraints = buildConstraints(columnIndex, rowIndex, fillType, anchorType, columnSpan, rowSpan);
constraints.insets.top = aMargins.top;
constraints.insets.left = aMargins.left;
constraints.insets.bottom = aMargins.bottom;
constraints.insets.right = aMargins.right;
return constraints;
}
public static GridBagConstraints buildConstraints(int columnIndex, int rowIndex, int fillType, int anchorType, int columnSpan, int rowSpan, int topMargin, int leftMargin) {
GridBagConstraints constraints = buildConstraints(columnIndex, rowIndex, fillType, anchorType, columnSpan, rowSpan);
constraints.insets.top = topMargin;
constraints.insets.left = leftMargin;
constraints.insets.bottom = 0;
constraints.insets.right = 0;
return constraints;
}
public static GridBagConstraints buildConstraints(int columnIndex, int rowIndex, int fillType, int anchorType, int columnSpan, int rowSpan) {
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = columnIndex; // place the component on the first column (zero based index)
constraints.gridy = rowIndex; // place the component on the first row (zero based index)
constraints.gridwidth = columnSpan; // the component will have one cell on horizontal
constraints.gridheight = rowSpan; // the component will have one cell on vertical
constraints.weightx = 0; // the cell will not receive extra horizontal space
constraints.weighty = 0; // the cell will not receive extra vertical space
if (fillType == GridBagConstraints.HORIZONTAL) {
constraints.weightx = 1.0;
} else if (fillType == GridBagConstraints.VERTICAL) {
constraints.weighty = 1.0;
} else if (fillType == GridBagConstraints.BOTH) {
constraints.weightx = 1.0;
constraints.weighty = 1.0;
}
constraints.fill = fillType;
constraints.anchor = anchorType;
return constraints;
}
}
| 6,487 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PairRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/loading/PairRunnable.java | package org.esa.snap.ui.loading;
/**
* Created by jcoravu on 19/2/2020.
*/
public abstract class PairRunnable<First, Second> implements Runnable {
private final First first;
private final Second second;
public PairRunnable(First first, Second second) {
this.first = first;
this.second = second;
}
protected abstract void execute(First first, Second second);
@Override
public void run() {
execute(this.first, this.second);
}
}
| 489 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CircularProgressIndicatorLabel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/loading/CircularProgressIndicatorLabel.java | package org.esa.snap.ui.loading;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by jcoravu on 28/12/2018.
*/
public class CircularProgressIndicatorLabel extends JLabel {
private final CircularProgressPainter circularProgressPainter;
private Timer timer;
private boolean isRunning;
public CircularProgressIndicatorLabel() {
this.circularProgressPainter = new CircularProgressPainter(Color.LIGHT_GRAY, getForeground());
this.isRunning = false;
setIcon(new PainterIcon(this.circularProgressPainter, this.circularProgressPainter.getPreferredSize()));
}
@Override
public void removeNotify() {
stopAnimation();
super.removeNotify();
}
@Override
public void addNotify() {
super.addNotify();
startAnimation();
}
public void setRunning(boolean isRunning) {
boolean timerDefined = (this.timer != null);
if (!timerDefined && isRunning) {
this.isRunning = true;
startAnimation();
} else if (timerDefined && !isRunning) {
this.isRunning = false;
stopAnimation();
}
}
private void startAnimation() {
if (!this.isRunning || getParent() == null) {
return;
}
stopAnimation();
this.timer = new Timer(100, new ActionListener() {
private int frame = 0;
@Override
public void actionPerformed(ActionEvent e) {
frame = (frame + 1) % circularProgressPainter.getPoints();
circularProgressPainter.setFrame(frame);
repaint();
}
});
this.timer.start(); // start the timer
}
private void stopAnimation() {
if (this.timer != null) {
this.timer.stop();
this.circularProgressPainter.setFrame(-1);
repaint();
this.timer = null;
}
}
private static class PainterIcon implements Icon {
private final Dimension size;
private final CircularProgressPainter painter;
public PainterIcon(CircularProgressPainter painter, Dimension size) {
this.painter = painter;
this.size = size;
}
@Override
public int getIconHeight() {
return this.size.height;
}
@Override
public int getIconWidth() {
return this.size.width;
}
@Override
public void paintIcon(Component component, Graphics graphics, int x, int y) {
if (this.painter != null && graphics instanceof Graphics2D) {
graphics = graphics.create();
graphics.translate(x, y);
this.painter.doPaint((Graphics2D) graphics, getIconWidth(), getIconHeight());
graphics.translate(-x, -y);
graphics.dispose();
}
}
}
}
| 3,005 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractDiagramGraph.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/diagram/AbstractDiagramGraph.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.ui.diagram;
import org.esa.snap.core.util.Guardian;
public abstract class AbstractDiagramGraph implements DiagramGraph {
private Diagram diagram;
private DiagramGraphStyle style;
protected AbstractDiagramGraph() {
style = new DefaultDiagramGraphStyle();
}
public Diagram getDiagram() {
return diagram;
}
public void setDiagram(Diagram diagram) {
this.diagram = diagram;
}
public void setStyle(DiagramGraphStyle style) {
Guardian.assertNotNull("style", style);
this.style = style;
invalidate();
}
public DiagramGraphStyle getStyle() {
return style;
}
protected void invalidate() {
if (diagram != null) {
diagram.invalidate();
}
}
public void dispose() {
diagram = null;
style = null;
}
}
| 1,604 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DiagramGraphStyle.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/diagram/DiagramGraphStyle.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.ui.diagram;
import java.awt.Color;
import java.awt.Paint;
import java.awt.Stroke;
public interface DiagramGraphStyle {
boolean isShowingPoints();
Paint getFillPaint();
Stroke getOutlineStroke();
Color getOutlineColor();
}
| 987 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DefaultDiagramGraph.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/diagram/DefaultDiagramGraph.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.ui.diagram;
import com.bc.ceres.core.Assert;
import com.bc.ceres.core.ProgressMonitor;
import org.esa.snap.core.util.ObjectUtils;
import org.esa.snap.core.util.math.IndexValidator;
import org.esa.snap.core.util.math.Range;
public class DefaultDiagramGraph extends AbstractDiagramGraph {
private String xName;
private double[] xValues;
private String yName;
private double[] yValues;
private Range xRange;
private Range yRange;
public DefaultDiagramGraph() {
}
public DefaultDiagramGraph(String xName,
double[] xValues,
String yName,
double[] yValues) {
Assert.notNull(yName, "yName");
setXName(xName);
setYName(yName);
setXYValues(xValues, yValues);
}
public String getXName() {
return xName;
}
public void setXName(String xName) {
Assert.notNull(xName, "xName");
if (!ObjectUtils.equalObjects(this.xName, xName)) {
this.xName = xName;
invalidate();
}
}
public String getYName() {
return yName;
}
public void setYName(String yName) {
Assert.notNull(yName, "yName");
if (!ObjectUtils.equalObjects(this.yName, yName)) {
this.yName = yName;
invalidate();
}
}
public double[] getXValues() {
return xValues;
}
public double[] getYValues() {
return yValues;
}
public void setXYValues(double[] xValues, double[] yValues) {
Assert.notNull(xValues, "xValues");
Assert.notNull(yValues, "yValues");
Assert.argument(xValues.length > 1, "xValues.length > 1");
Assert.argument(xValues.length == yValues.length, "xValues.length == yValues.length");
if (!ObjectUtils.equalObjects(this.xValues, xValues) || !ObjectUtils.equalObjects(this.yValues, yValues)) {
this.xValues = xValues;
this.yValues = yValues;
this.xRange = Range.computeRangeDouble(xValues, IndexValidator.TRUE, null, ProgressMonitor.NULL);
this.yRange = Range.computeRangeDouble(yValues, IndexValidator.TRUE, null, ProgressMonitor.NULL);
invalidate();
}
}
public int getNumValues() {
return xValues.length;
}
public double getXValueAt(int index) {
return xValues[index];
}
public double getYValueAt(int index) {
return yValues[index];
}
public double getXMin() {
return xRange.getMin();
}
public double getXMax() {
return xRange.getMax();
}
public double getYMin() {
return yRange.getMin();
}
public double getYMax() {
return yRange.getMax();
}
@Override
public void dispose() {
xValues = null;
yValues = null;
super.dispose();
}
}
| 3,653 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DefaultDiagramGraphStyle.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/diagram/DefaultDiagramGraphStyle.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.ui.diagram;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Paint;
import java.awt.Stroke;
public class DefaultDiagramGraphStyle implements DiagramGraphStyle {
private Color outlineColor;
private boolean showingPoints;
private Paint fillPaint;
private Stroke outlineStroke;
public DefaultDiagramGraphStyle() {
outlineColor = Color.BLACK;
fillPaint = Color.WHITE;
showingPoints = true;
outlineStroke = new BasicStroke(1.0f);
}
public Color getOutlineColor() {
return outlineColor;
}
public void setOutlineColor(Color outlineColor) {
this.outlineColor = outlineColor;
}
public Paint getFillPaint() {
return fillPaint;
}
public void setFillPaint(Paint fillPaint) {
this.fillPaint = fillPaint;
}
public boolean isShowingPoints() {
return showingPoints;
}
public void setShowingPoints(boolean showingPoints) {
this.showingPoints = showingPoints;
}
public Stroke getOutlineStroke() {
return outlineStroke;
}
public void setOutlineStroke(Stroke stroke) {
this.outlineStroke = stroke;
}
}
| 1,941 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
Diagram.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/diagram/Diagram.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.ui.diagram;
import org.esa.snap.core.util.Guardian;
import org.esa.snap.core.util.ObjectUtils;
import org.esa.snap.core.util.math.Range;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
/**
* The <code>Diagram</code> class is used to plot simple X/Y graphs. Instances of this class are composed of
* <code>{@link DiagramGraph}</code> and two <code>{@link DiagramAxis}</code> objects for the X and Y axes.
*/
public class Diagram {
public final static String DEFAULT_FONT_NAME = "Verdana";
public final static int DEFAULT_FONT_SIZE = 9;
public static final Color DEFAULT_FOREGROUND_COLOR = Color.BLACK;
public static final Color DEFAULT_BACKGROUND_COLOR = new Color(210, 210, 255);
// Main components: graphs + axes
private List<DiagramGraph> graphs;
private DiagramAxis xAxis;
private DiagramAxis yAxis;
// Visual properties
private boolean drawGrid;
private Font font;
private int textGap;
private Color textColor;
private int majorTickLength;
private int minorTickLength;
private Color majorGridColor;
private Color minorGridColor;
private Color foregroundColor;
private Color backgroundColor;
// Change management
private ArrayList<DiagramChangeListener> changeListeners;
private int numMergedChangeEvents;
// Internal properties
private boolean valid;
private double xMinAccum;
private double xMaxAccum;
private double yMinAccum;
private double yMaxAccum;
// Computed internal properties
private FontMetrics fontMetrics;
private Rectangle graphArea;
private String[] yTickTexts;
private String[] xTickTexts;
private int maxYTickTextWidth;
private RectTransform transform;
public Diagram() {
graphs = new ArrayList<DiagramGraph>(3);
font = new Font(DEFAULT_FONT_NAME, Font.PLAIN, DEFAULT_FONT_SIZE);
textGap = 3;
majorTickLength = 5;
minorTickLength = 3;
drawGrid = true;
foregroundColor = DEFAULT_FOREGROUND_COLOR;
backgroundColor = DEFAULT_BACKGROUND_COLOR;
minorGridColor = DEFAULT_BACKGROUND_COLOR.brighter();
majorGridColor = DEFAULT_BACKGROUND_COLOR.darker();
textColor = DEFAULT_FOREGROUND_COLOR;
changeListeners = new ArrayList<DiagramChangeListener>(3);
disableChangeEventMerging();
resetMinMaxAccumulators();
}
public Diagram(DiagramAxis xAxis, DiagramAxis yAxis, DiagramGraph graph) {
this();
setXAxis(xAxis);
setYAxis(yAxis);
addGraph(graph);
resetMinMaxAccumulatorsFromAxes();
}
public void enableChangeEventMerging() {
numMergedChangeEvents = 0;
}
public void disableChangeEventMerging() {
final boolean changeEventsMerged = numMergedChangeEvents > 0;
numMergedChangeEvents = -1;
if (changeEventsMerged) {
invalidate();
}
}
public RectTransform getTransform() {
return transform;
}
public boolean getDrawGrid() {
return drawGrid;
}
public void setDrawGrid(boolean drawGrid) {
if (this.drawGrid != drawGrid) {
this.drawGrid = drawGrid;
invalidate();
}
}
public DiagramAxis getXAxis() {
return xAxis;
}
public void setXAxis(DiagramAxis xAxis) {
Guardian.assertNotNull("xAxis", xAxis);
if (this.xAxis != xAxis) {
if (this.xAxis != null) {
this.xAxis.setDiagram(null);
}
this.xAxis = xAxis;
this.xAxis.setDiagram(this);
invalidate();
}
}
public DiagramAxis getYAxis() {
return yAxis;
}
public void setYAxis(DiagramAxis yAxis) {
Guardian.assertNotNull("yAxis", yAxis);
if (this.yAxis != yAxis) {
if (this.yAxis != null) {
this.yAxis.setDiagram(null);
}
this.yAxis = yAxis;
this.yAxis.setDiagram(this);
invalidate();
}
}
public DiagramGraph[] getGraphs() {
return graphs.toArray(new DiagramGraph[0]);
}
public int getGraphCount() {
return graphs.size();
}
public DiagramGraph getGraph(int index) {
return graphs.get(index);
}
public void addGraph(DiagramGraph graph) {
Guardian.assertNotNull("graph", graph);
if (graphs.add(graph)) {
graph.setDiagram(this);
invalidate();
}
}
public void removeGraph(DiagramGraph graph) {
Guardian.assertNotNull("graph", graph);
if (graphs.remove(graph)) {
graph.setDiagram(null);
invalidate();
}
}
public void removeAllGraphs() {
if (getGraphCount() > 0) {
for (DiagramGraph graph : graphs) {
graph.setDiagram(null);
}
graphs.clear();
invalidate();
}
}
public Font getFont() {
return font;
}
public void setFont(Font font) {
if (!ObjectUtils.equalObjects(this.font, font)) {
this.font = font;
invalidate();
}
}
public Color getMajorGridColor() {
return majorGridColor;
}
public void setMajorGridColor(Color majorGridColor) {
if (!ObjectUtils.equalObjects(this.majorGridColor, majorGridColor)) {
this.majorGridColor = majorGridColor;
invalidate();
}
}
public Color getMinorGridColor() {
return minorGridColor;
}
public void setMinorGridColor(Color minorGridColor) {
if (!ObjectUtils.equalObjects(this.minorGridColor, minorGridColor)) {
this.minorGridColor = minorGridColor;
invalidate();
}
}
public Color getForegroundColor() {
return foregroundColor;
}
public void setForegroundColor(Color foregroundColor) {
if (!ObjectUtils.equalObjects(this.foregroundColor, foregroundColor)) {
this.foregroundColor = foregroundColor;
invalidate();
}
}
public Color getBackgroundColor() {
return backgroundColor;
}
public void setBackgroundColor(Color backgroundColor) {
this.backgroundColor = backgroundColor;
if (!ObjectUtils.equalObjects(this.backgroundColor, backgroundColor)) {
this.backgroundColor = backgroundColor;
invalidate();
}
}
public int getTextGap() {
return textGap;
}
public void setTextGap(int textGap) {
if (!ObjectUtils.equalObjects(this.font, font)) {
this.textGap = textGap;
invalidate();
}
}
public boolean isValid() {
return valid;
}
public void setValid(boolean valid) {
this.valid = valid;
}
public void invalidate() {
setValid(false);
fireDiagramChanged();
}
public Rectangle getGraphArea() {
return new Rectangle(graphArea);
}
public void render(Graphics2D g2d, int x, int y, int width, int height) {
Font oldFont = g2d.getFont();
g2d.setFont(font);
if (!isValid()) {
validate(g2d, x, y, width, height);
}
if (isValid()) {
drawAxes(g2d, x, y, width, height);
drawGraphs(g2d);
}
g2d.setFont(oldFont);
}
private void validate(Graphics2D g2d, int x, int y, int width, int height) {
fontMetrics = g2d.getFontMetrics();
xTickTexts = xAxis.createTickmarkTexts();
yTickTexts = yAxis.createTickmarkTexts();
// define y-Axis _values
final int fontAscent = fontMetrics.getAscent();
maxYTickTextWidth = 0;
for (String yTickText : yTickTexts) {
int sw = fontMetrics.stringWidth(yTickText);
maxYTickTextWidth = Math.max(maxYTickTextWidth, sw);
}
final int widthMaxX = fontMetrics.stringWidth(xTickTexts[xTickTexts.length - 1]);
int x1 = textGap + fontAscent + textGap + maxYTickTextWidth + textGap + majorTickLength;
int y1 = textGap + fontAscent / 2;
int x2 = x + width - (textGap + widthMaxX / 2);
int y2 = y + height - (textGap + fontAscent + textGap + fontAscent + textGap + majorTickLength);
final int w = x2 - x1 + 1;
final int h = y2 - y1 + 1;
graphArea = new Rectangle(x1, y1, w, h);
transform = null;
if (w > 0 && h > 0) {
transform = new RectTransform(new Range(xAxis.getMinValue(), xAxis.getMaxValue()),
new Range(yAxis.getMinValue(), yAxis.getMaxValue()),
new Range(graphArea.x, graphArea.x + graphArea.width),
new Range(graphArea.y + graphArea.height, graphArea.y));
}
setValid(w > 0 && h > 0);
}
private void drawGraphs(Graphics2D g2d) {
final Stroke oldStroke = g2d.getStroke();
final Color oldColor = g2d.getColor();
final Rectangle oldClip = g2d.getClipBounds();
g2d.setClip(graphArea.x, graphArea.y, graphArea.width, graphArea.height);
Point2D.Double a;
Point2D.Double b1;
Point2D.Double b2;
DiagramGraph[] graphs = getGraphs();
for (DiagramGraph graph : graphs) {
a = new Point2D.Double();
b1 = new Point2D.Double();
b2 = new Point2D.Double();
g2d.setStroke(graph.getStyle().getOutlineStroke());
g2d.setColor(graph.getStyle().getOutlineColor());
int n = graph.getNumValues();
for (int i = 0; i < n; i++) {
double xa = graph.getXValueAt(i);
double ya = graph.getYValueAt(i);
if (!Double.isNaN(ya)) {
a.setLocation(xa, ya);
if (b2.equals(new Point2D.Double())) {
transform.transformA2B(a, b1);
b2.setLocation(b1);
} else {
b1.setLocation(b2);
transform.transformA2B(a, b2);
}
if (i > 0 && !b1.equals(b2)) {
g2d.draw(new Line2D.Double(b1, b2));
}
}
}
g2d.setStroke(new BasicStroke(0.5f));
if (graph.getStyle().isShowingPoints()) {
for (int i = 0; i < n; i++) {
double xa = graph.getXValueAt(i);
double ya = graph.getYValueAt(i);
if (!Double.isNaN(ya)) {
a.setLocation(xa, ya);
transform.transformA2B(a, b1);
Rectangle2D.Double r = new Rectangle2D.Double(b1.getX() - 1.5,
b1.getY() - 1.5,
3.0, 3.0);
g2d.setPaint(graph.getStyle().getFillPaint());
g2d.fill(r);
g2d.setColor(graph.getStyle().getOutlineColor());
g2d.draw(r);
}
}
}
}
g2d.setStroke(oldStroke);
g2d.setColor(oldColor);
g2d.setClip(oldClip);
}
private void drawAxes(Graphics2D g2d, int xOffset, int yOffset, int width, int height) {
final Stroke oldStroke = g2d.getStroke();
final Color oldColor = g2d.getColor();
g2d.setStroke(new BasicStroke(1.0f));
g2d.setColor(backgroundColor);
g2d.fillRect(graphArea.x, graphArea.y, graphArea.width, graphArea.height);
int tw;
int x0, y0, x1, x2, y1, y2, xMin, xMax, yMin, yMax, n, n1, n2;
String text;
final int th = fontMetrics.getAscent();
// draw X major tick lines
xMin = graphArea.x;
xMax = graphArea.x + graphArea.width;
yMin = graphArea.y;
yMax = graphArea.y + graphArea.height;
y1 = graphArea.y + graphArea.height;
n1 = xAxis.getNumMajorTicks();
n2 = xAxis.getNumMinorTicks();
n = (n1 - 1) * (n2 + 1) + 1;
for (int i = 0; i < n; i++) {
x0 = xMin + (i * (xMax - xMin)) / (n - 1);
if (i % (n2 + 1) == 0) {
y2 = y1 + majorTickLength;
text = xTickTexts[i / (n2 + 1)];
tw = fontMetrics.stringWidth(text);
g2d.setColor(textColor);
g2d.drawString(text, x0 - tw / 2, y2 + textGap + fontMetrics.getAscent());
if (drawGrid) {
g2d.setColor(majorGridColor);
g2d.drawLine(x0, y1, x0, yMin);
}
} else {
y2 = y1 + minorTickLength;
if (drawGrid) {
g2d.setColor(minorGridColor);
g2d.drawLine(x0, y1, x0, yMin);
}
}
g2d.setColor(foregroundColor);
g2d.drawLine(x0, y1, x0, y2);
}
// draw Y major tick lines
x1 = graphArea.x;
n1 = yAxis.getNumMajorTicks();
n2 = yAxis.getNumMinorTicks();
n = (n1 - 1) * (n2 + 1) + 1;
for (int i = 0; i < n; i++) {
if(yAxis.isMinToMax())
y0 = yMin + (i * (yMax - yMin)) / (n - 1);
else
y0 = yMax - (i * (yMax - yMin)) / (n - 1);
if (i % (n2 + 1) == 0) {
x2 = x1 - majorTickLength;
text = yTickTexts[n1 - 1 - (i / (n2 + 1))];
tw = fontMetrics.stringWidth(text);
g2d.setColor(textColor);
g2d.drawString(text, x2 - textGap - tw, y0 + th / 2);
if (drawGrid) {
g2d.setColor(majorGridColor);
g2d.drawLine(x1, y0, xMax, y0);
}
} else {
x2 = x1 - minorTickLength;
if (drawGrid) {
g2d.setColor(minorGridColor);
g2d.drawLine(x1, y0, xMax, y0);
}
}
g2d.setColor(foregroundColor);
g2d.drawLine(x1, y0, x2, y0);
}
g2d.setColor(foregroundColor);
g2d.drawRect(graphArea.x, graphArea.y, graphArea.width, graphArea.height);
// draw X axis name and unit
text = getAxisText(xAxis);
tw = fontMetrics.stringWidth(text);
x1 = graphArea.x + graphArea.width / 2 - tw / 2;
y1 = yOffset + height - textGap;
g2d.setColor(textColor);
g2d.drawString(text, x1, y1);
// draw Y axis name and unit
text = getAxisText(yAxis);
tw = fontMetrics.stringWidth(text);
x1 = graphArea.x - majorTickLength - textGap - maxYTickTextWidth - textGap;
y1 = graphArea.y + graphArea.height / 2 + tw / 2;
final AffineTransform oldTransform = g2d.getTransform();
g2d.translate(x1, y1);
g2d.rotate(-Math.PI / 2);
g2d.setColor(textColor);
g2d.drawString(text, 0, 0);
g2d.setTransform(oldTransform);
g2d.setStroke(oldStroke);
g2d.setColor(oldColor);
}
private String getAxisText(DiagramAxis axis) {
StringBuilder sb = new StringBuilder(37);
if (axis.getName() != null && axis.getName().length() > 0) {
sb.append(axis.getName());
}
if (axis.getUnit() != null && axis.getUnit().length() > 0) {
sb.append(" (");
sb.append(axis.getUnit());
sb.append(")");
}
return sb.toString();
}
public DiagramGraph getClosestGraph(int x, int y) {
double minDist = Double.MAX_VALUE;
Point2D.Double a = new Point2D.Double();
Point2D.Double b1 = new Point2D.Double();
Point2D.Double b2 = new Point2D.Double();
DiagramGraph closestGraph = null;
for (DiagramGraph graph : getGraphs()) {
double minDistGraph = Double.MAX_VALUE;
int n = graph.getNumValues();
for (int i = 0; i < n; i++) {
a.setLocation(graph.getXValueAt(i), graph.getYValueAt(i));
b1.setLocation(b2);
transform.transformA2B(a, b2);
if (i > 0) {
Line2D.Double segment = new Line2D.Double(b1, b2);
double v = segment.ptSegDist(x, y);
if (v < minDistGraph) {
minDistGraph = v;
}
}
}
if (minDistGraph < minDist) {
minDist = minDistGraph;
closestGraph = graph;
}
}
return closestGraph;
}
public void adjustAxes(boolean reset) {
if (reset) {
resetMinMaxAccumulators();
}
for (DiagramGraph graph : graphs) {
adjustAxes(graph);
}
}
protected void adjustAxes(DiagramGraph graph) {
try {
enableChangeEventMerging();
final DiagramAxis xAxis = getXAxis();
xMinAccum = Math.min(xMinAccum, graph.getXMin());
xMaxAccum = Math.max(xMaxAccum, graph.getXMax());
boolean xRangeValid = xMaxAccum > xMinAccum;
if (xRangeValid) {
xAxis.setValueRange(xMinAccum, xMaxAccum);
xAxis.setOptimalSubDivision(4, 6, 5);
}
final DiagramAxis yAxis = getYAxis();
yMinAccum = Math.min(yMinAccum, graph.getYMin());
yMaxAccum = Math.max(yMaxAccum, graph.getYMax());
boolean yRangeValid = yMaxAccum > yMinAccum;
if (yRangeValid) {
yAxis.setValueRange(yMinAccum, yMaxAccum);
yAxis.setOptimalSubDivision(3, 6, 5);
}
} finally {
disableChangeEventMerging();
}
}
public void resetMinMaxAccumulators() {
xMinAccum = +Double.MAX_VALUE;
xMaxAccum = -Double.MAX_VALUE;
yMinAccum = +Double.MAX_VALUE;
yMaxAccum = -Double.MAX_VALUE;
}
public void resetMinMaxAccumulatorsFromAxes() {
xMinAccum = getXAxis().getMinValue();
xMaxAccum = getXAxis().getMaxValue();
yMinAccum = getYAxis().getMinValue();
yMaxAccum = getYAxis().getMaxValue();
}
private void fireDiagramChanged() {
if (numMergedChangeEvents == -1) {
final DiagramChangeListener[] listeners = getChangeListeners();
for (DiagramChangeListener listener : listeners) {
listener.diagramChanged(this);
}
} else {
numMergedChangeEvents++;
}
}
public DiagramChangeListener[] getChangeListeners() {
return changeListeners.toArray(new DiagramChangeListener[0]);
}
public void addChangeListener(DiagramChangeListener listener) {
if (listener != null) {
changeListeners.add(listener);
}
}
public void removeChangeListener(DiagramChangeListener listener) {
if (listener != null) {
changeListeners.remove(listener);
}
}
public static class RectTransform {
private AffineTransform transformA2B;
private AffineTransform transformB2A;
public RectTransform(Range ax, Range ay,
Range bx, Range by) {
double ax1 = ax.getMin();
double ax2 = ax.getMax();
double ay1 = ay.getMin();
double ay2 = ay.getMax();
double bx1 = bx.getMin();
double bx2 = bx.getMax();
double by1 = by.getMin();
double by2 = by.getMax();
transformA2B = new AffineTransform();
transformA2B.translate(bx1 - ax1 * (bx2 - bx1) / (ax2 - ax1),
by1 - ay1 * (by2 - by1) / (ay2 - ay1));
transformA2B.scale((bx2 - bx1) / (ax2 - ax1),
(by2 - by1) / (ay2 - ay1));
try {
transformB2A = transformA2B.createInverse();
} catch (NoninvertibleTransformException e) {
throw new IllegalArgumentException();
}
}
public Point2D transformA2B(Point2D a, Point2D b) {
return transformA2B.transform(a, b);
}
public Point2D transformB2A(Point2D b, Point2D a) {
return transformB2A.transform(b, a);
}
}
public void dispose() {
// first disable listening to what will happen next!
changeListeners.clear();
// remove main components
removeAllGraphs();
if (xAxis != null) {
xAxis.setDiagram(null);
xAxis = null;
}
if (yAxis != null) {
yAxis.setDiagram(null);
yAxis = null;
}
}
}
| 22,134 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DiagramCanvas.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/diagram/DiagramCanvas.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.ui.diagram;
import org.esa.snap.core.util.ObjectUtils;
import javax.swing.JPanel;
import javax.swing.event.MouseInputAdapter;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.text.DecimalFormat;
/**
* The <code>DiagramCanvas</code> class is a UI component used to display simple X/Y plots represented by objects of
* type <code>{@link Diagram}</code>.
*/
public class DiagramCanvas extends JPanel {
private Diagram diagram;
private String messageText;
private Insets insets;
private DiagramGraph selectedGraph;
private Point dragPoint;
private DiagramChangeHandler diagramChangeHandler;
public DiagramCanvas() {
setName("diagram");
diagramChangeHandler = new DiagramChangeHandler();
addComponentListener(new ComponentAdapter() {
/**
* Invoked when the component's size changes.
*/
@Override
public void componentResized(ComponentEvent e) {
if (diagram != null) {
diagram.invalidate();
}
}
});
MouseInputAdapter mouseHandler = new IndicatorHandler();
addMouseListener(mouseHandler);
addMouseMotionListener(mouseHandler);
setPreferredSize(new Dimension(320, 200));
}
public Diagram getDiagram() {
return diagram;
}
public void setDiagram(Diagram diagram) {
Diagram oldDiagram = this.diagram;
if (oldDiagram != diagram) {
if (oldDiagram != null) {
oldDiagram.removeChangeListener(diagramChangeHandler);
}
this.diagram = diagram;
if (this.diagram != null) {
diagram.addChangeListener(diagramChangeHandler);
}
firePropertyChange("diagram", oldDiagram, diagram);
repaint();
}
}
public String getMessageText() {
return messageText;
}
public void setMessageText(String messageText) {
String oldValue = this.messageText;
if (!ObjectUtils.equalObjects(oldValue, messageText)) {
this.messageText = messageText;
repaint();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (!(g instanceof Graphics2D)) {
return;
}
final Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
insets = getInsets(insets);
final int width = getWidth() - (insets.left + insets.right);
final int height = getHeight() - (insets.top + insets.bottom);
final int x0 = insets.left;
final int y0 = insets.top;
if (diagram != null) {
diagram.render(g2d, x0, y0, width, height);
if (dragPoint != null && selectedGraph != null) {
drawValueIndicator(g2d);
}
}
if (messageText != null) {
drawTextBox(g2d, this.messageText, x0 + width / 2, y0 + height / 2, new Color(255, 192, 102));
}
}
private void drawValueIndicator(Graphics2D g2d) {
Diagram.RectTransform transform = diagram.getTransform();
Point2D a = transform.transformB2A(dragPoint, null);
double x = a.getX();
if (x < selectedGraph.getXMin()) {
x = selectedGraph.getXMin();
}
if (x > selectedGraph.getXMax()) {
x = selectedGraph.getXMax();
}
final Stroke oldStroke = g2d.getStroke();
final Color oldColor = g2d.getColor();
double y = getY(selectedGraph, x);
Point2D b = transform.transformA2B(new Point2D.Double(x, y), null);
g2d.setStroke(new BasicStroke(1.0f));
g2d.setColor(diagram.getForegroundColor());
Ellipse2D.Double marker = new Ellipse2D.Double(b.getX() - 4.0, b.getY() - 4.0, 8.0, 8.0);
g2d.draw(marker);
g2d.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{6, 6}, 12));
g2d.setColor(diagram.getForegroundColor());
final Rectangle graphArea = diagram.getGraphArea();
g2d.draw(new Line2D.Double(b.getX(), graphArea.y + graphArea.height, b.getX(), b.getY()));
g2d.draw(new Line2D.Double(graphArea.x, b.getY(), b.getX(), b.getY()));
DecimalFormat decimalFormat = new DecimalFormat("0.#####E0");
String text = selectedGraph.getYName() + ": x = " + decimalFormat.format(x) + ", y = " + decimalFormat.format(y);
g2d.setStroke(oldStroke);
g2d.setColor(oldColor);
drawTextBox(g2d, text, graphArea.x + 6, graphArea.y + 6 + 16, new Color(255, 255, 255, 128));
}
private void drawTextBox(Graphics2D g2D, String text, int x0, int y0, Color color) {
final FontMetrics fontMetrics = g2D.getFontMetrics();
final Rectangle2D textBounds = fontMetrics.getStringBounds(text, g2D);
x0 -= textBounds.getWidth() / 2;
textBounds.setRect(textBounds.getX() - 1, textBounds.getY(), textBounds.getWidth(), textBounds.getHeight());
Rectangle2D.Double r = new Rectangle2D.Double(x0 + textBounds.getX() - 2.0,
y0 + textBounds.getY() - 2.0,
textBounds.getWidth() + 4.0,
textBounds.getHeight() + 4.0);
if (r.getMaxX() > getWidth()) {
r.setRect(getWidth() - r.getWidth(), r.getY(), r.getWidth(), r.getHeight());
}
if (r.getMinX() < 0) {
r.setRect(0, r.getY(), r.getWidth(), r.getHeight());
}
if (r.getMaxY() > getHeight()) {
r.setRect(r.getX(), getHeight() - r.getHeight(), r.getWidth(), r.getHeight());
}
if (r.getMinY() < 0) {
r.setRect(r.getX(), 0, r.getWidth(), r.getHeight());
}
g2D.setColor(color);
g2D.fill(r);
g2D.setColor(Color.black);
g2D.draw(r);
g2D.drawString(text, x0, y0);
}
public double getY(DiagramGraph graph, double x) {
int n = graph.getNumValues();
double x1, y1, x2 = 0, y2 = 0;
for (int i = 0; i < n; i++) {
x1 = x2;
y1 = y2;
x2 = graph.getXValueAt(i);
y2 = graph.getYValueAt(i);
if (i > 0) {
if (x >= x1 && x <= x2) {
return y1 + (x - x1) / (x2 - x1) * (y2 - y1);
}
}
}
throw new IllegalArgumentException("x out of bounds: " + x);
}
private class IndicatorHandler extends MouseInputAdapter {
@Override
public void mouseDragged(MouseEvent e) {
if (getDiagram() == null) {
return;
}
if (selectedGraph == null) {
selectedGraph = getDiagram().getClosestGraph(e.getX(), e.getY());
}
if (selectedGraph != null) {
dragPoint = e.getPoint();
} else {
dragPoint = null;
}
repaint();
}
@Override
public void mouseReleased(MouseEvent e) {
selectedGraph = null;
dragPoint = null;
repaint();
}
}
private class DiagramChangeHandler implements DiagramChangeListener {
public void diagramChanged(Diagram diagram) {
repaint();
}
}
}
| 8,759 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DiagramGraph.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/diagram/DiagramGraph.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.ui.diagram;
public interface DiagramGraph {
Diagram getDiagram();
void setDiagram(Diagram diagram);
String getXName();
String getYName();
int getNumValues();
double getXValueAt(int index);
double getYValueAt(int index);
double getXMin();
double getXMax();
double getYMin();
double getYMax();
DiagramGraphStyle getStyle();
void dispose();
}
| 1,147 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DiagramGraphIO.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/diagram/DiagramGraphIO.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.ui.diagram;
import org.esa.snap.core.util.PropertyMap;
import org.esa.snap.core.util.io.CsvReader;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.ui.SnapFileChooser;
import javax.swing.JOptionPane;
import java.awt.Component;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
public class DiagramGraphIO {
public static final SnapFileFilter CSV_FILE_FILTER = new SnapFileFilter("CSV", ".csv", "CSV (plain text)");
public static final SnapFileFilter SPECTRA_CSV_FILE_FILTER = new SnapFileFilter("Spectra-CSV", ".csv", "Spectra CSV");
public static final String DIAGRAM_GRAPH_IO_LAST_DIR_KEY = "diagramGraphIO.lastDir";
public static DiagramGraph[] readGraphs(Reader reader) throws IOException {
CsvReader csvReader = new CsvReader(reader, new char[]{'\t'});
List<DiagramGraph> graphGroup = new ArrayList<DiagramGraph>(5);
List<double[]> dataRecords = new ArrayList<double[]>(20);
String[] headerRecord = csvReader.readRecord();
while (true) {
if (headerRecord.length < 2) {
throw new IOException("Invalid format.");
}
String[] record = csvReader.readRecord();
if (record == null) {
break;
}
double[] dataRecord = toDoubles(record);
if (dataRecord != null) {
if (dataRecord.length != headerRecord.length) {
throw new IOException("Invalid format.");
}
dataRecords.add(dataRecord);
} else {
readGraphGroup(headerRecord, dataRecords, graphGroup);
headerRecord = record;
}
}
readGraphGroup(headerRecord, dataRecords, graphGroup);
return graphGroup.toArray(new DiagramGraph[0]);
}
public static void writeGraphs(DiagramGraph[] graphs, Writer writer) throws IOException {
List<List<DiagramGraph>> graphGroups = computeGraphGroups(graphs);
for (List<DiagramGraph> graphGroup : graphGroups) {
writeGraphGroup(graphGroup, writer);
}
}
private static void readGraphGroup(String[] headerRecord, List<double[]> dataRecords, List<DiagramGraph> graphs) {
if (dataRecords.size() > 0) {
double[] xValues = new double[dataRecords.size()];
for (int j = 0; j < dataRecords.size(); j++) {
xValues[j] = dataRecords.get(j)[0];
}
double[] dataRecord0 = dataRecords.get(0);
for (int i = 1; i < dataRecord0.length; i++) {
double[] yValues = new double[dataRecords.size()];
for (int j = 0; j < dataRecords.size(); j++) {
yValues[j] = dataRecords.get(j)[i];
}
graphs.add(new DefaultDiagramGraph(headerRecord[0], xValues,
headerRecord[i], yValues));
}
}
dataRecords.clear();
}
public static double[] toDoubles(String[] textRecord) throws IOException {
double[] doubleRecord = new double[textRecord.length];
for (int i = 0; i < textRecord.length; i++) {
try {
doubleRecord[i] = Double.valueOf(textRecord[i]);
} catch (NumberFormatException e) {
return null;
}
}
return doubleRecord;
}
private static List<List<DiagramGraph>> computeGraphGroups(DiagramGraph[] graphs) {
List<List<DiagramGraph>> graphGroups = new ArrayList<List<DiagramGraph>>(3);
for (DiagramGraph graph : graphs) {
boolean found = false;
for (List<DiagramGraph> graphGroup : graphGroups) {
if (equalXValues(graph, graphGroup.get(0))) {
graphGroup.add(graph);
found = true;
break;
}
}
if (!found) {
ArrayList<DiagramGraph> graphGroup = new ArrayList<DiagramGraph>(3);
graphGroup.add(graph);
graphGroups.add(graphGroup);
}
}
return graphGroups;
}
private static void writeGraphGroup(List<DiagramGraph> graphGroup, Writer writer) throws IOException {
DiagramGraph graph0 = graphGroup.get(0);
writer.write(graph0.getXName());
for (DiagramGraph graph : graphGroup) {
writer.write((int) '\t');
writer.write(graph.getYName());
}
writer.write((int) '\n');
int numValues = graph0.getNumValues();
for (int i = 0; i < numValues; i++) {
writer.write(String.valueOf(graph0.getXValueAt(i)));
for (DiagramGraph graph : graphGroup) {
writer.write((int) '\t');
writer.write(String.valueOf(graph.getYValueAt(i)));
}
writer.write((int) '\n');
}
}
public static boolean equalXValues(DiagramGraph g1, DiagramGraph g2) {
if (g1.getNumValues() != g2.getNumValues()) {
return false;
}
for (int i = 0; i < g1.getNumValues(); i++) {
if (Math.abs(g1.getXValueAt(i) - g2.getXValueAt(i)) > 1.0e-10) {
return false;
}
}
return true;
}
public static DiagramGraph[] readGraphs(Component parentComponent,
String title,
SnapFileFilter[] fileFilters,
PropertyMap preferences) {
File selectedFile = selectGraphFile(parentComponent, title, fileFilters, preferences, true);
if (selectedFile != null) {
try {
FileReader fileReader = new FileReader(selectedFile);
try {
return readGraphs(fileReader);
} finally {
fileReader.close();
}
} catch (IOException e) {
JOptionPane.showMessageDialog(parentComponent, "I/O error: " + e.getMessage());
}
}
return new DiagramGraph[0];
}
public static void writeGraphs(Component parentComponent,
String title,
SnapFileFilter[] fileFilters,
PropertyMap preferences,
DiagramGraph[] graphs) {
if (graphs.length == 0) {
JOptionPane.showMessageDialog(parentComponent, "Nothing to save.");
return;
}
File selectedFile = selectGraphFile(parentComponent, title, fileFilters, preferences, false);
if (selectedFile != null) {
try {
FileWriter fileWriter = new FileWriter(selectedFile);
try {
writeGraphs(graphs, fileWriter);
} finally {
fileWriter.close();
}
} catch (IOException e) {
JOptionPane.showMessageDialog(parentComponent, "I/O error: " + e.getMessage());
}
}
}
private static File selectGraphFile(Component parentComponent,
String title,
SnapFileFilter[] fileFilters,
PropertyMap preferences,
boolean open) {
String lastDirPath = preferences.getPropertyString(DIAGRAM_GRAPH_IO_LAST_DIR_KEY, ".");
SnapFileChooser fileChooser = new SnapFileChooser(new File(lastDirPath));
fileChooser.setAcceptAllFileFilterUsed(true);
fileChooser.setDialogTitle(title);
for (SnapFileFilter fileFilter : fileFilters) {
fileChooser.addChoosableFileFilter(fileFilter);
}
fileChooser.setFileFilter(fileFilters[0]);
if (open) {
fileChooser.setDialogType(SnapFileChooser.OPEN_DIALOG);
} else {
fileChooser.setDialogType(SnapFileChooser.SAVE_DIALOG);
}
File selectedFile;
while (true) {
int i = fileChooser.showDialog(parentComponent, null);
if (i == SnapFileChooser.APPROVE_OPTION) {
selectedFile = fileChooser.getSelectedFile();
if (open || !selectedFile.exists()) {
break;
}
i = JOptionPane.showConfirmDialog(parentComponent,
"The file\n" + selectedFile + "\nalready exists.\nOverwrite?",
"File exists", JOptionPane.YES_NO_CANCEL_OPTION);
if (i == JOptionPane.CANCEL_OPTION) {
// Canceled
selectedFile = null;
break;
} else if (i == JOptionPane.YES_OPTION) {
// Overwrite existing file
break;
}
} else {
// Canceled
selectedFile = null;
break;
}
}
if (selectedFile != null) {
preferences.setPropertyString(DIAGRAM_GRAPH_IO_LAST_DIR_KEY, selectedFile.getParent());
}
return selectedFile;
}
}
| 10,251 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DiagramAxis.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/diagram/DiagramAxis.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.ui.diagram;
import org.esa.snap.core.util.ObjectUtils;
import org.esa.snap.core.util.math.MathUtils;
import java.io.Serializable;
/**
* Represents an axis in a <code>{@link Diagram}</code>. By default an axis has no name, no units and a range set to
* (0,100).
*/
public class DiagramAxis implements Serializable {
private static final double[] _tickFactors = new double[]{1.0, 1.5, 2.0, 2.5, 4.0, 5.0, 7.5, 10.0};
private Diagram diagram;
private String name;
private String unit;
private double unitFactor;
private double minValue;
private double maxValue;
private int numMajorTicks;
private int numMinorTicks;
private boolean isMinToMax;
public DiagramAxis() {
this(null, null);
}
public DiagramAxis(String name, String unit) {
this.name = name;
this.unit = unit;
unitFactor = 1.0;
minValue = 0.0;
maxValue = 100.0;
numMajorTicks = 3;
numMinorTicks = 5;
isMinToMax = true;
}
public String getName() {
return name;
}
public Diagram getDiagram() {
return diagram;
}
public void setDiagram(Diagram diagram) {
this.diagram = diagram;
}
public void setName(String name) {
if (!ObjectUtils.equalObjects(this.name, name)) {
this.name = name;
invalidate();
}
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
if (!ObjectUtils.equalObjects(this.unit, unit)) {
this.unit = unit;
invalidate();
}
}
public double getUnitFactor() {
return unitFactor;
}
public void setUnitFactor(double unitFactor) {
if (this.unitFactor != unitFactor) {
this.unitFactor = unitFactor;
invalidate();
}
}
/**
* Sets if Axis increases from min to max or decreases max to min
* isMinToMax true if increases min to max
*/
public void setMinToMax(final boolean isMinToMax) {
this.isMinToMax = isMinToMax;
}
/**
* Does Axis increase from min to max or decrease max to min
* @return true if increases min to max
*/
public boolean isMinToMax() {
return isMinToMax;
}
public double getMinValue() {
return minValue;
}
public double getMaxValue() {
return maxValue;
}
public void setValueRange(double minValue, double maxValue) {
if (minValue >= maxValue) {
throw new IllegalArgumentException("minValue >= maxValue");
}
if (this.minValue != minValue || this.maxValue != maxValue) {
this.minValue = minValue;
this.maxValue = maxValue;
invalidate();
}
}
public int getNumMajorTicks() {
return numMajorTicks;
}
public void setNumMajorTicks(int numMajorTicks) {
if (numMajorTicks < 2) {
throw new IllegalArgumentException("numMajorTicks < 2");
}
if (this.numMajorTicks != numMajorTicks) {
this.numMajorTicks = numMajorTicks;
invalidate();
}
}
public int getNumMinorTicks() {
return numMinorTicks;
}
public void setNumMinorTicks(int numMinorTicks) {
if (numMinorTicks < 2) {
throw new IllegalArgumentException("numMinorTicks < 2");
}
if (this.numMinorTicks != numMinorTicks) {
this.numMinorTicks = numMinorTicks;
invalidate();
}
}
public double getMajorTickMarkDistance() {
return (getMaxValue() - getMinValue()) / (getNumMajorTicks() - 1);
}
public void setSubDivision(double minValue, double maxValue, int numMajorTicks, int numMinorTicks) {
setValueRange(minValue, maxValue);
setNumMajorTicks(numMajorTicks);
setNumMinorTicks(numMinorTicks);
}
public void setOptimalSubDivision(int numMajorTicksMin, int numMajorTicksMax, int numMinorTicks) {
final double oldMinValue = minValue;
final double oldMaxValue = maxValue;
final double oldDelta = oldMaxValue - oldMinValue;
double deltaDeltaMin = Double.MAX_VALUE;
int numMajorTicksOpt = numMajorTicks;
double newMinValueOpt = oldMinValue;
double newMaxValueOpt = oldMaxValue;
for (int numMajorTicks = numMajorTicksMin; numMajorTicks <= numMajorTicksMax; numMajorTicks++) {
final double tickDist = getOptimalTickDistance(oldMinValue, oldMaxValue, numMajorTicks);
final double newMinValue = adjustFloor(oldMinValue, tickDist);
final double newMaxValue = adjustCeil(oldMaxValue, tickDist);
final double newDelta = newMaxValue - newMinValue;
final double deltaDelta = Math.abs(newDelta - oldDelta);
if (deltaDelta < deltaDeltaMin) {
deltaDeltaMin = deltaDelta;
numMajorTicksOpt = numMajorTicks;
newMinValueOpt = newMinValue;
newMaxValueOpt = newMaxValue;
}
}
setSubDivision(newMinValueOpt, newMaxValueOpt, numMajorTicksOpt, numMinorTicks);
}
public static double getOptimalTickDistance(double minValue, double maxValue, int numMajorTicks) {
if (minValue >= maxValue) {
throw new IllegalArgumentException("minValue >= maxValue");
}
if (numMajorTicks < 2) {
throw new IllegalArgumentException("numMajorTicks < 2");
}
final double tickDist = (maxValue - minValue) / (numMajorTicks - 1);
final double oom = MathUtils.getOrderOfMagnitude(tickDist);
final double scale = Math.pow(10.0, oom);
double tickDistOpt = 0.0;
for (double tickFactor : _tickFactors) {
tickDistOpt = tickFactor * scale;
if (tickDistOpt >= tickDist) {
break;
}
}
return tickDistOpt;
}
private static double adjustCeil(double x, double dx) {
return Math.ceil(x / dx) * dx;
}
private static double adjustFloor(double x, double dx) {
return Math.floor(x / dx) * dx;
}
public String[] createTickmarkTexts() {
double roundFactor = MathUtils.computeRoundFactor(getMinValue(), getMaxValue(), 3);
return createTickmarkTexts(getMinValue(), getMaxValue(), getNumMajorTicks(), roundFactor);
}
private static String[] createTickmarkTexts(double min, double max, int n, double roundFactor) {
String[] texts = new String[n];
double x;
long xi;
for (int i = 0; i < n; i++) {
x = min + i * (max - min) / (n - 1);
x = MathUtils.round(x, roundFactor);
xi = (long) Math.floor(x);
if (x == xi) {
texts[i] = String.valueOf(xi);
} else {
texts[i] = String.valueOf(x);
}
}
return texts;
}
private void invalidate() {
if (diagram != null) {
diagram.invalidate();
}
}
}
| 7,853 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DiagramChangeListener.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/diagram/DiagramChangeListener.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.ui.diagram;
public interface DiagramChangeListener {
void diagramChanged(Diagram diagram);
}
| 841 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
FilteredListModel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/util/FilteredListModel.java | package org.esa.snap.ui.util;
import javax.swing.AbstractListModel;
import javax.swing.ListModel;
import javax.swing.SwingWorker;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import java.util.ArrayList;
// found at http://stackoverflow.com/questions/14758313/filtering-jlist-based-on-jtextfield
public class FilteredListModel<T> extends AbstractListModel {
public static interface Filter<T> {
boolean accept(T element);
}
private final ListModel<T> sourceModel;
private Filter<T> filter;
private final ArrayList<Integer> indices = new ArrayList<>();
public FilteredListModel(ListModel<T> source) {
if (source == null) {
throw new IllegalArgumentException("Source is null");
}
sourceModel = source;
sourceModel.addListDataListener(new ListDataListener() {
public void intervalRemoved(ListDataEvent e) {
doFilter();
}
public void intervalAdded(ListDataEvent e) {
doFilter();
}
public void contentsChanged(ListDataEvent e) {
doFilter();
}
});
}
public void setFilter(Filter<T> f) {
filter = f;
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
doFilter();
return null;
}
@Override
protected void done() {
fireContentsChanged(this, 0, getSize() - 1);
}
};
worker.execute();
}
private void doFilter() {
indices.clear();
Filter<T> f = filter;
if (f != null) {
int count = sourceModel.getSize();
for (int i = 0; i < count; i++) {
T element = sourceModel.getElementAt(i);
if (f.accept(element)) {
indices.add(i);
}
}
}
}
@Override
public int getSize() {
return (filter != null) ? indices.size() : sourceModel.getSize();
}
@Override
public T getElementAt(int index) {
return (filter != null) ? sourceModel.getElementAt(indices.get(index)) : sourceModel.getElementAt(index);
}
}
| 2,349 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CustomTextField.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/components/CustomTextField.java | package org.esa.snap.ui.components;
import org.esa.snap.ui.loading.SwingUtils;
import javax.swing.*;
import java.awt.*;
public class CustomTextField extends JTextField {
private final int preferredHeight;
public CustomTextField(int preferredHeight, Color backgroundColor) {
super();
if (preferredHeight <= 0) {
throw new IllegalArgumentException("The preferred size " + preferredHeight + " must be > 0.");
}
if (backgroundColor == null) {
throw new NullPointerException("The background color is null.");
}
this.preferredHeight = preferredHeight;
setBackground(backgroundColor);
setBorder(SwingUtils.LINE_BORDER);
}
@Override
public void setBounds(int x, int y, int width, int height) {
super.setBounds(x, y, width, this.preferredHeight);
}
@Override
public Dimension getMinimumSize() {
Dimension size = super.getMinimumSize();
size.height = this.preferredHeight;
return size;
}
@Override
public Dimension getMaximumSize() {
Dimension size = super.getMaximumSize();
size.height = this.preferredHeight;
return size;
}
@Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.height = this.preferredHeight;
return size;
}
}
| 1,403 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DatePickerComboBox.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/components/DatePickerComboBox.java | package org.esa.snap.ui.components;
import org.esa.snap.ui.loading.SwingUtils;
import org.jdesktop.swingx.JXMonthView;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.event.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
public class DatePickerComboBox extends JComboBox<Void> {
private final int preferredHeight;
private final DateFormat dateFormat;
private final JXMonthView monthView;
private final JPopupMenu popup;
public DatePickerComboBox(int preferredHeight, Color backgroundColor, DateFormat dateFormat) {
super();
if (preferredHeight <= 0) {
throw new IllegalArgumentException("The preferred size " + preferredHeight + " must be > 0.");
}
if (backgroundColor == null) {
throw new NullPointerException("The background color is null.");
}
if (dateFormat == null) {
throw new NullPointerException("The date format is null.");
}
this.preferredHeight = preferredHeight;
this.dateFormat = dateFormat;
setBackground(backgroundColor);
setBorder(SwingUtils.LINE_BORDER);
setEditable(true); // set the combo box as editable
this.monthView = new JXMonthView();
this.monthView.setTraversable(true);
this.monthView.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
newSelectedDate();
}
});
}
});
Date todayDate = new Date(System.currentTimeMillis());
String dateAsString = this.dateFormat.format(todayDate);
JLabel todayLabel = new JLabel("Today is " + dateAsString, JLabel.CENTER);
Border outsideBorder = new MatteBorder(1, 0, 0, 0, SwingUtils.LINE_BORDER.getLineColor());
Border insideBorder = new EmptyBorder(5, 0, 5, 0);
todayLabel.setBorder(new CompoundBorder(outsideBorder, insideBorder));
this.popup = new JPopupMenu();
this.popup.setLayout(new BorderLayout());
this.popup.add(this.monthView, BorderLayout.CENTER);
this.popup.add(todayLabel, BorderLayout.SOUTH);
this.popup.setBorder(SwingUtils.LINE_BORDER);
JComponent editorComponent = getEditorComponent();
editorComponent.setBorder(null);
editorComponent.setOpaque(false);
editorComponent.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
popup.setVisible(false);
}
});
replaceArrowButtonMouseListeners();
}
@Override
protected final void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
graphics.setColor(getBackground());
graphics.fillRect(0, 0, getWidth(), getHeight());
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
if (getEditor() != null && getEditor().getEditorComponent() != null) {
getEditor().getEditorComponent().setEnabled(enabled);
}
}
@Override
public void setBounds(int x, int y, int width, int height) {
super.setBounds(x, y, width, this.preferredHeight);
}
@Override
public Dimension getMinimumSize() {
Dimension size = super.getMinimumSize();
size.height = this.preferredHeight;
return size;
}
@Override
public Dimension getMaximumSize() {
Dimension size = super.getMaximumSize();
size.height = this.preferredHeight;
return size;
}
@Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.height = this.preferredHeight;
return size;
}
public void setDate(Date date) {
this.monthView.setSelectionDate(date);
String dateAsString = (date == null) ? "" : this.dateFormat.format(date);
getEditorComponent().setText(dateAsString);
}
public String getEnteredDateAsString() {
return getEditorComponent().getText().trim();
}
public Date getDate() {
String dateAsString = getEnteredDateAsString();
if (dateAsString.length() > 0) {
try {
return this.dateFormat.parse(dateAsString);
} catch (ParseException e) {
throw new IllegalStateException("Failed to parse the date '" + dateAsString+"'.", e);
}
}
return null;
}
private void newSelectedDate() {
String dateAsString = this.dateFormat.format(this.monthView.getSelectionDate());
getEditorComponent().setText(dateAsString);
this.popup.setVisible(false);
}
private JTextComponent getEditorComponent() {
return (JTextComponent)getEditor().getEditorComponent();
}
private void toggleShowPopup() {
if (this.popup.isVisible()) {
this.popup.setVisible(false);
} else {
String dateAsString = getEnteredDateAsString();
Date date = null;
if (dateAsString.length() > 0) {
try {
date = this.dateFormat.parse(dateAsString);
} catch (ParseException e) {
// failed to parse the date
getEditorComponent().setText("");
}
}
Date visibleDate = date;
if (visibleDate == null) {
visibleDate = new Date(System.currentTimeMillis());
}
this.monthView.setSelectionDate(date);
this.monthView.ensureDateVisible(visibleDate);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
DatePickerComboBox.this.popup.show(DatePickerComboBox.this, 0, DatePickerComboBox.this.getHeight());
}
});
}
}
private void replaceArrowButtonMouseListeners() {
int count = getComponentCount();
for (int i=0; i<count; i++) {
Component component = getComponent(i);
if (component instanceof JButton) {
JButton arrowButton = (JButton)component;
MouseListener[] mouseListeners = arrowButton.getMouseListeners();
if (mouseListeners.length >= 1) {
// remove the second mouse listener to avoid showing the popup containing the list
arrowButton.removeMouseListener(mouseListeners[1]);
}
arrowButton.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent mouseEvent) {
toggleShowPopup();
}
});
}
}
}
}
| 7,190 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ExploreTabs.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/ExploreTabs.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import com.arantius.tivocommander.rpc.MindRpc;
@SuppressWarnings("deprecation")
public class ExploreTabs extends TabActivity {
private String mCollectionId;
private String mContentId;
private String mOfferId;
private String mRecordingId;
private TabHost mTabHost;
private TabSpec makeTab(String name, Class<? extends Activity> cls, int iconId) {
TabSpec tab = mTabHost.newTabSpec(name);
tab.setIndicator(name, getResources().getDrawable(iconId));
Intent intent = new Intent(getBaseContext(), cls);
if (mCollectionId != null) {
intent.putExtra("collectionId", mCollectionId);
}
if (mContentId != null) {
intent.putExtra("contentId", mContentId);
}
if (mOfferId != null) {
intent.putExtra("offerId", mOfferId);
}
if (mRecordingId != null) {
intent.putExtra("recordingId", mRecordingId);
}
tab.setContent(intent);
return tab;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
// Put the URI details, if any, in the bundle. Where we'll read them
// later, even if MindRpc.init() restarts us with only bundle data.
Uri uri = getIntent().getData();
if (uri != null) {
uriToBundle(uri, bundle);
}
if (MindRpc.init(this, bundle)) {
return;
}
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.explore_tabs);
setTitle("Explore");
mTabHost = getTabHost();
try {
mCollectionId = bundle.getString("collectionId");
if ("tivo:cl.0".equals(mCollectionId)) {
mCollectionId = null;
}
} catch (NullPointerException e) {
mCollectionId = null;
}
try {
mContentId = bundle.getString("contentId");
} catch (NullPointerException e) {
mContentId = null;
}
try {
mOfferId = bundle.getString("offerId");
} catch (NullPointerException e) {
mOfferId = null;
}
try {
mRecordingId = bundle.getString("recordingId");
} catch (NullPointerException e) {
mRecordingId = null;
}
mTabHost.addTab(makeTab("Explore", Explore.class, R.drawable.icon_tv));
if (mCollectionId != null) {
mTabHost
.addTab(makeTab("Credits", Credits.class, R.drawable.icon_people));
mTabHost.addTab(makeTab("Similar", Suggestions.class,
R.drawable.icon_similar));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Utils.createFullOptionsMenu(menu, this);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return Utils.onOptionsItemSelected(item, this);
}
/** Parse a TiVo URL in a Uri object into an extras bundle. */
private void uriToBundle(Uri uri, Bundle bundle) {
final String[] keys = new String[] {
"collectionId", "contentId", "offerId",
};
for (String key : keys) {
String val = uri.getQueryParameter(key);
if (val != null) {
bundle.putString(key, val);
}
}
}
}
| 4,237 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
Person.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/Person.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.arantius.tivocommander.rpc.MindRpc;
import com.arantius.tivocommander.rpc.request.PersonCreditsSearch;
import com.arantius.tivocommander.rpc.request.PersonSearch;
import com.arantius.tivocommander.rpc.response.MindRpcResponse;
import com.arantius.tivocommander.rpc.response.MindRpcResponseListener;
import com.fasterxml.jackson.databind.JsonNode;
public class Person extends ListActivity {
// TODO: Refactor this to be DRY w/ Credits.
private class CreditsAdapter extends ArrayAdapter<JsonNode> {
private final JsonNode[] mCredits;
private final Drawable mDrawable;
private final int mResource;
public CreditsAdapter(Context context, int resource, JsonNode[] objects) {
super(context, resource, objects);
mCredits = objects;
mDrawable = context.getResources().getDrawable(R.drawable.content_banner);
mResource = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(mResource, null);
}
ImageView iv = (ImageView) v.findViewById(R.id.person_image);
View pv = v.findViewById(R.id.person_image_progress);
if (convertView != null) {
iv.setImageDrawable(mDrawable);
pv.setVisibility(View.VISIBLE);
v.findViewById(R.id.person_role).setVisibility(View.VISIBLE);
}
JsonNode item = mCredits[position];
if (item == null) {
return null;
}
if (iv != null) {
String imgUrl = Utils.findImageUrl(item);
new DownloadImageTask(Person.this, iv, pv).execute(imgUrl);
}
((TextView) v.findViewById(R.id.person_name)).setText(item.path("title")
.asText());
((TextView) v.findViewById(R.id.person_role)).setText(Utils
.ucFirst(findRole(item.path("credit"))));
// TODO: Can we display / sort by the year?
return v;
}
}
private JsonNode mCredits = null;
private String mName;
private final OnItemClickListener mOnItemClickListener =
new OnItemClickListener() {
public void onItemClick(android.widget.AdapterView<?> parent,
View view, int position, long id) {
JsonNode person = mCredits.path(position);
Intent intent = new Intent(getBaseContext(), ExploreTabs.class);
intent.putExtra("collectionId", person.path("collectionId")
.asText());
startActivity(intent);
}
};
private int mOutstandingRequests = 0;
private JsonNode mPerson = null;
private final MindRpcResponseListener mPersonCreditsListener =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
mCredits = response.getBody().path("collection");
requestFinished();
}
};
private String mPersonId;
private final MindRpcResponseListener mPersonListener =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
mPerson = response.getBody().path("person").path(0);
requestFinished();
}
};
private String findRole(JsonNode credits) {
for (JsonNode credit : credits) {
String x = credit.path("personId").asText();
if (mPersonId.equals(x)) {
return credit.path("role").asText();
}
}
return null;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
if (bundle == null) {
Utils.log("Person: null bundle!");
finish();
return;
}
MindRpc.init(this, bundle);
mName = bundle.getString("fName");
if (bundle.getString("lName") != null) {
mName += " " + bundle.getString("lName");
}
mPersonId = bundle.getString("personId");
Utils.log(String.format("Person: " + "name:%s personId:%s", mName,
mPersonId));
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.list);
MindRpc.addRequest(new PersonSearch(mPersonId), mPersonListener);
mOutstandingRequests++;
MindRpc.addRequest(new PersonCreditsSearch(mPersonId),
mPersonCreditsListener);
mOutstandingRequests++;
Utils.showProgress(this, true);
}
@Override
protected void onPause() {
super.onPause();
Utils.log("Activity:Pause:Person");
};
@Override
protected void onResume() {
super.onResume();
Utils.log("Activity:Resume:Person");
}
private void requestFinished() {
if (--mOutstandingRequests > 0) {
return;
}
Utils.showProgress(this, false);
if (mPerson == null || mCredits == null) {
setContentView(R.layout.no_results);
return;
}
setContentView(R.layout.list_person);
// Credits.
JsonNode[] credits = new JsonNode[mCredits.size()];
int i = 0;
for (JsonNode credit : mCredits) {
credits[i++] = credit;
}
ListView lv = getListView();
CreditsAdapter adapter =
new CreditsAdapter(Person.this, R.layout.item_person_credits, credits);
lv.setAdapter(adapter);
lv.setOnItemClickListener(mOnItemClickListener);
// Name.
((TextView) findViewById(R.id.person_name)).setText(mName);
// Role.
JsonNode rolesNode = mPerson.path("roleForPersonId");
String[] roles = new String[rolesNode.size()];
for (i = 0; i < rolesNode.size(); i++) {
roles[i] = rolesNode.path(i).asText();
roles[i] = Utils.ucFirst(roles[i]);
}
((TextView) findViewById(R.id.person_role))
.setText(Utils.join(", ", roles));
// Birth date.
TextView birthdateView = ((TextView) findViewById(R.id.person_birthdate));
if (mPerson.has("birthDate")) {
Date birthdate =
Utils.parseDateStr(mPerson.path("birthDate").asText());
SimpleDateFormat dateFormatter =
new SimpleDateFormat("MMMM d, yyyy", Locale.US);
dateFormatter.setTimeZone(TimeZone.getDefault());
Spannable birthdateStr =
new SpannableString("Birthdate: " + dateFormatter.format(birthdate));
birthdateStr.setSpan(new ForegroundColorSpan(Color.WHITE), 11,
birthdateStr.length(), 0);
birthdateView.setText(birthdateStr);
} else {
birthdateView.setVisibility(View.GONE);
}
// Birth place.
TextView birthplaceView = ((TextView) findViewById(R.id.person_birthplace));
if (mPerson.has("birthPlace")) {
Spannable birthplaceStr =
new SpannableString("Birthplace: "
+ mPerson.path("birthPlace").asText());
birthplaceStr.setSpan(new ForegroundColorSpan(Color.WHITE), 12,
birthplaceStr.length(), 0);
birthplaceView.setText(birthplaceStr);
} else {
birthplaceView.setVisibility(View.GONE);
}
ImageView iv = (ImageView) findViewById(R.id.person_image);
View pv = findViewById(R.id.person_image_progress);
String imgUrl = Utils.findImageUrl(mPerson);
new DownloadImageTask(this, iv, pv).execute(imgUrl);
}
}
| 8,740 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
ExploreCommon.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/ExploreCommon.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import com.arantius.tivocommander.rpc.MindRpc;
import com.arantius.tivocommander.rpc.request.CollectionSearch;
import com.arantius.tivocommander.rpc.request.ContentSearch;
import com.arantius.tivocommander.rpc.request.MindRpcRequest;
import com.arantius.tivocommander.rpc.request.RecordingSearch;
import com.arantius.tivocommander.rpc.response.MindRpcResponse;
import com.arantius.tivocommander.rpc.response.MindRpcResponseListener;
import com.fasterxml.jackson.databind.JsonNode;
abstract public class ExploreCommon extends Activity {
private final MindRpcResponseListener mListener =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
if ("error".equals(response.getBody().path("type").asText())) {
if ("staleData".equals(response.getBody().path("code"))) {
Utils.toast(ExploreCommon.this, "Stale data error, panicking.",
Toast.LENGTH_SHORT);
finish();
return;
}
}
JsonNode body = response.getBody();
if (body.has("collection")) {
mContent = response.getBody().path("collection").path(0);
} else if (body.has("recording")) {
mContent = response.getBody().path("recording").path(0);
} else if (body.has("content")) {
mContent = response.getBody().path("content").path(0);
} else {
Utils.toast(ExploreCommon.this, "Response missing content",
Toast.LENGTH_SHORT);
finish();
return;
}
onContent();
}
};
protected String mCollectionId = null;
protected JsonNode mContent = null;
protected String mContentId = null;
protected String mOfferId = null;
protected String mRecordingId = null;
protected MindRpcRequest getRequest() {
if (mRecordingId != null) {
return new RecordingSearch(mRecordingId);
} else if (mContentId != null) {
return new ContentSearch(mContentId);
} else if (mCollectionId != null) {
return new CollectionSearch(mCollectionId);
} else {
final String message = "Content: Bad input!";
Utils.toast(ExploreCommon.this, message, Toast.LENGTH_SHORT);
Utils.logError(message);
finish();
return null;
}
}
abstract protected void onContent();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
if (MindRpc.init(this, bundle))
return;
if (bundle != null) {
mCollectionId = bundle.getString("collectionId");
mContentId = bundle.getString("contentId");
mOfferId = bundle.getString("offerId");
mRecordingId = bundle.getString("recordingId");
}
if (getParent() == null) {
Utils.logError("Null getParent() in ExploreCommon.onCreate() ?!");
Utils.toast(this, R.string.unexpected_please_report, Toast.LENGTH_LONG);
finish();
return;
}
Utils.showProgress(getParent(), true);
MindRpcRequest req = getRequest();
MindRpc.addRequest(req, mListener);
}
protected void setRefreshResult() {
Intent resultIntent = new Intent();
resultIntent.putExtra("refresh", true);
getParent().setResult(Activity.RESULT_OK, resultIntent);
}
}
| 4,308 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
SubscribeCollection.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/SubscribeCollection.java | package com.arantius.tivocommander;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.TimeZone;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.arantius.tivocommander.rpc.MindRpc;
import com.arantius.tivocommander.rpc.request.OfferSearch;
import com.arantius.tivocommander.rpc.request.Subscribe;
import com.arantius.tivocommander.rpc.request.SubscriptionSearch;
import com.arantius.tivocommander.rpc.response.MindRpcResponse;
import com.arantius.tivocommander.rpc.response.MindRpcResponseListener;
import com.arantius.tivocommander.views.LinearListView;
import com.fasterxml.jackson.databind.JsonNode;
public class SubscribeCollection extends SubscribeBase {
private final static String[] mMaxLabels =
new String[] { "1 recorded show", "2 recorded shows", "3 recorded shows",
"4 recorded shows", "5 recorded shows", "10 recorded shows",
"25 recorded shows", "All shows" };
private final static Integer[] mMaxValues = new Integer[] { 1, 2, 3, 4, 5,
10, 25, 0 };
private final static String[] mWhichLabels = new String[] {
"Repeats & first-run", "First-run only", "All (with duplicates)" };
private final static String[] mWhichValues = new String[] { "rerunsAllowed",
"firstRunOnly", "everyEpisode" };
private JsonNode mChannel;
private String[] mChannelNames;
private final ArrayList<JsonNode> mChannelNodes = new ArrayList<JsonNode>();
private JsonNode mOffers;
private int mRequestCount = 0;
private String mCollectionId;
private int mMax;
private int mPriority = 0;
private JsonNode mSubscription = null;
private String mWhich;
private final MindRpcResponseListener mChannelsListener =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
mOffers = response.getBody().path("offerGroup");
mChannelNodes.clear();
mChannelNames = new String[mOffers.size()];
int i = 0;
for (JsonNode offer : mOffers) {
JsonNode channel = offer.path("example").path("channel");
mChannelNodes.add(channel);
mChannelNames[i++] =
channel.path("channelNumber").asText() + " "
+ channel.path("callSign").asText();
}
if (i == 0) {
Utils.toast(SubscribeCollection.this,
"Sorry: Couldn't find any channels to record that on.",
Toast.LENGTH_SHORT);
finish();
return;
}
finishRequest();
}
};
private final MindRpcResponseListener mSubscriptionListener =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
mSubscription = response.getBody().path("subscription").path(0);
finishRequest();
}
};
private HashMap<String, String> conflictListItem(JsonNode conflict,
String prefix, boolean fullDate, String titleField) {
HashMap<String, String> listItem = new HashMap<String, String>();
String title = conflict.path(titleField).asText();
if ("".equals(title) && "subtitle".equals(titleField)) {
title = conflict.path("title").asText();
}
listItem
.put(prefix + "show_name", title);
listItem.put(prefix + "channel",
conflict.path("channel").path("channelNumber").asText() + " "
+ conflict.path("channel").path("callSign").asText());
Date startTime =
Utils.parseDateTimeStr(conflict.path("startTime").asText());
SimpleDateFormat dateFormatter1 =
new SimpleDateFormat(fullDate ? "MMM dd h:mm - " : "h:mm - ",
Locale.US);
dateFormatter1.setTimeZone(TimeZone.getDefault());
String showTime = dateFormatter1.format(startTime);
Calendar endTime = Calendar.getInstance();
endTime.setTime(startTime);
endTime.add(Calendar.SECOND, conflict.path("duration").asInt());
SimpleDateFormat dateFormatter2 = new SimpleDateFormat("h:mm a", Locale.US);
dateFormatter2.setTimeZone(TimeZone.getDefault());
showTime += dateFormatter2.format(endTime.getTime());
listItem.put(prefix + "show_time", showTime);
return listItem;
}
private void doSubscribe(Boolean ignoreConflicts) {
final Subscribe request = new Subscribe();
final String subscriptionId = (mSubscription == null)
? null : mSubscription.path("subscriptionId").textValue();
request
.setCollection(mCollectionId, mChannel, mMax, mWhich, subscriptionId);
if (mSubscription != null && subscriptionId != null) {
request.setIgnoreConflicts(true);
request.setPriority(mSubscription.path("priority").asInt());
} else {
request.setIgnoreConflicts(ignoreConflicts);
request.setPriority(mPriority);
}
subscribeRequestCommon(request);
final ProgressDialog d = new ProgressDialog(this);
d.setIndeterminate(true);
d.setTitle("Subscribing ...");
d.setMessage("Saving season pass.");
d.setCancelable(false);
d.show();
MindRpc.addRequest(request, new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
if ("error".equals(response.getBody().path("type").asText())) {
final String msg = "Error making subscription: "
+ response.getBody().path("text").asText();
Utils.toast(SubscribeCollection.this, msg, Toast.LENGTH_SHORT);
d.dismiss();
finish();
} else if (response.getBody().has("conflicts")) {
d.dismiss();
handleConflicts(response.getBody().path("conflicts"));
} else if (response.getBody().has("subscription")) {
d.dismiss();
finish();
} else {
Utils.log("What kind of subscribe response is this??");
Utils.log(Utils.stringifyToPrettyJson(response.getBody()));
}
}
});
}
public void doSubscribe(View v) {
getValues();
doSubscribe(false);
}
public void doSubscribeAll(View v) {
// Conflict dialog. Either boost priority or, if we already did that, also
// ignore conflicts.
if (mPriority == 0) {
mPriority++;
doSubscribe(false);
} else {
doSubscribe(true);
}
}
public void doSubscribeAsIs(View v) {
// Conflict dialog, do a ignore-conflicts subscribe.
doSubscribe(true);
}
protected void finishRequest() {
if (--mRequestCount > 0) {
return;
}
setContentView(R.layout.subscribe_collection);
setUpSpinner(R.id.channel, mChannelNames);
setUpSpinner(R.id.record_which, mWhichLabels);
setUpSpinner(R.id.record_max, mMaxLabels);
setUpSpinner(R.id.until, mUntilLabels);
setUpSpinner(R.id.start, mStartLabels);
setUpSpinner(R.id.stop, mStopLabels);
// Set defaults.
((Spinner) findViewById(R.id.record_max)).setSelection(4);
// If known, set values from existing subscription.
if (mSubscription != null) {
final String thatChannelId =
mSubscription.path("idSetSource").path("channel")
.path("stationId").asText();
int i = 0;
for (JsonNode offer : mOffers) {
final String thisChannelId =
offer.path("example").path("channel")
.path("stationId").asText();
if (thatChannelId.equals(thisChannelId)) {
// Set spinner so it will save properly, then hide.
Spinner s = ((Spinner) findViewById(R.id.channel));
s.setSelection(i);
s.setVisibility(View.GONE);
// Set text view to display immutable (?) channel.
TextView tv = ((TextView) findViewById(R.id.channel_text));
tv.setText(mChannelNames[i]);
tv.setVisibility(View.VISIBLE);
break;
}
i++;
}
setSpinner(R.id.record_which, mWhichValues,
mSubscription.path("showStatus").asText());
setSpinner(R.id.record_max, mMaxValues,
mSubscription.path("maxRecordings").asInt());
setSpinner(R.id.until, mUntilValues,
mSubscription.path("keepBehavior").asText());
setSpinner(R.id.start, mStartStopValues,
mSubscription.path("startTimePadding").asInt());
setSpinner(R.id.stop, mStartStopValues,
mSubscription.path("endTimePadding").asInt());
}
}
@Override
protected void getValues() {
super.getValues();
int pos;
pos = ((Spinner) findViewById(R.id.channel)).getSelectedItemPosition();
try {
mChannel = mChannelNodes.get(pos);
} catch (IndexOutOfBoundsException e) {
Utils.log(Utils.join(" / ", mChannelNames));
Utils.logError("Couldn't get channel", e);
Utils.toast(this, "Oops, something weird happened with the channels.",
Toast.LENGTH_SHORT);
finish();
}
pos = ((Spinner) findViewById(R.id.record_max)).getSelectedItemPosition();
mMax = mMaxValues[pos];
pos = ((Spinner) findViewById(R.id.record_which)).getSelectedItemPosition();
mWhich = mWhichValues[pos];
}
private void handleConflicts(JsonNode conflicts) {
Utils.showProgress(this, false);
setContentView(R.layout.subscribe_conflicts);
if (mPriority == 1) {
findViewById(R.id.button_get_all).setVisibility(View.GONE);
}
// "Will Record" list.
ArrayList<HashMap<String, String>> willRecord =
new ArrayList<HashMap<String, String>>();
for (JsonNode conflict : conflicts.path("willGet")) {
HashMap<String, String> listItem =
conflictListItem(conflict, "", true, "subtitle");
willRecord.add(listItem);
}
LinearListView willLv = (LinearListView) findViewById(R.id.will_record);
willLv.setAdapter(new SimpleAdapter(this, willRecord,
R.layout.item_sub_base, new String[] { "channel", "show_name",
"show_time" }, new int[] { R.id.channel, R.id.show_name,
R.id.show_time }));
// "Will NOT Record" list.
ArrayList<HashMap<String, String>> willNotRecord =
new ArrayList<HashMap<String, String>>();
for (JsonNode conflict : conflicts.path("wontGet")) {
HashMap<String, String> listItem =
conflictListItem(conflict.path("losingOffer").path(0), "", true,
"subtitle");
listItem.putAll(conflictListItem(conflict.path("winningOffer").path(0),
"overlap_", false, "title"));
listItem.put("overlap_show_name",
"Overlaps with: " + listItem.get("overlap_show_name"));
willNotRecord.add(listItem);
}
for (JsonNode conflict : conflicts.path("willCancel")) {
HashMap<String, String> listItem =
conflictListItem(conflict.path("losingOffer").path(0), "", true,
"title");
listItem.putAll(conflictListItem(conflict.path("winningOffer").path(0),
"overlap_", false, "subtitle"));
listItem.put("overlap_show_name",
"Overlaps with: " + listItem.get("overlap_show_name"));
willNotRecord.add(listItem);
}
LinearListView willNotLv = (LinearListView) findViewById(R.id.wont_record);
willNotLv.setAdapter(new SimpleAdapter(this, willNotRecord,
R.layout.item_sub_wont, new String[] { "channel", "overlap_show_name",
"overlap_show_time", "show_name", "show_time" }, new int[] {
R.id.channel, R.id.overlap_show_name, R.id.overlap_show_time,
R.id.show_name, R.id.show_time }));
// TODO: Will clip list.
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
if (MindRpc.init(this, bundle)) {
return;
}
setContentView(R.layout.progress);
mCollectionId = bundle.getString("collectionId");
OfferSearch request = new OfferSearch();
request.setChannelsForCollection(mCollectionId);
mRequestCount++;
MindRpc.addRequest(request, mChannelsListener);
String subscriptionJson = bundle.getString("subscriptionJson");
if (subscriptionJson != null) {
mSubscription = Utils.parseJson(subscriptionJson);
mRequestCount++;
finishRequest();
} else {
mRequestCount++;
MindRpc.addRequest(new SubscriptionSearch(mCollectionId),
mSubscriptionListener);
}
}
@Override
protected void onPause() {
super.onPause();
Utils.log("Activity:Pause:SubscribeCollection");
}
@Override
protected void onResume() {
super.onResume();
Utils.log("Activity:Resume:SubscribeCollection");
MindRpc.init(this, getIntent().getExtras());
}
private void setSpinner(int spinnerId, Object[] values, Object value) {
int i = Arrays.asList(values).indexOf(value);
if (i != -1) {
((Spinner) findViewById(spinnerId)).setSelection(i);
}
}
}
| 13,055 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
Device.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/Device.java | package com.arantius.tivocommander;
public class Device {
public String addr = null;
public String device_name = null;
public Long id = null;
public String mak = null;
public Integer port = 1413;
public String tsn = "-";
}
| 246 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
SeasonPass.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/SeasonPass.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.arantius.tivocommander.rpc.MindRpc;
import com.arantius.tivocommander.rpc.request.SubscriptionSearch;
import com.arantius.tivocommander.rpc.request.SubscriptionsReprioritize;
import com.arantius.tivocommander.rpc.request.Unsubscribe;
import com.arantius.tivocommander.rpc.response.MindRpcResponse;
import com.arantius.tivocommander.rpc.response.MindRpcResponseListener;
import com.fasterxml.jackson.databind.JsonNode;
import com.mobeta.android.dslv.DragSortListView;
// TODO: This copies a lot from ShowList; be DRY?
public class SeasonPass extends ListActivity implements
OnItemLongClickListener, OnClickListener {
protected class SubscriptionAdapter extends ArrayAdapter<JsonNode> {
protected ColorDrawable mBlankLogoDrawable;
public SubscriptionAdapter() {
super(SeasonPass.this, 0, mSubscriptionData);
mBlankLogoDrawable = new ColorDrawable(0x00000000);
Rect r = new Rect(0, 0, 65, 55); // Logo images are 65x55 px.
mBlankLogoDrawable.setBounds(r);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (mSubscriptionStatus.get(position) == SubscriptionStatus.MISSING) {
// If the data for this position is missing, fetch it and more, if they
// exist, up to a limit of MAX_REQUEST_BATCH.
ArrayList<String> subscriptionIds = new ArrayList<String>();
ArrayList<Integer> slots = new ArrayList<Integer>();
int i = position;
while (i < mSubscriptionData.size()) {
if (mSubscriptionStatus.get(i) == SubscriptionStatus.MISSING) {
String subscriptionId = mSubscriptionIds.get(i);
subscriptionIds.add(subscriptionId);
slots.add(i);
mSubscriptionStatus.set(i, SubscriptionStatus.LOADING);
if (subscriptionIds.size() >= MAX_REQUEST_BATCH) {
break;
}
}
i++;
}
SubscriptionSearch req = new SubscriptionSearch(subscriptionIds);
mRequestSlotMap.put(req.getRpcId(), slots);
MindRpc.addRequest(req, mDetailCallback);
}
LayoutInflater vi =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (mSubscriptionStatus.get(position) == SubscriptionStatus.LOADED) {
// If this item is available, display it.
v = vi.inflate(R.layout.item_season_pass, parent, false);
v.setLayoutParams(new AbsListView.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
final JsonNode item = mSubscriptionData.get(position);
((TextView) v.findViewById(R.id.index)).setText(
Integer.toString(position + 1));
((TextView) v.findViewById(R.id.show_title)).setText(
Utils.stripQuotes(item.path("title").asText()));
((ImageView) v.findViewById(R.id.icon_until_deleted)).setVisibility(
"forever".equals(item.path("keepBehavior").asText())
? View.VISIBLE : View.GONE);
String keepNum =item.path("maxRecordings").asText();
if ("0".equals(keepNum)) {
keepNum = "all";
}
((TextView) v.findViewById(R.id.keep_num)).setText(keepNum);
final boolean newOnly =
"firstRunOnly".equals(item.path("showStatus").asText());
final int newOnlyVis = newOnly ? View.VISIBLE : View.GONE;
((TextView) v.findViewById(R.id.new_comma)).setVisibility(newOnlyVis);
((ImageView) v.findViewById(R.id.badge_new)).setVisibility(newOnlyVis);
((TextView) v.findViewById(R.id.new_only)).setVisibility(newOnlyVis);
TextView channelView = (TextView) v.findViewById(R.id.show_channel);
ImageView dragHandle = (ImageView) v.findViewById(R.id.drag_handle);
if (mInReorderMode) {
dragHandle.setVisibility(View.VISIBLE);
channelView.setVisibility(View.GONE);
} else {
dragHandle.setVisibility(View.GONE);
channelView.setVisibility(View.VISIBLE);
final JsonNode channel = item.path("idSetSource").path("channel");
channelView.setText(
channel.path("channelNumber").asText());
channelView
.setCompoundDrawables(null, null, null, mBlankLogoDrawable);
if (channel.has("logoIndex")) {
// Wish lists don't have channels, so get the image conditionally.
final String channelLogoUrl =
"http://" + MindRpc.mTivoDevice.addr + "/ChannelLogo/icon-" +
channel.path("logoIndex") + "-1.png";
new DownloadImageTask(SeasonPass.this, channelView)
.execute(channelLogoUrl);
}
}
} else {
// Otherwise give a loading indicator.
v = vi.inflate(R.layout.progress, parent, false);
}
return v;
}
}
protected enum SubscriptionStatus {
LOADED, LOADING, MISSING;
}
protected final static int MAX_REQUEST_BATCH = 5;
protected boolean mInReorderMode = false;
protected SubscriptionAdapter mListAdapter;
protected int mLongClickPosition;
protected final SparseArray<ArrayList<Integer>> mRequestSlotMap =
new SparseArray<ArrayList<Integer>>();
protected final ArrayList<JsonNode> mSubscriptionData =
new ArrayList<JsonNode>();
protected final ArrayList<String> mSubscriptionIds = new ArrayList<String>();
protected ArrayList<String> mSubscriptionIdsBeforeReorder =
new ArrayList<String>();
protected final ArrayList<SubscriptionStatus> mSubscriptionStatus =
new ArrayList<SubscriptionStatus>();
protected MindRpcResponseListener mDetailCallback =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
final JsonNode items = response.getBody().path("subscription");
ArrayList<Integer> slotMap =
mRequestSlotMap.get(response.getRpcId());
for (int i = 0; i < items.size(); i++) {
int pos = slotMap.get(i);
JsonNode item = items.get(i);
mSubscriptionData.set(pos, item);
mSubscriptionStatus.set(pos, SubscriptionStatus.LOADED);
}
mRequestSlotMap.remove(response.getRpcId());
mListAdapter.notifyDataSetChanged();
}
};
protected final OnItemClickListener mOnClickListener =
new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
final JsonNode item = mSubscriptionData.get(position);
if (item == null) {
return;
}
final String collectionId =
item.path("idSetSource").path("collectionId")
.asText();
if ("".equals(collectionId)) {
return;
}
Intent intent = new Intent(SeasonPass.this, ExploreTabs.class);
intent.putExtra("collectionId", collectionId);
startActivityForResult(intent, 1);
}
};
final protected DragSortListView.DropListener mOnDrop =
new DragSortListView.DropListener() {
public void drop(int from, int to) {
JsonNode item = mListAdapter.getItem(from);
mListAdapter.remove(item);
mListAdapter.insert(item, to);
String id = mSubscriptionIds.get(from);
mSubscriptionIds.remove(id);
mSubscriptionIds.add(to, id);
}
};
public void onClick(DialogInterface dialog, int which) {
JsonNode sub = mSubscriptionData.get(mLongClickPosition);
// TODO: De-dupe vs. Explore.doRecord().
switch (which) {
case 0:
Intent intent =
new Intent(getBaseContext(), SubscribeCollection.class);
intent.putExtra("collectionId",
sub.path("idSetSource").path("collectionId").asText());
intent.putExtra("subscriptionId", sub.path("subscriptionId").asText());
intent.putExtra("subscriptionJson", Utils.stringifyToJson(sub));
startActivity(intent);
break;
case 1:
Utils.showProgress(SeasonPass.this, true);
MindRpc.addRequest(new Unsubscribe(sub.path("subscriptionId").asText()),
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
Utils.showProgress(SeasonPass.this, false);
mSubscriptionData.remove(mLongClickPosition);
mSubscriptionIds.remove(mLongClickPosition);
mSubscriptionStatus.remove(mLongClickPosition);
mListAdapter.notifyDataSetChanged();
}
});
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
if (data.getBooleanExtra("refresh", false)) {
startRequest();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (MindRpc.init(this, null)) {
return;
}
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
Utils.activateHomeButton(this);
setTitle("Season Pass Manager");
setContentView(R.layout.list_season_pass);
mListAdapter = new SubscriptionAdapter();
setListAdapter(mListAdapter);
DragSortListView dslv = (DragSortListView) getListView();
dslv.setOnItemClickListener(mOnClickListener);
dslv.setDropListener(mOnDrop);
dslv.setLongClickable(true);
dslv.setOnItemLongClickListener(this);
startRequest();
}
protected void startRequest() {
mSubscriptionData.clear();
mSubscriptionIds.clear();
mSubscriptionStatus.clear();
MindRpcResponseListener idSequenceCallback =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
JsonNode body = response.getBody();
for (JsonNode node : body.path("objectIdAndType")) {
mSubscriptionIds.add(node.asText());
}
for (int i = 0; i < mSubscriptionIds.size(); i++) {
mSubscriptionData.add(null);
mSubscriptionStatus.add(SubscriptionStatus.MISSING);
}
mListAdapter.notifyDataSetChanged();
}
};
MindRpc.addRequest(new SubscriptionSearch(), idSequenceCallback);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Utils.createFullOptionsMenu(menu, this);
return true;
}
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
final JsonNode sub = mSubscriptionData.get(position);
final String subType = sub.path("idSetSource").path("type").asText();
if ("wishListSource".equals(subType)) {
return false;
}
mLongClickPosition = position;
final ArrayList<String> choices = new ArrayList<String>();
choices.add(Explore.RecordActions.SP_MODIFY.toString());
choices.add(Explore.RecordActions.SP_CANCEL.toString());
final ArrayAdapter<String> choicesAdapter =
new ArrayAdapter<String>(this, android.R.layout.select_dialog_item,
choices);
Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Operation?");
dialogBuilder.setAdapter(choicesAdapter, this);
AlertDialog dialog = dialogBuilder.create();
dialog.show();
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return Utils.onOptionsItemSelected(item, this);
}
@Override
protected void onPause() {
super.onPause();
Utils.log("Activity:Pause:SeasonPass");
}
@Override
protected void onResume() {
super.onResume();
Utils.log("Activity:Resume:SeasonPass");
if (MindRpc.init(this, null)) {
return;
}
}
public void reorderApply(View unusedView) {
Utils.log("SeasonPass::reorderApply() " + Boolean.toString(mInReorderMode));
boolean noChange = true;
ArrayList<String> subIds = new ArrayList<String>();
for (int i = 0; i < mSubscriptionIds.size(); i++) {
if (mSubscriptionIds.get(i) != mSubscriptionIdsBeforeReorder.get(i)) {
noChange = false;
}
subIds.add(mSubscriptionData.get(i).path("subscriptionId").asText());
}
final ProgressDialog d = new ProgressDialog(this);
final MindRpcResponseListener onReorderComplete =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
if (d.isShowing()) {
d.dismiss();
}
// Flip the buttons.
findViewById(R.id.reorder_enable).setVisibility(View.VISIBLE);
findViewById(R.id.reorder_apply).setVisibility(View.GONE);
// Turn off the drag handles.
mInReorderMode = false;
mListAdapter.notifyDataSetChanged();
}
};
if (noChange) {
// If there was no change, switch the UI back immediately.
onReorderComplete.onResponse(null);
} else {
// Otherwise show a dialog while we do the RPC.
d.setIndeterminate(true);
d.setTitle("Saving ...");
d.setMessage("Saving new season pass order. "
+ "Patience please, this takes a while.");
d.setCancelable(false);
d.show();
SubscriptionsReprioritize req = new SubscriptionsReprioritize(subIds);
MindRpc.addRequest(req, onReorderComplete);
}
}
public void reorderEnable(View unusedView) {
Utils
.log("SeasonPass::reorderEnable() " + Boolean.toString(mInReorderMode));
final ArrayList<String> subscriptionIds = new ArrayList<String>();
final ArrayList<Integer> slots = new ArrayList<Integer>();
int i = 0;
while (i < mSubscriptionData.size()) {
if (mSubscriptionStatus.get(i) == SubscriptionStatus.MISSING) {
String subscriptionId = mSubscriptionIds.get(i);
subscriptionIds.add(subscriptionId);
slots.add(i);
mSubscriptionStatus.set(i, SubscriptionStatus.LOADING);
}
i++;
}
final ProgressDialog d = new ProgressDialog(this);
final MindRpcResponseListener onAllPassesLoaded =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
if (response != null) {
mDetailCallback.onResponse(response);
}
d.dismiss();
// Save the state before ordering.
mSubscriptionIdsBeforeReorder.clear();
mSubscriptionIdsBeforeReorder.addAll(mSubscriptionIds);
// Flip the buttons.
findViewById(R.id.reorder_enable).setVisibility(View.GONE);
findViewById(R.id.reorder_apply).setVisibility(View.VISIBLE);
// Show the drag handles.
mInReorderMode = true;
mListAdapter.notifyDataSetChanged();
}
};
if (subscriptionIds.size() == 0) {
// No subscriptions need loading? Proceed immediately.
onAllPassesLoaded.onResponse(null);
} else {
// Otherwise, show dialog and start loading.
d.setIndeterminate(true);
d.setTitle("Preparing ...");
d.setMessage("Loading all season pass data.");
d.setCancelable(false);
d.show();
final SubscriptionSearch req = new SubscriptionSearch(subscriptionIds);
mRequestSlotMap.put(req.getRpcId(), slots);
MindRpc.addRequest(req, onAllPassesLoaded);
}
}
}
| 17,293 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
Explore.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/Explore.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.arantius.tivocommander.rpc.MindRpc;
import com.arantius.tivocommander.rpc.request.RecordingSearch;
import com.arantius.tivocommander.rpc.request.RecordingUpdate;
import com.arantius.tivocommander.rpc.request.SubscriptionSearch;
import com.arantius.tivocommander.rpc.request.UiNavigate;
import com.arantius.tivocommander.rpc.request.Unsubscribe;
import com.arantius.tivocommander.rpc.response.MindRpcResponse;
import com.arantius.tivocommander.rpc.response.MindRpcResponseListener;
import com.fasterxml.jackson.databind.JsonNode;
public class Explore extends ExploreCommon {
enum RecordActions {
DONT_RECORD("Don't record"), RECORD("Record this episode"), RECORD_STOP(
"Stop recording in progress"), SP_ADD("Add season pass"), SP_CANCEL(
"Cancel season pass"), SP_MODIFY("Modify season pass");
private final String mText;
private RecordActions(String text) {
mText = text;
}
@Override
public String toString() {
return mText;
}
}
private final MindRpcResponseListener mDeleteListener =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
Utils.showProgress(getParent(), false);
if (!("success".equals(response.getRespType()))) {
Utils.logError("Delete attempt failed!");
Utils.toast(Explore.this, "Delete failed!.", Toast.LENGTH_SHORT);
return;
}
setRefreshResult();
finish();
}
};
private final MindRpcResponseListener mRecordingListener =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
mRecording = response.getBody().path("recording").path(0);
mRecordingState = mRecording.path("state").asText();
mSubscriptionType = Utils.subscriptionTypeForRecording(mRecording);
finishRequest();
}
};
private final MindRpcResponseListener mSubscriptionListener =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
mSubscription = response.getBody().path("subscription").path(0);
if (mSubscription.isMissingNode()) {
mSubscription = null;
mSubscriptionId = null;
} else {
mSubscriptionId = mSubscription.path("subscriptionId").asText();
final String subType =
mSubscription.path("idSetSource").path("type").asText();
if ("seasonPassSource".equals(subType)) {
mSubscriptionType = SubscriptionType.SEASON_PASS;
} else if ("wishListSource".equals(subType)) {
mSubscriptionType = SubscriptionType.WISHLIST;
}
}
finishRequest();
}
};
private final ArrayList<String> mChoices = new ArrayList<String>();
private JsonNode mRecording = null;
private String mRecordingState = null;
private int mRequestCount = 0;
private SubscriptionType mSubscriptionType = null;
private JsonNode mSubscription = null;
private String mSubscriptionId = null;
public void doDelete(View v) {
// FIXME: Fails when deleting the currently-playing show.
Utils.showProgress(getParent(), true);
String newState = "deleted";
if (v.getId() == R.id.explore_btn_undelete) {
newState = "complete";
}
// (Un-)Delete the recording ...
final RecordingUpdate req = new RecordingUpdate(mRecordingId, newState);
MindRpc.addRequest(req, mDeleteListener);
}
public void doRecord(View v) {
ArrayAdapter<String> choicesAdapter =
new ArrayAdapter<String>(this, android.R.layout.select_dialog_item,
mChoices);
Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Operation?");
dialogBuilder.setAdapter(choicesAdapter,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int position) {
setRefreshResult();
String label = mChoices.get(position);
if (RecordActions.DONT_RECORD.toString().equals(label)) {
Utils.showProgress(getParent(), true);
MindRpc.addRequest(
new RecordingUpdate(mRecordingId, "cancelled"),
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
Utils.showProgress(getParent(), false);
ImageView iconSubType =
(ImageView) findViewById(R.id.icon_sub_type);
TextView textSubType =
(TextView) findViewById(R.id.text_sub_type);
iconSubType.setVisibility(View.GONE);
textSubType.setVisibility(View.GONE);
}
});
} else if (RecordActions.RECORD.toString().equals(label)) {
Intent intent =
new Intent(getBaseContext(), SubscribeOffer.class);
intent.putExtra("contentId", mContentId);
intent.putExtra("offerId", mOfferId);
startActivity(intent);
} else if (RecordActions.RECORD_STOP.toString().equals(label)) {
Utils.showProgress(getParent(), true);
MindRpc.addRequest(new RecordingUpdate(mRecordingId, "complete"),
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
Utils.showProgress(getParent(), false);
mRecordingId = null;
}
});
} else if (RecordActions.SP_ADD.toString().equals(label)) {
Intent intent =
new Intent(getBaseContext(), SubscribeCollection.class);
intent.putExtra("collectionId", mCollectionId);
startActivity(intent);
// TODO: Start for result, get subscription ID.
} else if (RecordActions.SP_CANCEL.toString().equals(label)) {
Utils.showProgress(getParent(), true);
MindRpc.addRequest(new Unsubscribe(mSubscriptionId),
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
Utils.showProgress(getParent(), false);
mSubscriptionId = null;
}
});
} else if (RecordActions.SP_MODIFY.toString().equals(label)) {
Intent intent =
new Intent(getBaseContext(), SubscribeCollection.class);
intent.putExtra("collectionId", mCollectionId);
intent.putExtra("subscriptionId", mSubscriptionId);
intent.putExtra("subscriptionJson",
Utils.stringifyToJson(mSubscription));
startActivity(intent);
}
}
});
AlertDialog dialog = dialogBuilder.create();
dialog.show();
}
public void doUpcoming(View v) {
Intent intent = new Intent(getBaseContext(), Upcoming.class);
intent.putExtra("collectionId", mCollectionId);
startActivity(intent);
}
public void doWatch(View v) {
MindRpc.addRequest(new UiNavigate(mRecordingId), null);
Intent intent = new Intent(this, NowShowing.class);
startActivity(intent);
}
protected void finishRequest() {
if (--mRequestCount != 0) {
return;
}
Utils.showProgress(getParent(), false);
if (mRecordingId == null) {
for (JsonNode recording : mContent.path("recordingForContentId")) {
String state = recording.path("state").asText();
if ("inProgress".equals(state) || "complete".equals(state)
|| "scheduled".equals(state)) {
mRecordingId = recording.path("recordingId").asText();
mRecordingState = state;
break;
}
}
}
// Fill mChoices based on the data we now have.
if ("scheduled".equals(mRecordingState)) {
mChoices.add(RecordActions.DONT_RECORD.toString());
} else if ("inProgress".equals(mRecordingState)) {
mChoices.add(RecordActions.RECORD_STOP.toString());
} else if (mOfferId != null) {
mChoices.add(RecordActions.RECORD.toString());
}
if (mSubscriptionId != null) {
mChoices.add(RecordActions.SP_MODIFY.toString());
mChoices.add(RecordActions.SP_CANCEL.toString());
} else if (mCollectionId != null
&& !"movie".equals(mContent.path("collectionType").asText())
&& !mContent.has("movieYear")) {
mChoices.add(RecordActions.SP_ADD.toString());
}
setContentView(R.layout.explore);
// Show only appropriate buttons.
findViewById(R.id.explore_btn_watch).setVisibility(
"complete".equals(mRecordingState)
|| "inprogress".equals(mRecordingState)
? View.VISIBLE : View.GONE);
hideViewIfNull(R.id.explore_btn_upcoming, mCollectionId);
if (mChoices.size() == 0) {
findViewById(R.id.explore_btn_record).setVisibility(View.GONE);
}
// Delete / undelete buttons visible only if appropriate.
findViewById(R.id.explore_btn_delete).setVisibility(
"complete".equals(mRecordingState) ? View.VISIBLE : View.GONE);
findViewById(R.id.explore_btn_undelete).setVisibility(
"deleted".equals(mRecordingState) ? View.VISIBLE : View.GONE);
// Display titles.
String title = mContent.path("title").asText();
String subtitle = mContent.path("subtitle").asText();
((TextView) findViewById(R.id.content_title)).setText(title);
TextView subtitleView = ((TextView) findViewById(R.id.content_subtitle));
if ("".equals(subtitle)) {
subtitleView.setVisibility(View.GONE);
} else {
subtitleView.setText(subtitle);
}
// Display (only the proper) badges.
if (mRecording != null
&& mRecording.path("episodic").asBoolean()
&& !mRecording.path("repeat").asBoolean()
) {
findViewById(R.id.badge_new).setVisibility(View.VISIBLE);
}
if (mRecording != null && mRecording.path("hdtv").asBoolean()) {
findViewById(R.id.badge_hd).setVisibility(View.VISIBLE);
}
ImageView iconSubType = (ImageView) findViewById(R.id.icon_sub_type);
TextView textSubType = (TextView) findViewById(R.id.text_sub_type);
// TODO: Downloading state?
if ("complete".equals(mRecordingState)) {
iconSubType.setVisibility(View.GONE);
textSubType.setVisibility(View.GONE);
} else if ("inProgress".equals(mRecordingState)) {
iconSubType.setImageResource(R.drawable.recording_recording);
textSubType.setText(R.string.sub_recording);
} else if (mSubscriptionType != null) {
switch (mSubscriptionType) {
case SEASON_PASS:
iconSubType.setImageResource(R.drawable.todo_seasonpass);
textSubType.setText(R.string.sub_season_pass);
break;
case SINGLE_OFFER:
iconSubType.setImageResource(R.drawable.todo_single_offer);
textSubType.setText(R.string.sub_single_offer);
break;
case WISHLIST:
iconSubType.setImageResource(R.drawable.todo_wishlist);
textSubType.setText(R.string.sub_wishlist);
break;
default:
iconSubType.setVisibility(View.GONE);
textSubType.setVisibility(View.GONE);
}
} else {
iconSubType.setVisibility(View.GONE);
textSubType.setVisibility(View.GONE);
}
// Display channel and time.
if (mRecording != null) {
String channelStr = "";
JsonNode channel = mRecording.path("channel");
if (!channel.isMissingNode()) {
channelStr =
String.format("%s %s, ", channel.path("channelNumber")
.asText(),
channel.path("callSign").asText());
}
// Lots of shows seem to be a few seconds short, add padding so that
// rounding down works as expected. Magic number.
final int minutes = (30 + mRecording.path("duration").asInt()) / 60;
String durationStr =
minutes >= 60 ? String.format(Locale.US, "%d hr", minutes / 60)
: String.format(Locale.US, "%d min", minutes);
if (isRecordingPartial()) {
durationStr += " (partial)";
}
((TextView) findViewById(R.id.content_chan_len)).setText(channelStr
+ durationStr);
String airTime = new SimpleDateFormat(
"EEE MMM d, hh:mm a", Locale.US).format(
Utils.parseDateTimeStr(
mRecording.path("actualStartTime").asText()));
((TextView) findViewById(R.id.content_air_time)).setText(
"Air time: " + airTime);
} else {
((TextView) findViewById(R.id.content_chan_len)).setVisibility(View.GONE);
((TextView) findViewById(R.id.content_air_time)).setVisibility(View.GONE);
}
// Construct and display details.
ArrayList<String> detailParts = new ArrayList<String>();
int season = mContent.path("seasonNumber").asInt();
int epNum = mContent.path("episodeNum").path(0).asInt();
if (season != 0 && epNum != 0) {
detailParts.add(String.format("Sea %d Ep %d", season, epNum));
}
if (mContent.has("mpaaRating")) {
detailParts.add(mContent.path("mpaaRating").asText()
.toUpperCase(Locale.US));
} else if (mContent.has("tvRating")) {
detailParts.add("TV-"
+ mContent.path("tvRating").asText().toUpperCase(Locale.US));
}
detailParts.add(mContent.path("category").path(0).path("label")
.asText());
int year = mContent.path("originalAirYear").asInt();
if (year != 0) {
detailParts.add(Integer.toString(year));
}
// Filter empty strings.
for (int i = detailParts.size() - 1; i >= 0; i--) {
if ("".equals(detailParts.get(i)) || null == detailParts.get(i)) {
detailParts.remove(i);
}
}
// Then format the parts into one string.
String detail1 = "(" + Utils.join(", ", detailParts) + ") ";
if ("() ".equals(detail1)) {
detail1 = "";
}
String detail2 = mContent.path("description").asText();
TextView detailView = ((TextView) findViewById(R.id.content_details));
if (detail2 == null) {
detailView.setText(detail1);
} else {
Spannable details = new SpannableString(detail1 + detail2);
details.setSpan(new ForegroundColorSpan(Color.WHITE), detail1.length(),
details.length(), 0);
detailView.setText(details);
}
// Add credits.
ArrayList<String> credits = new ArrayList<String>();
for (JsonNode credit : mContent.path("credit")) {
String role = credit.path("role").asText();
if ("actor".equals(role) || "host".equals(role)
|| "guestStar".equals(role)) {
credits.add(credit.path("first").asText() + " "
+ credit.path("last").asText());
}
}
TextView creditsView = (TextView) findViewById(R.id.content_credits);
creditsView.setText(Utils.join(", ", credits));
// Find and set the banner image if possible.
ImageView imageView = (ImageView) findViewById(R.id.content_image);
View progressView = findViewById(R.id.content_image_progress);
String imageUrl = Utils.findImageUrl(mContent);
new DownloadImageTask(this, imageView, progressView).execute(imageUrl);
}
private void hideViewIfNull(int viewId, Object condition) {
if (condition != null)
return;
findViewById(viewId).setVisibility(View.GONE);
}
private Boolean isRecordingPartial() {
final Date actualStart =
Utils.parseDateTimeStr(mRecording.path("actualStartTime")
.asText());
final Date scheduledStart =
Utils.parseDateTimeStr(mRecording.path("scheduledStartTime")
.asText());
final Date actualEnd =
Utils.parseDateTimeStr(mRecording.path("actualEndTime").asText());
final Date scheduledEnd =
Utils.parseDateTimeStr(mRecording.path("scheduledEndTime")
.asText());
return actualStart.getTime() - scheduledStart.getTime() >= 30000
|| scheduledEnd.getTime() - actualEnd.getTime() >= 30000;
}
@Override
protected void onContent() {
finishRequest();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.log(String.format("Explore: "
+ "contentId:%s collectionId:%s offerId:%s recordingId:%s", mContentId,
mCollectionId, mOfferId, mRecordingId));
// The one from ExploreCommon.
mRequestCount = 1;
if (mCollectionId != null) {
mRequestCount++;
MindRpc.addRequest(new SubscriptionSearch(mCollectionId),
mSubscriptionListener);
}
if (mRecordingId != null) {
mRequestCount++;
MindRpc.addRequest(new RecordingSearch(mRecordingId), mRecordingListener);
}
}
@Override
protected void onPause() {
super.onPause();
Utils.log("Activity:Pause:Explore");
}
@Override
protected void onResume() {
super.onResume();
Utils.log("Activity:Resume:Explore");
if (MindRpc.init(this, null)) {
return;
}
}
}
| 18,562 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
Suggestions.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/Suggestions.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.arantius.tivocommander.rpc.MindRpc;
import com.arantius.tivocommander.rpc.request.SuggestionsSearch;
import com.arantius.tivocommander.rpc.response.MindRpcResponse;
import com.arantius.tivocommander.rpc.response.MindRpcResponseListener;
import com.fasterxml.jackson.databind.JsonNode;
public class Suggestions extends Activity {
private class ShowAdapter extends ArrayAdapter<JsonNode> {
private final Drawable mDrawable;
private final JsonNode[] mShows;
public ShowAdapter(Context context, int resource, JsonNode[] objects) {
super(context, resource, objects);
mShows = objects;
mDrawable = context.getResources().getDrawable(R.drawable.content_banner);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.item_show, null);
}
ImageView iv = (ImageView) v.findViewById(R.id.image_show);
View pv = v.findViewById(R.id.image_show_progress);
if (convertView != null) {
iv.setImageDrawable(mDrawable);
pv.setVisibility(View.VISIBLE);
}
JsonNode item = mShows[position];
if (item == null) {
return null;
}
if (iv != null) {
String imgUrl = Utils.findImageUrl(item);
new DownloadImageTask(Suggestions.this, iv, pv).execute(imgUrl);
}
((TextView) v.findViewById(R.id.show_name)).setText(item.path("title")
.asText());
return v;
}
}
private final OnItemClickListener mOnItemClickListener =
new OnItemClickListener() {
public void onItemClick(android.widget.AdapterView<?> parent,
View view, int position, long id) {
String collectionId =
mShows.path(position).path("collectionId").asText();
Intent intent = new Intent(getBaseContext(), ExploreTabs.class);
intent.putExtra("collectionId", collectionId);
startActivity(intent);
}
};
protected JsonNode mShows;
private final MindRpcResponseListener mSuggestionListener =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
Utils.showProgress(getParent(), false);
mShows =
response.getBody().path("collection").path(0)
.path("correlatedCollectionForCollectionId");
if (mShows.size() == 0) {
setContentView(R.layout.no_results);
} else {
setContentView(R.layout.list_explore);
JsonNode[] shows = new JsonNode[mShows.size()];
int i = 0;
for (JsonNode show : mShows) {
shows[i++] = show;
}
ListView lv = (ListView) findViewById(R.id.list_explore);
ShowAdapter adapter =
new ShowAdapter(Suggestions.this, R.layout.item_show, shows);
lv.setAdapter(adapter);
lv.setOnItemClickListener(mOnItemClickListener);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
MindRpc.init(this, bundle);
String collectionId = null;
if (bundle != null) {
collectionId = bundle.getString("collectionId");
if (collectionId == null) {
Utils.toast(this, "Oops; missing collection ID", Toast.LENGTH_SHORT);
} else {
Utils.showProgress(getParent(), true);
SuggestionsSearch request = new SuggestionsSearch(collectionId);
MindRpc.addRequest(request, mSuggestionListener);
}
}
Utils.log(String.format("Suggestions: collectionId:%s", collectionId));
}
@Override
protected void onPause() {
super.onPause();
Utils.log("Activity:Pause:Suggestions");
}
@Override
protected void onResume() {
super.onResume();
Utils.log("Activity:Resume:Suggestions");
MindRpc.init(this, getIntent().getExtras());
}
}
| 5,460 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
Discover.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/Discover.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Pattern;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceInfo;
import javax.jmdns.ServiceListener;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.arantius.tivocommander.rpc.MindRpc;
public class Discover extends ListActivity implements OnItemClickListener,
ServiceListener, OnItemLongClickListener {
private static Database db;
private TextView mEmpty;
private SimpleAdapter mHostAdapter;
private volatile ArrayList<HashMap<String, Object>> mHosts =
new ArrayList<HashMap<String, Object>>();
private JmDNS mJmdns;
private MulticastLock mMulticastLock = null;
private final Pattern mPatternCompat = Pattern.compile(
"^("
+ "746|748|750|758|" // Series 4 DVRs
+ "A90|A92|A93|" // Series 4 non-DVRs (e.g. Mini)
+ "840|846|848|D18|" // Series 5 DVRs
+ "849" // Series 6 DVRs (i.e. Bolt)
+ ")");
private final Pattern mPatternNonCompat = Pattern.compile(
"^("
+ "110|240|540|649|" // Series 2 DVRs
+ "648|652|658|663|" // Series 3 DVRs
+ "B42|C00|C8A|CF0|E80" // Virgin Media
+ ")");
private final String mServiceNameRpc = "_tivo-mindrpc._tcp.local.";
private final String mServiceNameVideos = "_tivo-videos._tcp.local.";
private final String[] mServiceNames = new String[] {
mServiceNameRpc, mServiceNameVideos};
public final void customDevice(View v) {
editCustomDevice(new Device());
}
@SuppressLint("InflateParams")
public final void editCustomDevice(final Device device) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Custom Device");
final LayoutInflater inflater =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View dialogView = inflater.inflate(R.layout.device_custom, null);
builder.setView(dialogView);
final EditText input_name = (EditText) dialogView.findViewById(
R.id.input_name);
input_name.setText(device.device_name);
final EditText input_addr = (EditText) dialogView.findViewById(
R.id.input_addr);
input_addr.setText(device.addr);
final EditText input_mak = (EditText) dialogView.findViewById(
R.id.input_mak);
input_mak.setText(device.mak);
final EditText input_tsn = (EditText) dialogView.findViewById(
R.id.input_tsn);
input_tsn.setText(device.tsn);
final EditText input_port = (EditText) dialogView.findViewById(
R.id.input_port);
input_port.setText(device.port.toString());
final OnClickListener onClickListener =
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
device.device_name =
input_name
.getText().toString();
device.addr = ((EditText) dialogView.findViewById(R.id.input_addr))
.getText().toString();
device.mak = ((EditText) dialogView.findViewById(R.id.input_mak))
.getText().toString();
device.tsn = ((EditText) dialogView.findViewById(R.id.input_tsn))
.getText().toString();
if ("".equals(device.tsn))
device.tsn = "-";
final String portStr =
((EditText) dialogView.findViewById(R.id.input_port))
.getText().toString();
try {
device.port = Integer.parseInt(portStr);
} catch (NumberFormatException e) {
device.port = 1413;
}
db.saveDevice(device);
db.switchDevice(device);
Intent intent = new Intent(Discover.this, NowShowing.class);
startActivity(intent);
Discover.this.finish();
}
};
builder.setPositiveButton("OK", onClickListener);
builder.setNegativeButton("Cancel", null);
builder.create().show();
}
public final boolean onCreateOptionsMenu(Menu menu) {
Utils.createShortOptionsMenu(menu, this);
return true;
}
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
final HashMap<String, Object> item = mHosts.get(position);
int messageId = (Integer) item.get("messageId");
if (messageId > 0) {
showWarning(messageId, position);
} else {
onItemClickResume(position);
}
}
public void onItemClickResume(int position) {
final HashMap<String, Object> item = mHosts.get(position);
final Long deviceId = (Long) item.get("deviceId");
if (deviceId != null) {
final Device clickedDevice = db.getDevice(deviceId);
if (clickedDevice != null && !"".equals(clickedDevice.mak)) {
db.switchDevice(clickedDevice);
Intent intent = new Intent(Discover.this, NowShowing.class);
startActivity(intent);
this.finish();
return;
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("MAK");
builder.setMessage(R.string.pref_mak_instructions);
final EditText makEditText = new EditText(this);
makEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
builder.setView(makEditText);
// TODO: Be DRY vs. the same in customDevice().
final OnClickListener onClickListener =
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Device device = db.getNamedDevice(
(String) item.get("name"), (String) item.get("addr"));
if (device == null) device = new Device();
device.device_name = (String) item.get("name");
device.addr = (String) item.get("addr");
device.mak = makEditText.getText().toString();
device.tsn = "-";
try {
final String portStr = (String) item.get("port");
device.port = Integer.parseInt(portStr);
} catch (ClassCastException e) {
// I don't know why this is showing up, but handle it anyway.
device.port = (Integer) item.get("port");
}
db.saveDevice(device);
db.switchDevice(device);
Intent intent = new Intent(Discover.this, NowShowing.class);
startActivity(intent);
Discover.this.finish();
}
};
builder.setPositiveButton("OK", onClickListener);
builder.setNegativeButton("Cancel", null);
builder.create().show();
}
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
final HashMap<String, Object> item = mHosts.get(position);
final Long deviceId = (Long) item.get("deviceId");
if (deviceId == null) {
return false;
}
final Device device = db.getDevice(deviceId);
final ArrayList<String> choices = new ArrayList<String>();
choices.add("Edit");
choices.add("Delete");
ArrayAdapter<String> choicesAdapter =
new ArrayAdapter<String>(this, android.R.layout.select_dialog_item,
choices);
DialogInterface.OnClickListener onClickListener =
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int position) {
switch (position) {
case 0:
editCustomDevice(device);
break;
case 1:
db.deleteDevice(deviceId);
stopQuery();
startQuery(null);
break;
}
}
};
Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Operation?");
dialogBuilder.setAdapter(choicesAdapter, onClickListener);
dialogBuilder.create().show();
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return Utils.onOptionsItemSelected(item, this, true);
}
/** ServiceListener */
public void serviceAdded(ServiceEvent event) {
// Make sure serviceResolved() gets called.
event.getDNS().requestServiceInfo(event.getType(), event.getName());
}
/** ServiceListener */
public void serviceRemoved(ServiceEvent event) {
// Ignore.
}
/** ServiceListener */
public void serviceResolved(ServiceEvent event) {
ServiceInfo info = event.getInfo();
Utils.log("Discovery serviceResolved(): " + event.toString());
if (mJmdns == null) {
Utils.log("Ignoring because search is not running.");
return;
}
checkDevice(
event.getName().replaceAll(" \\(\\d\\)$", ""),
info.getHostAddresses()[0],
Integer.toString(info.getPort()),
info.getPropertyString("platform"),
info.getType(),
info.getPropertyString("TSN"));
}
public final void showHelp(View V) {
stopQuery();
Intent intent = new Intent(Discover.this, Help.class);
startActivity(intent);
}
public final void startQuery(View v) {
mHosts.clear();
mHostAdapter.notifyDataSetChanged();
// Add stored (i.e. custom) devices.
for (Device device : db.getDevices()) {
final HashMap<String, Object> listItem = new HashMap<String, Object>();
listItem.put("addr", device.addr);
listItem.put("deviceId", device.id);
listItem.put("messageId", -1);
listItem.put("name", device.device_name);
listItem.put("port", device.port.toString());
listItem.put("tsn", "-");
listItem.put("warn_icon", android.R.drawable.ic_menu_recent_history);
addDeviceMap(listItem);
}
final boolean haveStoredDevices = !mHosts.isEmpty();
// Skip mDNS discovery on BlackBerry.
final String osName = System.getProperty("os.name");
Utils.log("Discover; os.name = " + osName);
if ("qnx".equals(osName)) {
if (mHosts.size() == 0) {
Utils.toast(this, R.string.blackberry_discovery, Toast.LENGTH_LONG);
}
findViewById(R.id.refresh_button).setVisibility(View.GONE);
return;
}
stopQuery();
Utils.log("Start discovery query ...");
mEmpty.setText("Searching ...");
setProgressSpinner(true);
final Discover that = this;
Thread jmdnsThread = new Thread(new Runnable() {
public void run() {
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifi.getConnectionInfo();
Utils.log("Starting discovery via wifi: " + wifiInfo.toString());
int intaddr = wifiInfo.getIpAddress();
if (intaddr == 0) {
runOnUiThread(new Runnable() {
public void run() {
showWarning(R.string.error_get_wifi_addr, -1);
setProgressSpinner(false);
}
});
return;
}
// JmDNS wants an InetAddress; WifiInfo gives us an int. Convert.
byte[] byteaddr =
new byte[] { (byte) (intaddr & 0xff), (byte) (intaddr >> 8 & 0xff),
(byte) (intaddr >> 16 & 0xff), (byte) (intaddr >> 24 & 0xff) };
InetAddress addr;
try {
addr = InetAddress.getByAddress(byteaddr);
} catch (UnknownHostException e1) {
runOnUiThread(new Runnable() {
public void run() {
showHelp(R.string.error_get_wifi_addr);
}
});
finish();
return;
}
mMulticastLock =
wifi.createMulticastLock("DVR Commander for TiVo Lock");
mMulticastLock.setReferenceCounted(true);
try {
mMulticastLock.acquire();
} catch (UnsupportedOperationException e) {
showHelp(R.string.error_wifi_lock);
finish();
return;
}
try {
mJmdns = JmDNS.create(addr, "localhost");
} catch (IOException e1) {
setProgressSpinner(false);
if (!haveStoredDevices) {
runOnUiThread(new Runnable() {
public void run() {
showWarning(R.string.error_multicast, -1);
}
});
}
return;
}
for (String serviceName : mServiceNames) {
mJmdns.addServiceListener(serviceName, that);
}
}
});
jmdnsThread.start();
try {
jmdnsThread.join();
} catch (InterruptedException e1) {
Utils.logError("jmdns thread interrupted", e1);
}
// Test / mock data.
/*
checkDevice(
"TEST Pace MG1",
"127.0.0.2",
"1413",
"tcd/XG1",
mServiceNameRpc,
"D180509555840S2");
checkDevice(
"TEST Series 2",
"127.0.0.3",
"1413",
"tcd/Series2",
mServiceNameVideos,
"6490556Q5753378");
checkDevice(
"TEST Virgin Media",
"127.0.0.5",
"1413",
"tcd/VM",
mServiceNameRpc,
"B42bfedfbd02");
checkDevice(
"TEST No Net Control",
"127.0.0.6",
"1413",
"tcd/Series4",
mServiceNameVideos,
"758623bea591");
checkDevice(
"TEST Unknown",
"127.0.0.7",
"1413",
"tcd/SeriesQ",
mServiceNameRpc,
"QQQ129ae7882");
/**/
// Don't run for too long.
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
// Ignore.
}
stopQuery();
}
}).start();
}
private final void showHelp(int messageId) {
stopQuery();
String message = getResources().getString(messageId);
Utils.log("Showing help because:\n" + message);
Intent intent = new Intent(Discover.this, Help.class);
intent.putExtra("note", message);
startActivity(intent);
}
protected void addDeviceMap(final HashMap<String, Object> listItem) {
final String addr = (String) listItem.get("addr");
final String name = (String) listItem.get("name");
final int warnIcon = (Integer) listItem.get("warn_icon");
final int blank = R.drawable.blank;
Integer oldIndex = null;
for (HashMap<String, Object> host : mHosts) {
if (name.equals(host.get("name")) && addr.equals(host.get("addr"))) {
if (((Integer) host.get("warn_icon") != blank && warnIcon == blank)
|| (warnIcon == android.R.drawable.ic_menu_recent_history)
) {
oldIndex = mHosts.indexOf(host);
listItem.put("deviceId", host.get("deviceId"));
break;
} else {
Utils.log("Ignoring duplicate event.");
return;
}
}
}
final Integer newIndex = oldIndex; // Final copy that the runnable can see.
runOnUiThread(new Runnable() {
public void run() {
if (newIndex == null) {
// We didn't detect an item above as an update, and we didn't short-
// circuit to avoid duplicate events. So add a new item.
mHosts.add(listItem);
} else {
mHosts.set(newIndex, listItem);
}
// And make it visible in the UI either way.
mHostAdapter.notifyDataSetChanged();
};
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MindRpc.disconnect();
db = new Database(this);
setTitle("TiVo Device Search");
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.list_discover);
mEmpty = ((TextView) findViewById(android.R.id.empty));
mHostAdapter =
new SimpleAdapter(this, mHosts, R.layout.item_discover, new String[] {
"name", "warn_icon" },
new int[] { R.id.discover_name, R.id.discover_warn_icon });
setListAdapter(mHostAdapter);
final ListView lv = getListView();
lv.setOnItemClickListener(this);
lv.setOnItemLongClickListener(this);
Utils.activateHomeButton(this);
}
@Override
protected void onPause() {
super.onPause();
Utils.log("Activity:Pause:Discover");
stopQuery();
}
@Override
protected void onResume() {
super.onResume();
Utils.log("Activity:Resume:Discover");
startQuery(null);
}
protected void showWarning(int messageId, final int position) {
String message = getResources().getString(messageId);
Utils.log("Showing warning: " + message);
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Warning!");
alert.setMessage(message);
if (position >= 0 && messageIdIsMinor(messageId)) {
alert.setCancelable(true).setNegativeButton("Cancel", null)
.setPositiveButton("Try Anyway", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Utils.log("I foolishly clicked Try Anyway.");
onItemClickResume(position);
}
});
} else {
alert.setCancelable(false).setPositiveButton("OK", null);
}
alert.create().show();
}
protected final void stopQuery() {
runOnUiThread(new Runnable() {
public void run() {
setProgressSpinner(false);
if (mEmpty != null) {
mEmpty.setText("No results found.");
}
}
});
// JmDNS close seems to take ~6 seconds, so do that on a background thread.
if (mJmdns != null) {
Utils.log("Stop discovery query ...");
final JmDNS oldMdns = mJmdns;
mJmdns = null;
new Thread(new Runnable() {
public void run() {
try {
for (String serviceName : mServiceNames) {
oldMdns.removeServiceListener(serviceName, Discover.this);
}
oldMdns.close();
} catch (RuntimeException e) {
Utils.logError("Could not close JmDNS!", e);
} catch (IOException e) {
Utils.logError("Could not close JmDNS!", e);
}
}
}).start();
}
if (mMulticastLock != null) {
try {
mMulticastLock.release();
} catch (RuntimeException e) {
// Ignore. Likely
// "MulticastLock under-locked DVR Commander for TiVo Lock".
}
mMulticastLock = null;
}
}
void addDevice(
final String name, final String addr, final String port,
final String platform, final String type, final String tsn,
int messageId) {
final HashMap<String, Object> listItem = new HashMap<String, Object>();
listItem.put("addr", addr);
listItem.put("deviceId", null);
listItem.put("messageId", messageId);
listItem.put("name", name);
listItem.put("port", port);
listItem.put("tsn", tsn);
listItem.put(
"warn_icon",
messageId == 0
? R.drawable.blank
: messageIdIsMinor(messageId)
? android.R.drawable.ic_menu_help
: android.R.drawable.ic_dialog_alert);
addDeviceMap(listItem);
Device device = db.getDeviceByTsn(tsn);
if (device != null && device.addr != addr) {
// We've discovered a device already listed in the DB, and its address
// has changed (DHCP!!! *shake fist*). Update the DB so that future
// connections work as expected without forcing discovery.
device.addr = addr;
db.saveDevice(device);
}
}
void checkDevice(
final String name, final String addr, final String port,
final String platform, final String type, final String tsn) {
int messageId = 0;
SharedPreferences prefs
= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
if (mPatternCompat.matcher(tsn).find()) {
if (!mServiceNameRpc.equals(type)) {
messageId = R.string.error_net_control;
}
} else if (prefs.getBoolean("skip_compat", false)) {
messageId = R.string.device_compat_skip;
} else if (mPatternNonCompat.matcher(tsn).find()) {
messageId = R.string.device_unsupported;
} else {
messageId = R.string.device_unknown;
}
addDevice(name, addr, port, platform, type, tsn, messageId);
}
protected void setProgressSpinner(boolean running) {
Utils.showProgress(this, running);
View refreshButton = findViewById(R.id.refresh_button);
if (refreshButton != null) {
refreshButton.setEnabled(!running);
}
}
private boolean messageIdIsMinor(int messageId) {
return (messageId == R.string.device_unknown
|| messageId == R.string.device_compat_skip);
}
}
| 22,398 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
Help.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/Help.java | package com.arantius.tivocommander;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class Help extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.help);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
((TextView) findViewById(R.id.note)).setText(bundle.getString("note"));
findViewById(R.id.note).setVisibility(View.VISIBLE);
}
Utils.activateHomeButton(this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return Utils.onOptionsItemSelected(item, this, true);
}
@Override
protected void onPause() {
super.onPause();
Utils.log("Activity:Pause:Help");
}
@Override
protected void onResume() {
super.onResume();
Utils.log("Activity:Resume:Help");
}
public final void sendReport(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Help me help you!");
builder.setMessage(
"Sorry you're having trouble. But I'm just one guy, giving this app "
+ "away for free. Please help me help you: describe in detail "
+ "exactly what you did, and be prepared to answer my followup "
+ "questions.");
// TODO: Be DRY vs. the same in customDevice().
final OnClickListener onClickListener =
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
sendReport();
}
};
builder.setPositiveButton("OK", onClickListener);
builder.setNegativeButton("Cancel", null);
builder.create().show();
}
@SuppressLint("WorldReadableFiles")
void sendReport() {
Intent i = new Intent(Intent.ACTION_SEND_MULTIPLE);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[] { "[email protected]" });
i.putExtra(Intent.EXTRA_SUBJECT,
"Error Log " + Utils.getVersion(this) + " DVR Commander for TiVo");
i.putExtra(Intent.EXTRA_TEXT, "Please explain the problem here:\n\n");
final String error_text =
"Log data for the developer:\n\n"
+ "Version: " + Utils.getVersion(this) + "\n\n"
+ "Raw logs:\n" + Utils.logBufferAsString();
ArrayList<Uri> uris = new ArrayList<Uri>();
final String error_file_name = "error.txt";
try {
@SuppressWarnings("deprecation")
FileOutputStream outs = openFileOutput(
error_file_name, MODE_WORLD_READABLE);
outs.write(error_text.getBytes(Charset.forName("UTF-8")));
outs.close();
// http://stackoverflow.com/a/11955326/91238
String sdCard =
Environment.getExternalStorageDirectory().getAbsolutePath();
Uri uri = Uri.fromFile(new File(sdCard +
new String(new char[sdCard.replaceAll("[^/]", "").length()])
.replace("\0", "/..") + getFilesDir() + "/" + error_file_name));
uris.add(uri);
} catch (IOException e) {
Utils.logError("could not write error text", e);
i.putExtra(
Intent.EXTRA_TEXT,
error_text + "\n\nWrite error:\n" + e.toString()
);
}
File buildprop = new File("/system/build.prop");
if (buildprop.exists()) uris.add(Uri.fromFile(buildprop));
i.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
try {
this.startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Utils.toast(this, "There are no email clients installed.",
Toast.LENGTH_SHORT);
}
finish();
}
}
| 4,140 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
NowShowing.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/NowShowing.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.ViewFlipper;
import com.arantius.tivocommander.rpc.MindRpc;
import com.arantius.tivocommander.rpc.request.BodyConfigSearch;
import com.arantius.tivocommander.rpc.request.OfferSearch;
import com.arantius.tivocommander.rpc.request.RecordingSearch;
import com.arantius.tivocommander.rpc.request.VideoPlaybackInfoEventRegister;
import com.arantius.tivocommander.rpc.request.WhatsOnSearch;
import com.arantius.tivocommander.rpc.response.MindRpcResponse;
import com.arantius.tivocommander.rpc.response.MindRpcResponseListener;
import com.arantius.tivocommander.views.TivoScrubBar;
import com.fasterxml.jackson.databind.JsonNode;
public class NowShowing extends Activity {
private enum ContentType {
LIVE, RECORDING, TBA;
}
private class PlaybackRange {
public long absoluteBegin;
public long absoluteEnd;
public int activeMin;
public int progress;
public int activeMax;
public int max;
}
private final MindRpcResponseListener mBodyConfigCallback =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
final JsonNode bodyConfig =
response.getBody().path("bodyConfig").path(0);
MindRpc.saveBodyId(
bodyConfig.path("bodyId").asText(), NowShowing.this);
int gmtOffsetSeconds = bodyConfig.path("secondsFromGmt").asInt();
mGmtOffsetMillis = gmtOffsetSeconds * 1000;
rpcComplete();
}
};
private String mCollectionId = null;
private String mContentId = null;
private ContentType mContentType = null;
final private SimpleDateFormat mDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.US);
final private SimpleDateFormat mDisplayTimeFormat = new SimpleDateFormat(
"h:mm", Locale.US);
private String mOfferId = null;
private String mRecordingId = null;
private String mWhatsOnId = null;
private Integer mGmtOffsetMillis = null;
private Long mMillisActualBegin = null;
private Long mMillisContentBegin = null;
private Long mMillisContentEnd = null;
private Integer mMillisPosition = null;
private Integer mMillisRecordingBegin = null;
private Integer mMillisRecordingEnd = null;
private Long mMillisVirtualPosition = null;
private boolean mRpcComplete = false;
private TivoScrubBar mScrubBar = null;
private final MindRpcResponseListener mOfferCallback =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
if (response.getBody().path("offer").size() == 0) {
setTba();
return;
}
final JsonNode offer = response.getBody().path("offer").path(0);
final Integer durationSec = offer.path("duration").asInt();
final String startTimeStr = offer.path("startTime").asText();
if (durationSec == null || startTimeStr == null) {
setTba();
return;
}
setTitleFromContent(offer);
try {
Date beginDate = mDateFormat.parse(startTimeStr);
mMillisContentBegin = beginDate.getTime();
} catch (ParseException e) {
Utils.logError("Failed to parse start time " + startTimeStr, e);
mMillisContentBegin = 0L;
}
mMillisContentEnd = mMillisContentBegin + (durationSec * 1000);
rpcComplete();
};
};
private final MindRpcResponseListener mPlaybackInfoCallback =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
JsonNode playbackInfo = response.getBody();
mMillisPosition = playbackInfo.path("position").asInt();
mMillisRecordingBegin = playbackInfo.path("begin").asInt();
mMillisRecordingEnd = playbackInfo.path("end").asInt();
mMillisVirtualPosition =
playbackInfo.path("virtualPosition").asLong();
rpcComplete();
// Update these every time, not just the first via rpcComplete().
setScrubBar();
};
};
private final MindRpcResponseListener mRecordingCallback =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
JsonNode recording = response.getBody().path("recording").path(0);
setTitleFromContent(recording);
// The time that this recording actually started.
final String actualBeginTimeStr =
recording.path("actualStartTime").asText();
try {
mMillisActualBegin =
mDateFormat.parse(actualBeginTimeStr).getTime();
} catch (ParseException e) {
Utils.logError("Failed to parse start time " + actualBeginTimeStr,
e);
mMillisActualBegin = 0L;
}
// The time this recording (content?) was scheduled to begin.
final String beginTimeStr =
recording.path("scheduledStartTime").asText();
try {
mMillisContentBegin = mDateFormat.parse(beginTimeStr).getTime();
} catch (ParseException e) {
Utils.logError("Failed to parse start time " + beginTimeStr, e);
mMillisContentBegin = 0L;
}
// The time this recording (content?) was scheduled to end.
final String endTimeStr = recording.path("scheduledEndTime").asText();
try {
final Date endDate = mDateFormat.parse(endTimeStr);
mMillisContentEnd = endDate.getTime();
} catch (ParseException e) {
Utils.logError("Failed to parse start time " + endTimeStr, e);
mMillisContentEnd = 0L;
}
rpcComplete();
}
};
private final MindRpcResponseListener mWhatsOnCallback =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
JsonNode whatsOn = response.getBody().path("whatsOn").path(0);
String playbackType = whatsOn.path("playbackType").asText();
String whatsOnId = null;
if ("recording".equals(playbackType)) {
whatsOnId = whatsOn.path("recordingId").asText();
} else if ("liveCache".equals(playbackType)) {
whatsOnId = whatsOn.path("offerId").asText();
} else {
setTba();
return;
}
mScrubBar.setVisibility(View.VISIBLE);
mCollectionId = whatsOn.path("collectionId").textValue();
mContentId = whatsOn.path("contentId").textValue();
mOfferId = whatsOn.path("offerId").textValue();
mRecordingId = whatsOn.path("recordingId").textValue();
if (mWhatsOnId != null) {
// Ignore extra callbacks where the content has not changed.
if (mWhatsOnId.equals(whatsOnId)) {
return;
}
// Otherwise, start over with new requests and data.
initInstanceVars();
}
mWhatsOnId = whatsOnId;
((ViewFlipper) findViewById(R.id.now_showing_detail_flipper))
.setDisplayedChild(1);
if ("recording".equals(playbackType)) {
mContentType = ContentType.RECORDING;
RecordingSearch request = new RecordingSearch(whatsOnId);
request.setLevelOfDetail("low");
MindRpc.addRequest(request, mRecordingCallback);
} else if ("liveCache".equals(playbackType)) {
mContentType = ContentType.LIVE;
OfferSearch request = new OfferSearch("offerId", whatsOnId);
MindRpc.addRequest(request, mOfferCallback);
}
};
};
/**
* Calculate everything about the range we should display. Absolute start
* and end times of the whole bar, the active range that is recorded, and
* the progress through that range.
*/
private PlaybackRange getPlaybackRange() {
final int millisHalfHour = 1000 * 60 * 30;
PlaybackRange range = new PlaybackRange();
if (mMillisContentBegin == null || mMillisContentEnd == null) {
return null;
}
range.absoluteBegin = mMillisContentBegin;
range.absoluteEnd = mMillisContentEnd;
range.max = (int) (mMillisContentEnd - mMillisContentBegin);
if (mContentType == ContentType.LIVE) {
// TODO: Recording starts 1/2 hour+ after absolute begin.
range.progress = (int) (mMillisVirtualPosition - mMillisContentBegin);
range.activeMin = range.progress - mMillisPosition;
range.activeMax = range.activeMin + mMillisRecordingEnd;
// If the active range is too far from the content beginning, shrink
// the range to hold it.
while (range.activeMin > millisHalfHour) {
range.absoluteBegin += millisHalfHour;
range.activeMin -= millisHalfHour;
range.progress -= millisHalfHour;
range.activeMax -= millisHalfHour;
range.max -= millisHalfHour;
}
} else {
range.activeMin = (int) (mMillisActualBegin - mMillisContentBegin);
range.activeMax = range.activeMin + mMillisRecordingEnd;
range.progress = range.activeMin + mMillisPosition;
}
// If the recording extends beyond the scheduled period (by more than half
// a minute) extend the scrub bar by half an hour.
// TODO: Do these need to be whiles in case of big padding?
if (range.activeMin < -30000) {
Utils.logDebug(String.format(Locale.US,
"Adjusting beginning back becase %d << 0", range.activeMin));
range.absoluteBegin -= millisHalfHour;
// Since min must be 0, actually shift everything else forward.
range.max += millisHalfHour;
range.progress += millisHalfHour;
range.activeMin += millisHalfHour;
range.activeMax += millisHalfHour;
} else if (range.activeMin < 0) {
range.activeMin = 0;
}
if (range.activeMax > range.max + 30000) {
Utils.logDebug(String.format(Locale.US,
"Adjusting end forward becase %d >> %d", range.activeMax, range.max));
range.absoluteEnd += millisHalfHour;
range.max += millisHalfHour;
} else if (range.activeMax > range.max) {
range.activeMax = range.max;
}
return range;
}
/** (Re-)Initialize instance variables. */
private void initInstanceVars() {
mCollectionId = null;
mContentId = null;
mContentType = null;
mMillisActualBegin = null;
mMillisContentBegin = null;
mMillisContentEnd = null;
mOfferId = null;
mRecordingId = null;
mRpcComplete = false;
mWhatsOnId = null;
}
public void doExplore(View unused) {
if (mContentType == ContentType.TBA) {
return;
}
Intent intent = new Intent(this, ExploreTabs.class);
if (mCollectionId != null) {
intent.putExtra("collectionId", mCollectionId);
}
if (mContentId != null) {
intent.putExtra("contentId", mContentId);
}
if (mOfferId != null) {
intent.putExtra("offerId", mOfferId);
}
if (mRecordingId != null) {
intent.putExtra("recordingId", mRecordingId);
}
startActivity(intent);
}
public void onClickButton(View target) {
Intent intent = null;
switch (target.getId()) {
case R.id.target_remote:
intent = new Intent(getBaseContext(), Remote.class);
break;
case R.id.target_myshows:
intent = new Intent(getBaseContext(), MyShows.class);
break;
case R.id.target_search:
intent = new Intent(getBaseContext(), Search.class);
break;
case R.id.target_season_pass:
intent = new Intent(getBaseContext(), SeasonPass.class);
break;
case R.id.target_devices:
intent = new Intent(getBaseContext(), Discover.class);
break;
case R.id.target_todo:
intent = new Intent(getBaseContext(), ToDo.class);
break;
}
if (intent != null) {
startActivity(intent);
}
}
public void onClickRemote(View v) {
MindRpc.addRequest(Remote.viewIdToEvent(v.getId()), null);
}
public final boolean onCreateOptionsMenu(Menu menu) {
Utils.createShortOptionsMenu(menu, this);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return Utils.onOptionsItemSelected(item, this);
}
@Override
protected void onPause() {
super.onPause();
Utils.log("Activity:Pause:NowShowing");
MindRpc.cancelAll();
}
@Override
protected void onResume() {
super.onResume();
Utils.log("Activity:Resume:NowShowing");
if (MindRpc.init(this, null)) {
return;
}
setContentView(R.layout.now_showing);
setTitle("Now Showing");
mScrubBar = (TivoScrubBar) findViewById(R.id.tivo_scrub_bar);
TimeZone gmtTz = TimeZone.getTimeZone("GMT");
mDateFormat.setTimeZone(gmtTz);
// Turn on loading indicator.
((ViewFlipper) findViewById(R.id.now_showing_detail_flipper))
.setDisplayedChild(1);
initInstanceVars();
MindRpc.addRequest(new BodyConfigSearch(), mBodyConfigCallback);
WhatsOnSearch whatsOnRequest = new WhatsOnSearch();
MindRpc.addRequest(whatsOnRequest, mWhatsOnCallback);
VideoPlaybackInfoEventRegister playbackInfoRequest =
new VideoPlaybackInfoEventRegister(1001);
MindRpc.addRequest(playbackInfoRequest, mPlaybackInfoCallback);
}
/** After any given RPC completes, check state (given all) and continue. */
private void rpcComplete() {
// @formatter:off
if (mRpcComplete) return;
if (mContentType == ContentType.TBA) {
// No-op.
} else {
if (mGmtOffsetMillis == null) return;
if (mMillisContentBegin == null) return;
if (mMillisContentEnd == null) return;
if (mContentType == ContentType.RECORDING) {
if (mMillisActualBegin == null) return;
}
if (mMillisPosition == null) return;
if (mMillisRecordingBegin == null) return;
if (mMillisRecordingEnd == null) return;
if (mMillisVirtualPosition == null) return;
}
// @formatter:on
mRpcComplete = true;
// Run this for sure once.
setScrubBar();
// Then make them visible.
((ViewFlipper) findViewById(R.id.now_showing_detail_flipper))
.setDisplayedChild(0);
}
/** Set the start/end time labels of the seek bar. */
private void setScrubBar() {
if (!mRpcComplete) {
return;
}
if (mContentType == ContentType.TBA) {
mScrubBar.setVisibility(View.GONE);
return;
} else {
mScrubBar.setVisibility(View.VISIBLE);
}
PlaybackRange range = getPlaybackRange();
if (range == null) {
mScrubBar.setVisibility(View.GONE);
return;
}
String labelLeft = null;
String labelRight = null;
if (mContentType == ContentType.LIVE) {
// Show absolute start and end time.
labelLeft = mDisplayTimeFormat.format(new Date(range.absoluteBegin));
labelRight = mDisplayTimeFormat.format(new Date(range.absoluteEnd));
} else if (mContentType == ContentType.RECORDING) {
final int millis = (int) (mMillisContentEnd - mMillisContentBegin);
int minutes = (int) Math.ceil((millis) / (1000 * 60));
labelRight = "";
if (minutes >= 60) {
labelRight += String.format(Locale.US, "%dh", (minutes / 60));
}
minutes %= 60;
if (minutes != 0) {
if (!"".equals(labelRight)) {
labelRight += " ";
}
labelRight += String.format(Locale.US, "%dm", minutes);
}
}
mScrubBar.update(range.activeMin, range.progress, range.activeMax,
range.max, labelLeft, labelRight);
}
private void setTitleFromContent(JsonNode content) {
String title, movieYear, subtitle;
if (mContentType == ContentType.TBA) {
title = "To Be Announced";
subtitle = "No Information Available";
} else {
title = content.path("title").asText();
movieYear = content.path("movieYear").asText();
if (movieYear != null && !"".equals(movieYear)) {
title += " (" + movieYear + ")";
}
subtitle = content.path("subtitle").textValue();
}
TextView titleView = (TextView) findViewById(R.id.content_title);
TextView subtitleView = (TextView) findViewById(R.id.content_subtitle);
titleView.setText(title);
if (null == subtitle) {
subtitleView.setVisibility(View.GONE);
} else {
subtitleView.setVisibility(View.VISIBLE);
subtitleView.setText(subtitle);
}
}
protected void setTba() {
initInstanceVars();
mContentType = ContentType.TBA;
mWhatsOnId = null;
setTitleFromContent(null);
rpcComplete();
}
}
| 18,280 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
DownloadImageTask.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/DownloadImageTask.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
private final Context mContext;
private final ImageView mImageView;
private final View mProgressView;
private final TextView mTextView;
public DownloadImageTask(Context context, ImageView imageView,
View progressView) {
mContext = context;
mImageView = imageView;
mProgressView = progressView;
mTextView = null;
}
public DownloadImageTask(Context context, TextView textView) {
mContext = context;
mImageView = null;
mProgressView = null;
mTextView = textView;
}
@Override
protected Bitmap doInBackground(String... urls) {
if (urls[0] == null) {
return null;
}
URL url = null;
try {
url = new URL(urls[0]);
} catch (MalformedURLException e) {
Utils.logError("Parse URL; " + urls[0], e);
return null;
}
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setUseCaches(true);
conn.connect();
InputStream is = conn.getInputStream();
return BitmapFactory.decodeStream(is);
} catch (NullPointerException e) {
Utils.logError("Download URL; " + urls[0], e);
return null;
} catch (IOException e) {
Utils.logError("Download URL; " + urls[0], e);
return null;
}
}
@Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
BitmapDrawable d = new BitmapDrawable(mContext.getResources(), result);
if (mImageView != null) {
mImageView.setImageDrawable(d);
} else if (mTextView != null) {
mTextView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, d);
}
}
if (mProgressView != null) {
mProgressView.setVisibility(View.GONE);
}
}
}
| 3,098 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
Upcoming.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/Upcoming.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.arantius.tivocommander.rpc.MindRpc;
import com.arantius.tivocommander.rpc.request.RecordingUpdate;
import com.arantius.tivocommander.rpc.request.UpcomingSearch;
import com.arantius.tivocommander.rpc.response.MindRpcResponse;
import com.arantius.tivocommander.rpc.response.MindRpcResponseListener;
import com.fasterxml.jackson.databind.JsonNode;
public class Upcoming extends ListActivity implements OnItemClickListener,
OnItemLongClickListener {
private class DateInPast extends Throwable {
private static final long serialVersionUID = -4184008452910054505L;
}
protected SimpleAdapter mListAdapter;
protected JsonNode mShows;
private final MindRpcResponseListener mUpcomingListener =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
Utils.showProgress(Upcoming.this, false);
findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
mShows = response.getBody().path("offer");
List<HashMap<String, Object>> listItems =
new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < mShows.size(); i++) {
final JsonNode item = mShows.path(i);
try {
HashMap<String, Object> listItem = new HashMap<String, Object>();
String channelNum =
item.path("channel").path("channelNumber").asText();
String callSign =
item.path("channel").path("callSign").asText();
String details =
String.format("%s %s %s", formatTime(item), channelNum,
callSign);
if (item.path("episodic").asBoolean()
&& item.path("episodeNum").path(0).asInt() > 0
&& item.path("seasonNumber").asInt() > 0) {
details =
String.format("(Sea %d Ep %d) ", item.path("seasonNumber")
.asInt(), item.path("episodeNum").path(0)
.asInt())
+ details;
}
listItem.put("icon", R.drawable.blank);
if (item.has("recordingForOfferId")) {
listItem.put("icon", R.drawable.check);
}
listItem.put("details", details);
listItem.put("title", item.has("subtitle") ? item
.path("subtitle").asText() : item.path("title")
.asText());
listItem.put("index", Integer.valueOf(i));
listItems.add(listItem);
} catch (DateInPast e) {
// No-op. Just don't show past items.
}
}
final ListView lv = getListView();
mListAdapter = new SimpleAdapter(Upcoming.this, listItems,
R.layout.item_upcoming,
new String[] { "details", "icon", "title" }, new int[] {
R.id.upcoming_details, R.id.upcoming_icon,
R.id.upcoming_title });
lv.setAdapter(mListAdapter);
lv.setOnItemClickListener(Upcoming.this);
lv.setLongClickable(true);
lv.setOnItemLongClickListener(Upcoming.this);
}
};
protected String formatTime(JsonNode item) throws DateInPast {
String timeIn = item.path("startTime").asText();
if (timeIn == null) {
return null;
}
Date playTime = Utils.parseDateTimeStr(timeIn);
if (playTime.before(new Date())) {
throw new DateInPast();
}
SimpleDateFormat dateFormatter =
new SimpleDateFormat("EEE M/d hh:mm a", Locale.US);
dateFormatter.setTimeZone(TimeZone.getDefault());
return dateFormatter.format(playTime);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
MindRpc.init(this, bundle);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.list_empty);
findViewById(android.R.id.empty).setVisibility(View.GONE);
String collectionId = null;
if (bundle != null) {
collectionId = bundle.getString("collectionId");
if (collectionId == null) {
Utils.toast(this, "Oops; missing collection ID", Toast.LENGTH_SHORT);
} else {
Utils.showProgress(Upcoming.this, true);
UpcomingSearch request = new UpcomingSearch(collectionId);
MindRpc.addRequest(request, mUpcomingListener);
}
}
Utils.log(String.format("Upcoming: collectionId:%s", collectionId));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Utils.createFullOptionsMenu(menu, this);
return true;
}
protected JsonNode showItemFromListPosition(int position) {
@SuppressWarnings("unchecked")
final HashMap<String, Object> listItem =
(HashMap<String, Object>) mListAdapter.getItem(position);
final JsonNode show =
mShows.path(((Integer) listItem.get("index")).intValue());
return show;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// This should only come from a long-press "record" activity finishing.
// Refresh the whole thing to get the check. (Lazy and slow, but it works.)
startActivity(getIntent());
finish();
}
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
final JsonNode show = showItemFromListPosition(position);
Intent intent = new Intent(Upcoming.this, ExploreTabs.class);
intent.putExtra("contentId", show.path("contentId").asText());
intent.putExtra("collectionId", show.path("collectionId")
.asText());
intent.putExtra("offerId", show.path("offerId").asText());
startActivityForResult(intent, 1);
}
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
final JsonNode show = showItemFromListPosition(position);
final ArrayList<String> choices = new ArrayList<String>();
if (show.has("recordingForOfferId")) {
choices.add("Don't Record");
} else {
choices.add("Record");
}
ArrayAdapter<String> choicesAdapter =
new ArrayAdapter<String>(this, android.R.layout.select_dialog_item,
choices);
DialogInterface.OnClickListener onClickListener =
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int position) {
final String action = choices.get(position);
if ("Record".equals(action)) {
Intent intent =
new Intent(getBaseContext(), SubscribeOffer.class);
intent.putExtra("offerId", show.path("offerId").asText());
intent.putExtra("contentId", show.path("contentId").asText());
startActivityForResult(intent, 1);
} else if ("Don't Record".equals(action)) {
Utils.showProgress(Upcoming.this, true);
final String recordingId =
show.path("recordingForOfferId")
.path(0).path("recordingId").asText();
MindRpc.addRequest(
new RecordingUpdate(recordingId, "cancelled"),
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
// Refresh the whole thing, to remove the check.
// (Lazy and slow, but it works.)
startActivity(getIntent());
finish();
}
});
}
}
};
Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Operation?");
dialogBuilder.setAdapter(choicesAdapter, onClickListener);
dialogBuilder.create().show();
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return Utils.onOptionsItemSelected(item, this, true);
}
@Override
protected void onPause() {
super.onPause();
Utils.log("Activity:Pause:Upcoming");
}
@Override
protected void onResume() {
super.onResume();
Utils.log("Activity:Resume:Upcoming");
MindRpc.init(this, getIntent().getExtras());
}
}
| 9,887 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
Remote.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/Remote.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.arantius.tivocommander.rpc.MindRpc;
import com.arantius.tivocommander.rpc.request.KeyEventSend;
public class Remote extends Activity implements OnClickListener {
private EditText mEditText;
private InputMethodManager mInputManager;
private String mLastString = null;
private Vibrator mVibrator;
private final TextWatcher mTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// In case of screen rotation, Android restores the contents of the
// (hidden) EditText. Pull it out for no-change-change detection.
if (mLastString == null) {
mLastString = mEditText.getText().toString();
}
String newString = s.toString();
String oldString = new String(mLastString);
mLastString = newString;
if (newString.equals(oldString)) {
// No actual change; e.g. screen rotation fired a fake one.
return;
}
if (before > count) {
while (before > count) {
MindRpc.addRequest(viewIdToEvent(R.id.remote_reverse), null);
count++;
}
} else {
for (int i = start + before; i < start + count; i++) {
// TODO: Only send legal characters.
MindRpc.addRequest(new KeyEventSend(s.charAt(i)), null);
}
}
}
};
public void onClick(View v) {
if (v.getId() == R.id.remote_clear) {
mLastString = "";
mEditText.setText("");
}
boolean doVibrate =
PreferenceManager.getDefaultSharedPreferences(this.getBaseContext())
.getBoolean("remote_vibrate", true);
if (mVibrator != null && doVibrate) {
mVibrator.vibrate(15);
}
MindRpc.addRequest(viewIdToEvent(v.getId()), null);
}
public static KeyEventSend viewIdToEvent(int id) {
String eventStr = null;
// @formatter:off
switch (id) {
case R.id.remote_tivo: eventStr = "tivo"; break;
case R.id.remote_liveTv: eventStr = "liveTv"; break;
case R.id.remote_info: eventStr = "info"; break;
case R.id.remote_zoom: eventStr = "zoom"; break;
case R.id.remote_back: eventStr = "back"; break;
case R.id.remote_guide: eventStr = "guide"; break;
case R.id.remote_up: eventStr = "up"; break;
case R.id.remote_down: eventStr = "down"; break;
case R.id.remote_left: eventStr = "left"; break;
case R.id.remote_right: eventStr = "right"; break;
case R.id.remote_select: eventStr = "select"; break;
case R.id.remote_channelUp: eventStr = "channelUp"; break;
case R.id.remote_channelDown: eventStr = "channelDown"; break;
case R.id.remote_thumbsDown: eventStr = "thumbsDown"; break;
case R.id.remote_thumbsUp: eventStr = "thumbsUp"; break;
case R.id.remote_record: eventStr = "record"; break;
case R.id.remote_play: eventStr = "play"; break;
case R.id.remote_pause: eventStr = "pause"; break;
case R.id.remote_reverse: eventStr = "reverse"; break;
case R.id.remote_forward: eventStr = "forward"; break;
case R.id.remote_slow: eventStr = "slow"; break;
case R.id.remote_replay: eventStr = "replay"; break;
case R.id.remote_advance: eventStr = "advance"; break;
case R.id.remote_actionA: eventStr = "actionA"; break;
case R.id.remote_actionB: eventStr = "actionB"; break;
case R.id.remote_actionC: eventStr = "actionC"; break;
case R.id.remote_actionD: eventStr = "actionD"; break;
case R.id.remote_clear: eventStr = "clear"; break;
case R.id.remote_enter: eventStr = "enter"; break;
}
// @formatter:on
if (eventStr != null) {
return new KeyEventSend(eventStr);
}
char eventChar = '\0';
// @formatter:off
switch (id) {
case R.id.remote_num1: eventChar = '1'; break;
case R.id.remote_num2: eventChar = '2'; break;
case R.id.remote_num3: eventChar = '3'; break;
case R.id.remote_num4: eventChar = '4'; break;
case R.id.remote_num5: eventChar = '5'; break;
case R.id.remote_num6: eventChar = '6'; break;
case R.id.remote_num7: eventChar = '7'; break;
case R.id.remote_num8: eventChar = '8'; break;
case R.id.remote_num9: eventChar = '9'; break;
case R.id.remote_num0: eventChar = '0'; break;
}
// @formatter:on
if (eventChar != '\0') {
return new KeyEventSend(eventChar);
}
return null;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MindRpc.init(this, null);
setContentView(R.layout.remote);
setTitle("Remote");
// It says always, but it only suppresses the open-on-launch.
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
mEditText = (EditText) findViewById(R.id.keyboard_activator);
mEditText.addTextChangedListener(mTextWatcher);
mInputManager =
(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Utils.createFullOptionsMenu(menu, this);
return true;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
char sendChar = '\0';
if (KeyEvent.KEYCODE_0 <= keyCode && keyCode <= KeyEvent.KEYCODE_9) {
sendChar = (char) ((int) '0' + keyCode - KeyEvent.KEYCODE_0);
} else if (KeyEvent.KEYCODE_A <= keyCode && keyCode <= KeyEvent.KEYCODE_Z) {
sendChar = (char) ((int) 'a' + keyCode - KeyEvent.KEYCODE_A);
} else if (KeyEvent.KEYCODE_SPACE == keyCode) {
sendChar = ' ';
} else if (KeyEvent.KEYCODE_DEL == keyCode) {
MindRpc.addRequest(viewIdToEvent(R.id.remote_reverse), null);
return true;
}
if (sendChar != '\0') {
MindRpc.addRequest(new KeyEventSend(sendChar), null);
return true;
} else {
return super.onKeyUp(keyCode, event);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return Utils.onOptionsItemSelected(item, this);
}
@Override
protected void onPause() {
super.onPause();
Utils.log("Activity:Pause:Remote");
}
@Override
protected void onResume() {
super.onResume();
Utils.log("Activity:Resume:Remote");
MindRpc.init(this, null);
}
public void toggleKeyboard(View v) {
mEditText.setText("");
mEditText.requestFocus();
mInputManager.toggleSoftInputFromWindow(mEditText.getWindowToken(), 0, 0);
}
}
| 8,257 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
Connect.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/Connect.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.net.http.HttpResponseCache;
import android.os.Bundle;
import android.view.View;
import com.arantius.tivocommander.rpc.MindRpc;
public class Connect extends Activity {
private static Thread mConnectThread;
private static Thread mLimitThread;
private static Thread mShowCancelThread;
public void doCancel(View v) {
stopThreads();
Intent intent = new Intent(getBaseContext(), Discover.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
private void stopThreads() {
MindRpc.mConnectInterrupted = true;
if (mConnectThread != null) mConnectThread.interrupt();
if (mLimitThread != null) mLimitThread.interrupt();
if (mShowCancelThread != null) mShowCancelThread.interrupt();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.log("Activity:Create:Connect");
setContentView(R.layout.connect);
}
@Override
protected void onPause() {
super.onPause();
Utils.log("Activity:Pause:Connect");
}
@Override
protected void onResume() {
super.onResume();
Utils.log("Activity:Resume:Connect");
// However we're connecting, now is a good time to (re-)start caching.
HttpResponseCache cache = HttpResponseCache.getInstalled();
if (cache != null) {
cache.flush();
}
try {
File httpCacheDir = new File(this.getCacheDir(), "http");
long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (IOException e) {
Utils.logError("HTTP response cache installation failed:", e);
}
// Start on a separate thread so this UI shows immediately.
mConnectThread = new Thread(new Runnable() {
public void run() {
MindRpc.init3(Connect.this);
stopThreads();
}
});
// A second thread limits the infinite loop built in to the above.
mLimitThread = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
return;
}
// We were not interrupted, so we ran too long. Error.
doCancel(null);
Connect.this.overridePendingTransition(0, 0);
}
});
// While a third allows the user to cancel even sooner.
mShowCancelThread = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
return;
}
runOnUiThread(new Runnable() {
public void run() {
View b = findViewById(R.id.cancel);
if (b != null) {
b.setVisibility(View.VISIBLE);
}
}
});
}
});
mConnectThread.start();
mLimitThread.start();
mShowCancelThread.start();
}
}
| 3,864 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
Database.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/Database.java | package com.arantius.tivocommander;
import java.util.ArrayList;
import java.util.Locale;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.preference.PreferenceManager;
public class Database extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "dvr_commander";
private static final int DATABASE_VERSION = 1;
private static final String QUERY_SELECT_DEVICE =
"SELECT id, addr, device_name, mak, port, tsn FROM devices";
public Database(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
private Device deviceFromCursor(Cursor cursor) {
Device device = new Device();
device.id = Long.parseLong(cursor.getString(0));
device.addr = cursor.getString(1);
device.device_name = cursor.getString(2);
device.mak = cursor.getString(3);
device.port = Integer.parseInt(cursor.getString(4));
device.tsn = cursor.getString(5);
return device;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(
"CREATE TABLE devices ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "used_time INTEGER, "
+ "addr TEXT, "
+ "device_name TEXT, "
+ "mak TEXT, "
+ "port INTEGER, "
+ "tsn TEXT"
+ ");"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO
}
public void deleteDevice(Long id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete("devices", "id = ?", new String[] { String.valueOf(id) });
db.close();
}
public Device getDevice(final Long id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
QUERY_SELECT_DEVICE + " WHERE id = ?",
new String[] { id.toString() });
Device device = null;
if (cursor.moveToFirst()) {
device = deviceFromCursor(cursor);
}
db.close();
return device;
}
public Device getDeviceByTsn(final String tsn) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
QUERY_SELECT_DEVICE + " WHERE tsn = ?",
new String[] { tsn });
Device device = null;
if (cursor.moveToFirst()) {
device = deviceFromCursor(cursor);
}
db.close();
return device;
}
public ArrayList<Device> getDevices() {
ArrayList<Device> devices = new ArrayList<Device>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
QUERY_SELECT_DEVICE + " ORDER BY device_name ASC",
null);
if (cursor.moveToFirst()) {
do {
devices.add(deviceFromCursor(cursor));
} while (cursor.moveToNext());
}
db.close();
return devices;
}
public Device getLastUsedDevice() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
QUERY_SELECT_DEVICE + " ORDER BY used_time DESC LIMIT 1",
null);
Device device = null;
if (cursor.moveToFirst()) {
device = deviceFromCursor(cursor);
}
db.close();
return device;
}
public Device getNamedDevice(String name, String addr) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
QUERY_SELECT_DEVICE + " WHERE device_name = ? AND addr = ?"
+ " ORDER BY used_time DESC LIMIT 1",
new String[] { name, addr });
Device device = null;
if (cursor.moveToFirst()) {
device = deviceFromCursor(cursor);
}
db.close();
return device;
}
public void portLegacySettings(Context context) {
final SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(context);
if ("missing".equals(prefs.getString("tivo_addr", "missing"))) {
return;
}
Device device = new Device();
device.device_name = "Unknown";
device.addr = prefs.getString("tivo_addr", "");
device.port = Integer.parseInt(prefs.getString("tivo_port", "0"));
device.mak = prefs.getString("tivo_mak", "");
this.saveDevice(device);
// TODO: remove prefs
}
public void saveDevice(Device device) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("addr", device.addr);
values.put("device_name", device.device_name);
values.put("mak", device.mak);
values.put("port", device.port);
values.put("tsn", device.tsn);
if (device.id == null) {
long id = db.insertOrThrow("devices", null, values);
device.id = id;
} else {
db.update(
"devices", values,
"id = ?", new String[] { String.valueOf(device.id) });
}
db.close();
}
public void switchDevice(Device device) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("used_time", System.currentTimeMillis());
db.update(
"devices", values,
"id = ?", new String[] { String.valueOf(device.id) });
db.close();
Utils.log(String.format(
Locale.US,
"Switched to device: %s / %s / %d",
device.addr, device.device_name, device.id
));
}
}
| 5,589 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
Utils.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/Utils.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import java.io.IOException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Calendar;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
public class Utils {
public static boolean DEBUG_LOG = false;
public static int LOG_BUFFER_SIZE = 1000;
private static final String LOG_TAG = "tivo_commander";
private static final ArrayDeque<String> mLogBuffer = new ArrayDeque<String>(
LOG_BUFFER_SIZE);
private static final SimpleDateFormat mLogDateFormat =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US);
private static final ObjectMapper mMapper = new ObjectMapper();
private static final ObjectWriter mMapperPretty = mMapper
.writerWithDefaultPrettyPrinter();
@TargetApi(11)
public final static void activateHomeButton(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ActionBar ab = activity.getActionBar();
ab.setDisplayHomeAsUpEnabled(true);
}
}
private final static Class<? extends Activity> activityForMenuId(int menuId) {
switch (menuId) {
case android.R.id.home:
return NowShowing.class;
case R.id.menu_item_about:
return About.class;
case R.id.menu_item_settings:
return Settings.class;
case R.id.menu_item_devices:
return Discover.class;
case R.id.menu_item_help:
return Help.class;
case R.id.menu_item_remote:
return Remote.class;
case R.id.menu_item_my_shows:
return MyShows.class;
case R.id.menu_item_search:
return Search.class;
case R.id.menu_item_season_pass:
return SeasonPass.class;
case R.id.menu_item_todo:
return ToDo.class;
}
return null;
}
@SuppressLint("NewApi")
final static void addToMenu(Menu menu, Activity activity, int itemId,
int iconId, String title, int showAsAction) {
if (Utils.activityForMenuId(itemId) == activity.getClass()) {
return;
}
MenuItem menuitem = menu.add(Menu.NONE, itemId, Menu.NONE, title);
menuitem.setIcon(iconId);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
menuitem.setShowAsAction(showAsAction);
}
}
@SuppressLint("InlinedApi")
public final static void createFullOptionsMenu(Menu menu, Activity activity) {
Utils.activateHomeButton(activity);
addToMenu(menu, activity, R.id.menu_item_remote, R.drawable.icon_remote,
"Remote", MenuItem.SHOW_AS_ACTION_IF_ROOM);
addToMenu(menu, activity, R.id.menu_item_my_shows, R.drawable.icon_tv32,
"My Shows", MenuItem.SHOW_AS_ACTION_IF_ROOM);
addToMenu(menu, activity, R.id.menu_item_search, R.drawable.icon_search,
"Search", MenuItem.SHOW_AS_ACTION_IF_ROOM);
addToMenu(menu, activity, R.id.menu_item_todo, R.drawable.icon_todo,
"To Do List", MenuItem.SHOW_AS_ACTION_NEVER);
addToMenu(menu, activity, R.id.menu_item_season_pass,
R.drawable.icon_seasonpass,
"Season Pass Manager", MenuItem.SHOW_AS_ACTION_NEVER);
addToMenu(menu, activity, R.id.menu_item_devices, R.drawable.icon_devices,
"Devices", MenuItem.SHOW_AS_ACTION_NEVER);
addToMenu(menu, activity, R.id.menu_item_settings, R.drawable.icon_help,
"Settings", MenuItem.SHOW_AS_ACTION_NEVER);
addToMenu(menu, activity, R.id.menu_item_help, R.drawable.icon_help,
"Help", MenuItem.SHOW_AS_ACTION_NEVER);
addToMenu(menu, activity, R.id.menu_item_about, R.drawable.icon_info,
"About", MenuItem.SHOW_AS_ACTION_NEVER);
}
@SuppressLint("InlinedApi")
public final static void createShortOptionsMenu(Menu menu, Activity activity) {
addToMenu(menu, activity,
R.id.menu_item_settings, R.drawable.icon_cog,
"Settings", MenuItem.SHOW_AS_ACTION_NEVER);
addToMenu(menu, activity, R.id.menu_item_help, R.drawable.icon_help,
"Help", MenuItem.SHOW_AS_ACTION_NEVER);
addToMenu(menu, activity, R.id.menu_item_about, R.drawable.icon_info,
"About", MenuItem.SHOW_AS_ACTION_NEVER);
}
public static final String findImageUrl(JsonNode node) {
String url = null;
int biggestSize = 0;
int size = 0;
for (JsonNode image : node.path("image")) {
size = image.path("width").asInt() * image.path("height").asInt();
if (size > biggestSize) {
biggestSize = size;
url = image.path("imageUrl").asText();
}
}
return url;
}
public final static String getVersion(Context context) {
String version = " v";
try {
PackageManager pm = context.getPackageManager();
version += pm.getPackageInfo(context.getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
version = "";
}
return version;
}
public static final String join(String glue, List<String> strings) {
Iterator<String> it = strings.iterator();
StringBuilder out = new StringBuilder();
String s;
while (it.hasNext()) {
s = it.next();
if (s == null || s == "") {
continue;
}
out.append(s);
if (it.hasNext()) {
out.append(glue);
}
}
return out.toString();
}
public static final String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
public final static void log(String message) {
Log.i(LOG_TAG, message);
logAddToBuffer(message, "I");
}
public final static synchronized void logAddToBuffer(
String message, String level) {
mLogBuffer.add(
mLogDateFormat.format(Calendar.getInstance().getTime())
+ " " + level + " " + message);
while (mLogBuffer.size() >= LOG_BUFFER_SIZE) {
mLogBuffer.pop();
}
}
public final static synchronized String logBufferAsString() {
StringBuilder sb = new StringBuilder();
try {
for (Iterator<String> itr = mLogBuffer.iterator(); itr.hasNext();) {
sb.append(itr.next());
sb.append("\n");
}
} catch (ConcurrentModificationException e) {
sb.append("Concurrent modification!");
}
return sb.toString();
}
public final static void logDebug(String message) {
if (DEBUG_LOG) {
Log.d(LOG_TAG, message);
logAddToBuffer(message, "D");
}
}
public final static void logError(String message) {
Log.e(LOG_TAG, message);
logAddToBuffer(message, "E");
}
public final static void logError(String message, Throwable e) {
Log.e(LOG_TAG, message, e);
logAddToBuffer(message, "E");
logAddToBuffer(Log.getStackTraceString(e), "E");
}
public final static void logRpc(Object obj) {
String json = Utils.stringifyToPrettyJson(obj);
for (String line : json.split(System.getProperty("line.separator"))) {
Utils.logDebug(line);
}
}
public final static boolean onOptionsItemSelected(MenuItem item,
Activity srcActivity) {
return onOptionsItemSelected(item, srcActivity, false);
}
public final static boolean onOptionsItemSelected(MenuItem item,
Activity srcActivity, boolean homeIsBack) {
if (android.R.id.home == item.getItemId() && homeIsBack) {
srcActivity.finish();
return true;
}
Class<? extends Activity> targetActivity =
Utils.activityForMenuId(item.getItemId());
if (targetActivity == null) {
Utils.logError("Unknown menu item ID: "
+ Integer.toString(item.getItemId()));
return false;
}
Intent intent = new Intent(srcActivity, targetActivity);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
srcActivity.startActivity(intent);
return true;
}
public final static Date parseDateStr(String dateStr) {
SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
return parseDateTimeStr(dateParser, dateStr);
}
private final static Date parseDateTimeStr(SimpleDateFormat dateParser,
String dateStr) {
TimeZone tz = TimeZone.getTimeZone("UTC");
dateParser.setTimeZone(tz);
ParsePosition pp = new ParsePosition(0);
return dateParser.parse(dateStr, pp);
}
public final static Date parseDateTimeStr(String dateStr) {
SimpleDateFormat dateParser =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
return parseDateTimeStr(dateParser, dateStr);
}
public final static JsonNode parseJson(String json) {
try {
return mMapper.readValue(json, JsonNode.class);
} catch (JsonMappingException e) {
Log.e(LOG_TAG, "parseJson failure", e);
} catch (JsonParseException e) {
Log.e(LOG_TAG, "parseJson failure", e);
} catch (IOException e) {
Log.e(LOG_TAG, "parseJson failure", e);
}
logError("When parsing:\n" + json);
return null;
}
public final static void showProgress(Activity activity, boolean show) {
ViewGroup vg = (ViewGroup) activity.findViewById(android.R.id.content);
ProgressBar p = (ProgressBar) vg.findViewById(R.id.global_progress);
if (p == null) {
log("Creating missing progress bar.");
p = new ProgressBar(
activity, null, android.R.attr.progressBarStyleHorizontal);
p.setId(R.id.global_progress);
p.setIndeterminate(true);
p.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
vg.addView(p, 0);
}
log("For activity " + activity.getClass().getName()
+ " showing progress: " + show);
p.setVisibility(show ? View.VISIBLE : View.GONE);
}
public final static String stringifyToJson(Object obj) {
return stringifyToJson(obj, false);
}
private final static String stringifyToJson(Object obj, boolean pretty) {
try {
if (pretty) {
return mMapperPretty.writeValueAsString(obj);
} else {
return mMapper.writeValueAsString(obj);
}
} catch (JsonGenerationException e) {
Log.e(LOG_TAG, "stringifyToJson failure", e);
} catch (JsonMappingException e) {
Log.e(LOG_TAG, "stringifyToJson failure", e);
} catch (IOException e) {
Log.e(LOG_TAG, "stringifyToJson failure", e);
}
return null;
}
public final static String stringifyToPrettyJson(Object obj) {
return stringifyToJson(obj, true);
}
public final static String stripQuotes(String s) {
if (s.length() <= 1)
return s;
if ('"' == s.charAt(0) && '"' == s.charAt(s.length() - 1)) {
return s.substring(1, s.length() - 1);
}
return s;
}
public final static SubscriptionType subscriptionTypeForRecording(
JsonNode recording) {
if ("inProgress".equals(recording.path("state").asText())) {
return SubscriptionType.RECORDING;
}
String subType = recording.path("subscriptionIdentifier").path(0)
.path("subscriptionType").asText();
if ("seasonPass".equals(subType)) {
return SubscriptionType.SEASON_PASS;
} else if ("singleOffer".equals(subType)) {
return SubscriptionType.SINGLE_OFFER;
} else if ("wishList".equals(subType)) {
return SubscriptionType.WISHLIST;
} else {
logError("Unsupported subscriptionType string: " + subType);
return null;
}
}
public final static void toast(Activity activity, int messageId, int length) {
Context ctx = activity.getBaseContext();
Toast.makeText(ctx, messageId, length).show();
}
public final static void toast(Activity activity, String message, int length) {
Context ctx = activity.getBaseContext();
Toast.makeText(ctx, message, length).show();
}
public final static String ucFirst(String s) {
if (s == null) {
return null;
}
return s.substring(0, 1).toUpperCase(Locale.US) + s.substring(1);
}
}
| 13,579 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
SubscribeOffer.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/SubscribeOffer.java | package com.arantius.tivocommander;
import android.os.Bundle;
import android.view.View;
import com.arantius.tivocommander.rpc.MindRpc;
import com.arantius.tivocommander.rpc.request.Subscribe;
import com.arantius.tivocommander.rpc.response.MindRpcResponse;
import com.arantius.tivocommander.rpc.response.MindRpcResponseListener;
public class SubscribeOffer extends SubscribeBase {
public void doSubscribe(View v) {
getValues();
Subscribe request = new Subscribe();
Bundle bundle = getIntent().getExtras();
request
.setOffer(bundle.getString("offerId"), bundle.getString("contentId"));
subscribeRequestCommon(request);
Utils.showProgress(this, true);
MindRpc.addRequest(request, new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
finish();
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MindRpc.init(this, getIntent().getExtras());
setContentView(R.layout.subscribe_offer);
setUpSpinner(R.id.until, mUntilLabels);
setUpSpinner(R.id.start, mStartLabels);
setUpSpinner(R.id.stop, mStopLabels);
}
@Override
protected void onPause() {
super.onPause();
Utils.log("Activity:Pause:SubscribeOffer");
}
@Override
protected void onResume() {
super.onResume();
Utils.log("Activity:Resume:SubscribeOffer");
MindRpc.init(this, getIntent().getExtras());
}
}
| 1,469 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
Credits.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/Credits.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.arantius.tivocommander.rpc.MindRpc;
import com.arantius.tivocommander.rpc.request.BaseSearch;
import com.arantius.tivocommander.rpc.request.CreditsSearch;
import com.fasterxml.jackson.databind.JsonNode;
public class Credits extends ExploreCommon {
private class CreditsAdapter extends ArrayAdapter<JsonNode> {
private final JsonNode[] mCredits;
private final Drawable mPersonDrawable;
public CreditsAdapter(Context context, int resource, JsonNode[] objects) {
super(context, resource, objects);
mCredits = objects;
mPersonDrawable = context.getResources().getDrawable(R.drawable.person);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.item_credits, parent, false);
}
ImageView iv = (ImageView) v.findViewById(R.id.person_image);
View pv = v.findViewById(R.id.person_image_progress);
if (convertView != null) {
iv.setImageDrawable(mPersonDrawable);
pv.setVisibility(View.VISIBLE);
v.findViewById(R.id.person_name).setVisibility(View.VISIBLE);
}
JsonNode item = mCredits[position];
if (item == null) {
Utils.log("Get view; item for position " + Integer.toString(position)
+ " is null");
return null;
}
if (iv != null) {
String imgUrl = Utils.findImageUrl(item);
new DownloadImageTask(Credits.this, iv, pv).execute(imgUrl);
}
((TextView) v.findViewById(R.id.person_name)).setText(item.path("first")
.asText() + " " + item.path("last").asText());
if (item.has("characterName")) {
((TextView) v.findViewById(R.id.person_char)).setText("\""
+ item.path("characterName").asText() + "\"");
v.findViewById(R.id.person_char).setVisibility(View.VISIBLE);
} else {
v.findViewById(R.id.person_char).setVisibility(View.GONE);
}
String role = Utils.ucFirst(item.path("role").asText());
role = role.replaceAll("(?=[A-Z])", " ").trim();
((TextView) v.findViewById(R.id.person_role)).setText(role);
return v;
}
}
protected JsonNode mCredits;
private final OnItemClickListener mOnItemClickListener =
new OnItemClickListener() {
public void onItemClick(android.widget.AdapterView<?> parent,
View view, int position, long id) {
JsonNode person = mCredits.path(position);
Intent intent = new Intent(getBaseContext(), Person.class);
intent.putExtra("personId", person.path("personId").asText());
intent.putExtra("fName", person.path("first").asText());
intent.putExtra("lName", person.path("last").asText());
startActivity(intent);
}
};
@Override
protected BaseSearch getRequest() {
return new CreditsSearch(mCollectionId, mContentId);
}
@Override
protected void onContent() {
Utils.showProgress(getParent(), false);
mCredits = mContent.path("credit");
if (mCredits.size() == 0) {
setContentView(R.layout.no_results);
} else {
setContentView(R.layout.list_explore);
JsonNode[] credits = new JsonNode[mCredits.size()];
int i = 0;
for (JsonNode credit : mCredits) {
credits[i++] = credit;
}
setContentView(R.layout.list_explore);
ListView lv = (ListView) findViewById(R.id.list_explore);
CreditsAdapter adapter =
new CreditsAdapter(this, R.layout.item_credits, credits);
lv.setAdapter(adapter);
lv.setOnItemClickListener(mOnItemClickListener);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.log(String.format("Credits: "
+ "contentId:%s collectionId:%s offerId:%s recordingId:%s", mContentId,
mCollectionId, mOfferId, mRecordingId));
}
@Override
protected void onPause() {
super.onPause();
Utils.log("Activity:Pause:Credits");
}
@Override
protected void onResume() {
super.onResume();
Utils.log("Activity:Resume:Credits");
if (MindRpc.init(this, null)) {
return;
}
}
}
| 5,597 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
ShowList.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/ShowList.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Pair;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.arantius.tivocommander.rpc.MindRpc;
import com.arantius.tivocommander.rpc.request.MindRpcRequest;
import com.arantius.tivocommander.rpc.request.RecordingFolderItemSearch;
import com.arantius.tivocommander.rpc.request.RecordingSearch;
import com.arantius.tivocommander.rpc.request.RecordingUpdate;
import com.arantius.tivocommander.rpc.request.TodoRecordingSearch;
import com.arantius.tivocommander.rpc.request.UiNavigate;
import com.arantius.tivocommander.rpc.response.MindRpcResponse;
import com.arantius.tivocommander.rpc.response.MindRpcResponseListener;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
public abstract class ShowList extends ListActivity implements
OnItemLongClickListener, DialogInterface.OnClickListener {
protected class ShowsAdapter extends ArrayAdapter<JsonNode> {
protected Context mContext;
public ShowsAdapter(Context context) {
super(context, 0, mShowData);
mContext = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (mShowStatus.get(position) == ShowStatus.MISSING) {
// If the show for this position is missing, fetch it and more, if they
// exist, up to a limit of MAX_SHOW_REQUEST_BATCH.
ArrayList<JsonNode> showIds = new ArrayList<JsonNode>();
ArrayList<Integer> slots = new ArrayList<Integer>();
int i = position;
while (i < mShowStatus.size()) {
if (mShowStatus.get(i) == ShowStatus.MISSING) {
JsonNode showId = mShowIds.get(i);
if ("deleted".equals(showId.asText())) {
mShowData.set(i, mDeletedItem);
mShowStatus.set(i, ShowStatus.LOADED);
} else {
showIds.add(showId);
slots.add(i);
mShowStatus.set(i, ShowStatus.LOADING);
if (showIds.size() >= MAX_SHOW_REQUEST_BATCH) {
break;
}
}
}
i++;
}
// We could rarely have no shows, if the "recently deleted" item
// which we don't fetch falls right on the border.
if (showIds.size() > 0) {
MindRpcRequest req;
if (mContext instanceof ToDo) {
req = new TodoRecordingSearch(showIds, mOrderBy);
} else if (mContext instanceof MyShows) {
if ("deleted".equals(mFolderId)) {
req = new RecordingSearch(showIds);
} else {
req = new RecordingFolderItemSearch(showIds, mOrderBy);
}
} else {
Utils.logError("Unsupported context!");
return null;
}
mRequestSlotMap.put(req.getRpcId(), slots);
MindRpc.addRequest(req, mDetailCallback);
setProgressIndicator(1);
}
}
LayoutInflater vi =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (mShowStatus.get(position) == ShowStatus.LOADED) {
// If this item is available, display it.
v = vi.inflate(R.layout.item_my_shows, parent, false);
final JsonNode item = mShowData.get(position);
final JsonNode recording = getRecordingFromItem(item);
((TextView) v.findViewById(R.id.show_title)).setText(
Utils.stripQuotes(item.path("title").asText()));
Integer folderItemCount = item.path("folderItemCount").asInt();
((TextView) v.findViewById(R.id.folder_num))
.setText(folderItemCount > 0 ? folderItemCount.toString() : "");
String channelStr = "";
JsonNode channel = recording.path("channel");
if (folderItemCount == 0 && !channel.isMissingNode()) {
channelStr =
String.format("%s %s", channel.path("channelNumber")
.asText(), channel.path("callSign").asText());
}
((TextView) v.findViewById(R.id.show_channel)).setText(channelStr);
TextView episodeNumView = (TextView) v.findViewById(R.id.episode_num);
episodeNumView.setVisibility(View.GONE);
if (0 == folderItemCount && item != mDeletedItem) {
if (recording.has("hdtv") && recording.path("hdtv").asBoolean()) {
v.findViewById(R.id.badge_hd).setVisibility(View.VISIBLE);
}
if (recording.path("episodic").asBoolean()) {
if (!recording.path("repeat").asBoolean()) {
v.findViewById(R.id.badge_new).setVisibility(View.VISIBLE);
}
Integer seasonNum = recording.path("seasonNumber").asInt();
Integer episodeNum = recording.path("episodeNum").path(0).asInt();
if (seasonNum > 0 && episodeNum > 0) {
episodeNumView.setVisibility(View.VISIBLE);
episodeNumView.setText(String.format(
Locale.ENGLISH, "S%02dE%02d", seasonNum, episodeNum));
}
}
}
String startTimeStr = item.path("startTime").asText();
if ("".equals(startTimeStr)) {
// Rarely the time is only on the recording, not the item.
startTimeStr = recording.path("startTime").asText();
}
if ("".equals(startTimeStr)
|| "1970".equals(startTimeStr.substring(0, 4))) {
v.findViewById(R.id.show_time).setVisibility(View.GONE);
} else {
Date startTime = Utils.parseDateTimeStr(startTimeStr);
String timeFormat = "EEE M/d";
if (mContext instanceof ToDo) {
timeFormat += "\nh:mm aa";
}
SimpleDateFormat dateFormatter =
new SimpleDateFormat(timeFormat, Locale.US);
String timeStr = dateFormatter.format(startTime);
((TextView) v.findViewById(R.id.show_time)).setText(timeStr);
}
final int iconId = getIconForItem(item);
((ImageView) v.findViewById(R.id.show_icon))
.setImageDrawable(getResources().getDrawable(iconId));
final String subTitle = getSubTitleFromItem(item);
TextView subTitleView = (TextView) v.findViewById(R.id.sub_title);
if (subTitle != null && subTitle != "") {
subTitleView.setText(subTitle);
subTitleView.setVisibility(View.VISIBLE);
} else {
subTitleView.setVisibility(View.GONE);
}
} else {
// Otherwise give a loading indicator.
v = vi.inflate(R.layout.progress, parent, false);
}
return v;
}
}
protected enum ShowStatus {
LOADED, LOADING, MISSING;
}
protected final static int EXPECT_REFRESH_INTENT_ID = 1;
protected final static int MAX_SHOW_REQUEST_BATCH = 5;
protected final JsonNode mDeletedItem = Utils
.parseJson("{\"folderTransportType\":[\"deletedFolder\"]"
+ ",\"recordingFolderItemId\":\"deleted\""
+ ",\"title\":\"Recently Deleted\"}");
protected MindRpcResponseListener mDetailCallback;
protected String mFolderId;
protected MindRpcResponseListener mIdSequenceCallback;
protected ShowsAdapter mListAdapter;
protected int mLongPressIndex;
protected JsonNode mLongPressItem;
protected String mOrderBy = "startTime";
protected final String[] mOrderLabels = new String[] { "Date", "A-Z" };
protected final String[] mOrderValues = new String[] { "startTime", "title" };
protected int mRequestCount = 0;
protected final SparseArray<ArrayList<Integer>> mRequestSlotMap =
new SparseArray<ArrayList<Integer>>();
protected final ArrayList<JsonNode> mShowData = new ArrayList<JsonNode>();
protected ArrayNode mShowIds;
protected final ArrayList<ShowStatus> mShowStatus =
new ArrayList<ShowStatus>();
protected final OnItemClickListener mOnClickListener =
new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
final JsonNode item = mShowData.get(position);
if (item == null) {
return;
}
final JsonNode countNode = item.path("folderItemCount");
if (mDeletedItem == item
|| (countNode != null && countNode.asInt() > 0)) {
// Navigate to 'my shows' for this folder.
Intent intent = new Intent(ShowList.this, MyShows.class);
intent.putExtra("folderId", item.path("recordingFolderItemId")
.asText());
intent.putExtra("folderName", item.path("title").asText());
startActivityForResult(intent, EXPECT_REFRESH_INTENT_ID);
} else {
final JsonNode recording = getRecordingFromItem(item);
Intent intent = new Intent(ShowList.this, ExploreTabs.class);
intent.putExtra("contentId", recording.path("contentId")
.asText());
intent.putExtra("collectionId", recording.path("collectionId")
.asText());
// Regular / deleted recordings IDs are differently located.
if (item.has("childRecordingId")) {
intent.putExtra("recordingId", item.path("childRecordingId")
.asText());
} else if (item.has("recordingId")) {
intent.putExtra("recordingId", item.path("recordingId")
.asText());
}
startActivityForResult(intent, EXPECT_REFRESH_INTENT_ID);
}
}
};
protected abstract int getIconForItem(JsonNode item);
protected abstract Pair<ArrayList<String>, ArrayList<Integer>> getLongPressChoices(
JsonNode item);
protected abstract JsonNode getRecordingFromItem(JsonNode item);
protected abstract void startRequest();
protected String getSubTitleFromItem(JsonNode item) {
return null;
};
protected void finishWithRefresh() {
setRefreshResult();
finish();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
if (EXPECT_REFRESH_INTENT_ID == requestCode) {
if (data.getBooleanExtra("refresh", false)) {
setRefreshResult();
if (mShowData.size() == 1) {
// We deleted the last show! Go up a level.
finishWithRefresh();
} else {
// Load the list of remaining shows.
startRequest();
setRefreshResult();
}
}
}
};
public void onClick(DialogInterface dialog, int position) {
final Pair<ArrayList<String>, ArrayList<Integer>> choices =
getLongPressChoices(mLongPressItem);
Integer action = choices.second.get(position);
String recordingId = mLongPressItem.path("recordingId").asText();
MindRpcRequest req = null;
final MindRpcResponseListener reqListener =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
setProgressIndicator(-1);
// Now that it's probably changed, re-load the list.
startRequest();
}
};
final MindRpcResponseListener removeListener =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
setProgressIndicator(-1);
mShowData.remove(mLongPressIndex);
mShowIds.remove(mLongPressIndex);
mShowStatus.remove(mLongPressIndex);
if (mShowData.isEmpty()) {
finishWithRefresh();
return;
}
mListAdapter.notifyDataSetChanged();
}
};
MindRpcResponseListener listener = reqListener;
switch (action) {
case R.string.delete:
case R.string.stop_recording_and_delete:
req = new RecordingUpdate(recordingId, "deleted");
listener = removeListener;
setRefreshResult();
break;
case R.string.dont_record:
req = new RecordingUpdate(recordingId, "cancelled");
listener = removeListener;
setRefreshResult();
break;
case R.string.stop_recording:
case R.string.undelete:
req = new RecordingUpdate(recordingId, "complete");
setRefreshResult();
break;
case R.string.watch_now:
req = new UiNavigate(recordingId);
listener =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
setProgressIndicator(-1);
Intent intent = new Intent(ShowList.this, NowShowing.class);
startActivity(intent);
}
};
break;
}
setProgressIndicator(1);
MindRpc.addRequest(req, listener);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this);
mOrderBy = sharedPrefs.getString("my_shows_order_by", mOrderBy);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Utils.createFullOptionsMenu(menu, this);
return true;
}
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
if (position > mShowData.size()) {
return false;
}
if (mShowStatus.get(position) != ShowStatus.LOADED) {
return false;
}
mLongPressIndex = position;
mLongPressItem = mShowData.get(position);
if (mLongPressItem.has("recordingForChildRecordingId")
&& !mLongPressItem.has("folderType")) {
mLongPressItem = mLongPressItem.path("recordingForChildRecordingId");
}
final Pair<ArrayList<String>, ArrayList<Integer>> choices =
getLongPressChoices(mLongPressItem);
if (choices == null) {
return false;
}
final ArrayAdapter<String> choicesAdapter =
new ArrayAdapter<String>(this, android.R.layout.select_dialog_item,
choices.first);
Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Operation?");
dialogBuilder.setAdapter(choicesAdapter, this);
AlertDialog dialog = dialogBuilder.create();
dialog.show();
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return Utils.onOptionsItemSelected(item, this);
}
protected void setProgressIndicator(int change) {
mRequestCount += change;
Utils.showProgress(this, mRequestCount > 0);
}
protected void setRefreshResult() {
Intent resultIntent = new Intent();
resultIntent.putExtra("refresh", true);
setResult(Activity.RESULT_OK, resultIntent);
}
}
| 16,315 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
SubscriptionType.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/SubscriptionType.java | package com.arantius.tivocommander;
enum SubscriptionType { RECORDING, SEASON_PASS, SINGLE_OFFER, WISHLIST; }
| 114 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
MyShows.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/MyShows.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Pair;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.arantius.tivocommander.rpc.MindRpc;
import com.arantius.tivocommander.rpc.request.BodyConfigSearch;
import com.arantius.tivocommander.rpc.request.RecordingFolderItemEmpty;
import com.arantius.tivocommander.rpc.request.RecordingFolderItemSearch;
import com.arantius.tivocommander.rpc.request.RecordingSearch;
import com.arantius.tivocommander.rpc.request.UiNavigate;
import com.arantius.tivocommander.rpc.response.MindRpcResponse;
import com.arantius.tivocommander.rpc.response.MindRpcResponseListener;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
public class MyShows extends ShowList {
private MindRpcResponseListener mBodyConfigCallback =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
setProgressIndicator(-1);
ProgressBar mMeter = (ProgressBar) findViewById(R.id.meter);
TextView mMeterText = (TextView) findViewById(R.id.meter_text);
JsonNode bodyConfig = response.getBody().path("bodyConfig").path(0);
// Convert long kilobytes to int megabytes. Roamio has 3TB, which
// is more KB than fits in a 32 bit int (!).
int used = (int) Math.floor(
bodyConfig.path("userDiskUsed").asLong() / 1024);
int size = (int) Math.floor(
bodyConfig.path("userDiskSize").asLong() / 1024);
mMeter.setMax(size);
mMeter.setProgress(used);
mMeterText.setText(String.format("%d%% Disk Used",
(int) ((double) 100 * used / size)));
}
};
public void doSort(View v) {
ArrayAdapter<String> orderAdapter =
new ArrayAdapter<String>(this, android.R.layout.select_dialog_item,
mOrderLabels);
Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Order?");
dialogBuilder.setAdapter(orderAdapter,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int position) {
mOrderBy = mOrderValues[position];
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(MyShows.this);
Editor editor = sharedPrefs.edit();
editor.putString("my_shows_order_by", mOrderBy);
editor.commit();
startRequest();
}
});
AlertDialog dialog = dialogBuilder.create();
dialog.show();
}
protected void folderDelete(JsonNode folder) {
final String folderId = folder.path("recordingFolderItemId").asText();
RecordingFolderItemEmpty req = new RecordingFolderItemEmpty(folderId);
MindRpc.addRequest(req, new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
startRequest();
}
});
}
protected void folderPlay(final JsonNode folder) {
Utils.log("Play folder:");
setProgressIndicator(1);
final String folderId = folder.path("recordingFolderItemId").asText();
final RecordingFolderItemSearch req =
new RecordingFolderItemSearch(folderId, mOrderBy);
MindRpc.addRequest(req, new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
final RecordingFolderItemSearch req =
new RecordingFolderItemSearch(
response.getBody().path("objectIdAndType"), mOrderBy);
MindRpc.addRequest(req, new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
setProgressIndicator(-1);
// Gather recordings in reverse order (by always adding to index
// zero), reversing the reverse-chronological order we got.
ArrayList<String> recordingIds = new ArrayList<String>();
for (JsonNode item : response.getBody().path("recordingFolderItem")) {
recordingIds.add(0, item.path("childRecordingId").asText());
}
UiNavigate req =
new UiNavigate(recordingIds, folder.path("title").asText());
MindRpc.addRequest(req, null);
Intent intent = new Intent(MyShows.this, NowShowing.class);
startActivityForResult(intent, EXPECT_REFRESH_INTENT_ID);
}
});
}
});
}
protected int getIconForItem(JsonNode item) {
String folderTransportType =
item.path("folderTransportType").path(0).asText();
if ("mrv".equals(folderTransportType)) {
return R.drawable.folder_downloading;
} else if ("stream".equals(folderTransportType)) {
return R.drawable.folder_recording;
} else if ("deletedFolder".equals(folderTransportType)) {
return R.drawable.folder;
}
if (item.has("folderItemCount")) {
if ("wishlist".equals(item.path("folderType").asText())) {
return R.drawable.folder_wishlist;
} else {
return R.drawable.folder;
}
}
if (item.has("recordingStatusType")) {
String recordingStatus = item.path("recordingStatusType").asText();
if ("expired".equals(recordingStatus)) {
return R.drawable.recording_expired;
} else if ("expiresSoon".equals(recordingStatus)) {
return R.drawable.recording_expiressoon;
} else if ("inProgressDownload".equals(recordingStatus)) {
return R.drawable.recording_downloading;
} else if ("inProgressRecording".equals(recordingStatus)) {
return R.drawable.recording_recording;
} else if ("keepForever".equals(recordingStatus)) {
return R.drawable.recording_keep;
} else if ("suggestion".equals(recordingStatus)) {
return R.drawable.recording_suggestion;
} else if ("wishlist".equals(recordingStatus)) {
return R.drawable.recording_wishlist;
}
}
if ("recording".equals(item.path("recordingForChildRecordingId")
.path("type").asText())) {
return R.drawable.recording;
}
if ("deleted".equals(item.path("state").asText())) {
return R.drawable.recording_deleted;
}
return R.drawable.blank;
}
protected Pair<ArrayList<String>, ArrayList<Integer>> getLongPressChoices(
JsonNode item) {
final ArrayList<String> choices = new ArrayList<String>();
final ArrayList<Integer> actions = new ArrayList<Integer>();
final String folderType = item.path("folderType").asText();
if ("series".equals(folderType) || "wishlist".equals(folderType)) {
// For season pass and/or wish list folders.
choices.add(getResources().getString(R.string.watch_folder));
actions.add(R.string.watch_folder);
choices.add(getResources().getString(R.string.delete_folder));
actions.add(R.string.delete_folder);
} else if (!"".equals(folderType)) {
// Other folders not supported.
return null;
} else {
// For individual recordings.
JsonNode recording = item.path("recordingForChildRecordingId");
if ("deleted".equals(mFolderId)) {
choices.add(getResources().getString(R.string.undelete));
actions.add(R.string.undelete);
} else {
choices.add(getResources().getString(R.string.watch_now));
actions.add(R.string.watch_now);
if ("inProgress" == recording.path("state").asText()) {
choices.add(getResources().getString(R.string.stop_recording));
actions.add(R.string.stop_recording);
choices.add(getResources()
.getString(R.string.stop_recording_and_delete));
actions.add(R.string.stop_recording_and_delete);
} else {
choices.add(getResources().getString(R.string.delete));
actions.add(R.string.delete);
}
}
}
return Pair.create(choices, actions);
}
protected JsonNode getRecordingFromItem(JsonNode item) {
if ("deleted".equals(mFolderId)) {
// In deleted mode, we directly fetch recordings.
return item;
} else {
// Otherwise we've got recordings wrapped in folders.
return item.path("recordingForChildRecordingId");
}
}
@Override
public void onClick(DialogInterface dialog, int position) {
final Pair<ArrayList<String>, ArrayList<Integer>> choices =
getLongPressChoices(mLongPressItem);
Integer action = choices.second.get(position);
switch (action) {
case R.string.delete_folder:
folderDelete(mLongPressItem);
break;
case R.string.watch_folder:
folderPlay(mLongPressItem);
return;
default:
super.onClick(dialog, position);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
if (MindRpc.init(this, bundle)) {
return;
}
if (bundle != null) {
mFolderId = bundle.getString("folderId");
setTitle(bundle.getString("folderName"));
} else {
mFolderId = null;
setTitle("My Shows");
}
Utils.log(String.format("MyShows: folderId:%s", mFolderId));
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.list_my_shows);
if (mFolderId != null) {
findViewById(R.id.sort_button).setVisibility(View.GONE);
}
mListAdapter = new ShowsAdapter(this);
final ListView lv = getListView();
lv.setAdapter(mListAdapter);
lv.setOnItemClickListener(mOnClickListener);
lv.setLongClickable(true);
lv.setOnItemLongClickListener(this);
mDetailCallback =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
setProgressIndicator(-1);
String itemId = "recordingFolderItem";
if ("deleted".equals(mFolderId)) {
itemId = "recording";
}
final JsonNode items = response.getBody().path(itemId);
ArrayList<Integer> slotMap =
mRequestSlotMap.get(response.getRpcId());
MindRpc.saveBodyId(
items.path(0).path("bodyId").asText(), MyShows.this);
for (int i = 0; i < items.size(); i++) {
int pos = slotMap.get(i);
JsonNode item = items.get(i);
mShowData.set(pos, item);
mShowStatus.set(pos, ShowStatus.LOADED);
}
mRequestSlotMap.remove(response.getRpcId());
mListAdapter.notifyDataSetChanged();
}
};
mIdSequenceCallback =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
JsonNode body = response.getBody();
if ("error".equals(body.path("status").asText())) {
Utils.log("Handling mIdSequenceCallback error response by "
+ "finishWithRefresh()");
finishWithRefresh();
return;
}
if (!body.has("objectIdAndType")) {
Utils.log("Handling mIdSequenceCallback empty response by "
+ "finishWithRefresh()");
finishWithRefresh();
return;
}
setProgressIndicator(-1);
mShowIds = (ArrayNode) body.findValue("objectIdAndType");
if (mFolderId == null) {
mShowIds.add("deleted");
}
if (mShowIds != null) {
// e.g. "Suggestions" can be present, but empty!
for (int i = 0; i < mShowIds.size(); i++) {
mShowData.add(null);
mShowStatus.add(ShowStatus.MISSING);
}
}
mListAdapter.notifyDataSetChanged();
}
};
startRequest();
}
@Override
protected void onPause() {
super.onPause();
Utils.log("Activity:Pause:MyShows");
}
@Override
protected void onResume() {
super.onResume();
Utils.log("Activity:Resume:MyShows");
MindRpc.init(this, null);
}
protected void startRequest() {
mShowData.clear();
mShowStatus.clear();
mListAdapter.notifyDataSetChanged();
if ("deleted".equals(mFolderId)) {
MindRpc.addRequest(new RecordingSearch(mFolderId), mIdSequenceCallback);
} else {
MindRpc.addRequest(new RecordingFolderItemSearch(mFolderId, mOrderBy),
mIdSequenceCallback);
}
setProgressIndicator(1);
MindRpc.addRequest(new BodyConfigSearch(), mBodyConfigCallback);
setProgressIndicator(1);
}
}
| 13,811 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
Search.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/Search.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.arantius.tivocommander.rpc.MindRpc;
import com.arantius.tivocommander.rpc.request.UnifiedItemSearch;
import com.arantius.tivocommander.rpc.response.MindRpcResponse;
import com.arantius.tivocommander.rpc.response.MindRpcResponseListener;
import com.fasterxml.jackson.databind.JsonNode;
public class Search extends ListActivity {
private class SearchAdapter extends ArrayAdapter<JsonNode> {
// TODO: Make this class DRY vs. Suggestions.ShowAdapter
private final Drawable mDrawable;
private final ArrayList<JsonNode> mItems;
public SearchAdapter(Context context, int resource,
ArrayList<JsonNode> objects) {
super(context, resource, objects);
mItems = objects;
mDrawable = context.getResources().getDrawable(R.drawable.content_banner);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.item_show, null);
}
ImageView iv = (ImageView) v.findViewById(R.id.image_show);
View pv = v.findViewById(R.id.image_show_progress);
if (convertView != null) {
iv.setImageDrawable(mDrawable);
pv.setVisibility(View.VISIBLE);
}
JsonNode item = mItems.get(position);
if (item == null) {
return null;
}
if (iv != null) {
String imgUrl = Utils.findImageUrl(item);
if (item.has("personId")) {
iv.setImageResource(R.drawable.person);
}
new DownloadImageTask(Search.this, iv, pv).execute(imgUrl);
}
String title = null;
if (item.has("collectionId") || item.has("contentId")) {
title = item.path("title").asText();
} else if (item.has("personId")) {
title = item.path("first").asText();
if (item.has("last")) {
// Some people only have one (thus first) name.
title += " " + item.path("last").asText();
}
} else {
Utils.log("Could not find title!");
Utils.log(item.toString());
return v;
}
((TextView) v.findViewById(R.id.show_name)).setText(title);
return v;
}
}
private final class SearchTask extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
// Give the user time to type more.
try {
Thread.sleep(333);
} catch (InterruptedException e) {
// No-op.
}
// Then proceed.
if (isCancelled()) {
return null;
}
runOnUiThread(new Runnable() {
public void run() {
Utils.showProgress(Search.this, true);
}
});
UnifiedItemSearch request = new UnifiedItemSearch(params[0] + "*");
MindRpc.addRequest(request, mSearchListener);
return null;
}
}
private SearchAdapter mAdapter;
private View mEmptyView;
private final OnItemClickListener mOnClickListener =
new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
JsonNode result = mResults.get(position);
if (result.has("collectionId") || result.has("contentId")) {
Intent intent = new Intent(getBaseContext(), ExploreTabs.class);
if (result.has("collectionId")) {
intent.putExtra("collectionId", result.path("collectionId")
.asText());
}
if (result.has("contentId")) {
intent.putExtra("contentId", result.path("contentId")
.asText());
}
startActivity(intent);
} else if (result.has("personId")) {
Intent intent = new Intent(getBaseContext(), Person.class);
intent.putExtra("fName", result.path("first").asText());
intent.putExtra("lName", result.path("last").asText());
intent.putExtra("personId", result.path("personId").asText());
startActivity(intent);
} else {
Utils
.logError("Result had neither collectionId, contentId, nor personId!\n"
+ Utils.stringifyToJson(result));
}
}
};
private final ArrayList<JsonNode> mResults = new ArrayList<JsonNode>();
private final MindRpcResponseListener mSearchListener =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
mEmptyView.setVisibility(View.VISIBLE);
JsonNode resultsNode = response.getBody().path("unifiedItem");
mResults.clear();
for (JsonNode result : resultsNode) {
mResults.add(result);
}
mAdapter.notifyDataSetChanged();
Utils.showProgress(Search.this, false);
}
};
private AsyncTask<String, Void, Void> mSearchTask = null;
private final TextWatcher mTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Cancel any previous request.
if (mSearchTask != null) {
mSearchTask.cancel(true);
mSearchTask = null;
}
MindRpc.cancelAll();
// Handle empty input.
if ("".equals(s.toString())) {
mResults.clear();
runOnUiThread(new Runnable() {
public void run() {
mAdapter.notifyDataSetChanged();
mEmptyView.setVisibility(View.INVISIBLE);
}
});
return;
}
mSearchTask = new SearchTask().execute(s.toString());
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.search);
setTitle("Search");
final EditText searchBox = (EditText) findViewById(R.id.search_box);
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
mAdapter = new SearchAdapter(this, R.layout.item_show, mResults);
setListAdapter(mAdapter);
searchBox.addTextChangedListener(mTextWatcher);
final ListView lv = getListView();
lv.setOnItemClickListener(mOnClickListener);
mEmptyView = findViewById(android.R.id.empty);
mEmptyView.setVisibility(View.INVISIBLE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Utils.createFullOptionsMenu(menu, this);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return Utils.onOptionsItemSelected(item, this);
}
@Override
protected void onPause() {
super.onPause();
Utils.log("Activity:Pause:Search");
}
@Override
protected void onResume() {
super.onResume();
Utils.log("Activity:Resume:Search");
MindRpc.init(this, null);
}
}
| 8,689 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
About.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/About.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import android.app.Activity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.TextView;
public class About extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
TextView title = (TextView) findViewById(R.id.about_version);
title.setText(title.getText() + Utils.getVersion(this));
Utils.activateHomeButton(this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return Utils.onOptionsItemSelected(item, this);
}
@Override
protected void onPause() {
super.onPause();
Utils.log("Activity:Pause:About");
}
@Override
protected void onResume() {
super.onResume();
Utils.log("Activity:Resume:About");
}
}
| 1,659 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
ToDo.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/ToDo.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import java.util.ArrayList;
import android.content.Intent;
import android.os.Bundle;
import android.util.Pair;
import android.view.Window;
import android.widget.ListView;
import com.arantius.tivocommander.rpc.MindRpc;
import com.arantius.tivocommander.rpc.request.TodoSearch;
import com.arantius.tivocommander.rpc.response.MindRpcResponse;
import com.arantius.tivocommander.rpc.response.MindRpcResponseListener;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
public class ToDo extends ShowList {
protected int getIconForItem(JsonNode item) {
if (item == null) return R.drawable.blank;
SubscriptionType subType = Utils.subscriptionTypeForRecording(item);
if (subType == null) return R.drawable.blank;
switch (subType) {
case RECORDING:
return R.drawable.recording_recording;
case SEASON_PASS:
return R.drawable.todo_seasonpass;
case SINGLE_OFFER:
return R.drawable.todo_single_offer;
case WISHLIST:
return R.drawable.todo_wishlist;
}
return R.drawable.blank;
}
protected String getSubTitleFromItem(JsonNode item) {
return item.path("subtitle").asText();
};
protected Pair<ArrayList<String>, ArrayList<Integer>> getLongPressChoices(
JsonNode item) {
final ArrayList<String> choices = new ArrayList<String>();
final ArrayList<Integer> actions = new ArrayList<Integer>();
if ("inProgress".equals(item.path("state").asText())) {
choices.add(getResources().getString(R.string.stop_recording));
actions.add(R.string.stop_recording);
choices.add(getResources().getString(R.string.stop_recording_and_delete));
actions.add(R.string.stop_recording_and_delete);
} else {
choices.add(getResources().getString(R.string.dont_record));
actions.add(R.string.dont_record);
}
return Pair.create(choices, actions);
}
protected JsonNode getRecordingFromItem(JsonNode item) {
return item;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Assume we've been asked to refresh, restart the activity.
startActivity(getIntent());
finish();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (MindRpc.init(this, null)) {
return;
}
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.list_todo);
setTitle("To Do List");
mListAdapter = new ShowsAdapter(this);
ListView lv = getListView();
lv.setAdapter(mListAdapter);
lv.setOnItemClickListener(mOnClickListener);
lv.setLongClickable(true);
lv.setOnItemLongClickListener(this);
mDetailCallback =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
setProgressIndicator(-1);
String itemId = "recording";
final JsonNode items = response.getBody().path(itemId);
ArrayList<Integer> slotMap =
mRequestSlotMap.get(response.getRpcId());
for (int i = 0; i < items.size(); i++) {
int pos = slotMap.get(i);
JsonNode item = items.get(i);
mShowData.set(pos, item);
mShowStatus.set(pos, ShowStatus.LOADED);
}
mRequestSlotMap.remove(response.getRpcId());
mListAdapter.notifyDataSetChanged();
}
};
mIdSequenceCallback =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
JsonNode body = response.getBody();
setProgressIndicator(-1);
mShowIds = (ArrayNode) body.findValue("objectIdAndType");
if (mShowIds == null) return;
for (int i = 0; i < mShowIds.size(); i++) {
mShowData.add(null);
mShowStatus.add(ShowStatus.MISSING);
}
mListAdapter.notifyDataSetChanged();
}
};
startRequest();
}
@Override
protected void onPause() {
super.onPause();
Utils.log("Activity:Pause:ToDo");
}
@Override
protected void onResume() {
super.onResume();
Utils.log("Activity:Resume:ToDo");
MindRpc.init(this, null);
}
protected void startRequest() {
mShowData.clear();
mShowStatus.clear();
mListAdapter.notifyDataSetChanged();
MindRpc.addRequest(new TodoSearch(), mIdSequenceCallback);
setProgressIndicator(1);
}
}
| 5,372 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
Settings.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/Settings.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.Menu;
import com.arantius.tivocommander.rpc.MindRpc;
public class Settings extends PreferenceActivity {
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MindRpc.disconnect();
addPreferencesFromResource(R.xml.preferences);
}
public final boolean onCreateOptionsMenu(Menu menu) {
Utils.createShortOptionsMenu(menu, this);
return true;
}
@Override
protected void onPause() {
super.onPause();
Utils.log("Activity:Pause:Settings");
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
Utils.DEBUG_LOG = prefs.getBoolean("debug_log", false);
}
@Override
protected void onResume() {
super.onResume();
setTitle("Settings");
Utils.log("Activity:Resume:Settings");
}
}
| 1,895 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
SubscribeBase.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/SubscribeBase.java | package com.arantius.tivocommander;
import android.app.Activity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.arantius.tivocommander.rpc.request.Subscribe;
abstract public class SubscribeBase extends Activity {
protected final static String[] mStartLabels = new String[] { "On time",
"1 minute early", "2 minutes early", "3 minutes early",
"4 minutes early", "5 minutes early", "10 minutes early"};
protected final static Integer[] mStartStopValues = new Integer[] { 0,
60 * 1, 60 * 2, 60 * 3, 60 * 4, 60 * 5, 60 * 10, 60 * 30, 60 * 60,
60 * 90 };
protected final static String[] mStopLabels = new String[] {"On time",
"1 minute late", "2 minutes late", "3 minutes late", "4 minutes late",
"5 minutes late", "10 minutes late", "30 minutes late",
"60 minutes late", "90 minutes late"};
protected final static String[] mUntilLabels = new String[] { "Space needed",
"Until I delete" };
protected final static String[] mUntilValues = new String[] { "fifo",
"forever" };
protected String mKeepBehavior = null;
protected String mKeepUntil = null;
protected Integer mPaddingStart = null;
protected Integer mPaddingStop = null;
protected void getValues() {
int pos;
pos = ((Spinner) findViewById(R.id.until)).getSelectedItemPosition();
mKeepUntil = mUntilValues[pos];
pos = ((Spinner) findViewById(R.id.start)).getSelectedItemPosition();
mPaddingStart = mStartStopValues[pos];
pos = ((Spinner) findViewById(R.id.stop)).getSelectedItemPosition();
mPaddingStop = mStartStopValues[pos];
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
Utils.activateHomeButton(this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return Utils.onOptionsItemSelected(item, this, true);
}
protected void setUpSpinner(int spinnerId, String[] labels) {
Spinner spinner = (Spinner) findViewById(spinnerId);
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
labels);
adapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
protected void subscribeRequestCommon(Subscribe request) {
request.setKeepUntil(mKeepUntil);
request.setPadding(mPaddingStart, mPaddingStop);
}
}
| 2,594 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
LinearListView.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/views/LinearListView.java | package com.arantius.tivocommander.views;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.content.Context;
import android.database.DataSetObserver;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Adapter;
import android.widget.LinearLayout;
// http://stackoverflow.com/questions/3192595/android-listview-that-does-not-scroll/5646121#5646121
// Like a ListView, but it does not implicitly scroll.
public class LinearListView extends LinearLayout {
private class Observer extends DataSetObserver {
LinearListView context;
public Observer(LinearListView context) {
this.context = context;
}
@Override
public void onChanged() {
List<View> oldViews = new ArrayList<View>(context.getChildCount());
for (int i = 0; i < context.getChildCount(); i++)
oldViews.add(context.getChildAt(i));
Iterator<View> iter = oldViews.iterator();
context.removeAllViews();
for (int i = 0; i < context.adapter.getCount(); i++) {
View convertView = iter.hasNext() ? iter.next() : null;
context.addView(context.adapter.getView(i, convertView, context));
}
super.onChanged();
}
@Override
public void onInvalidated() {
context.removeAllViews();
super.onInvalidated();
}
}
Adapter adapter;
Observer observer = new Observer(this);
public LinearListView(Context context) {
super(context);
}
public LinearListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setAdapter(Adapter adapter) {
if (this.adapter != null)
this.adapter.unregisterDataSetObserver(observer);
this.adapter = adapter;
adapter.registerDataSetObserver(observer);
observer.onChanged();
}
}
| 1,820 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
TivoScrubBar.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/views/TivoScrubBar.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.views;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import com.arantius.tivocommander.R;
/** A scrub bar to display/control playback like the native TiVo interface. */
public class TivoScrubBar extends View {
/** The max value for the available section of the recording; milliseconds. */
protected int mAvailableMax = 2400000;
/** The min value for the available section of the recording; milliseconds. */
protected int mAvailableMin = 600000;
/** The maximum point possible within this recording; milliseconds. */
protected int mMax = 5400000;
/** The current point of playback; milliseconds; inside available range. */
protected int mProgress = 1700000;
/** The time label to display on the left side. */
protected String mLabelLeft = "";
/** The time label to display on the right side. */
protected String mLabelRight = "1h 30m";
private Bitmap mBitmapBarEndLeft;
private Bitmap mBitmapBarEndRight;
private Bitmap mBitmapBarMid;
private Bitmap mBitmapThumb;
private Paint mPaintActiveSection;
private Paint mPaintHash;
private Paint mPaintText;
final private int mSizeHashWid = 4;
final private int mSizeHeiBar = 36;
final private int mSizeHeiBarPad = 10;
final private int mSizeTextPadSide = 20;
final private int mSizeTextPadTop = 25;
final private int mSizeTextHei = 22;
final private int mSizeThumb = 55;
final private int mSizeThumbPad = 27;
final private int mSizeViewHei = 56;
private int mSizeViewWid;
private float mScaleHei = 1;
final private int mCoordActiveTop = 12;
final private int mCoordActiveBot = 45;
final private int mCoordThumbTop = 2;
private int mCoordThumbLeft = 0;
private Rect mRectActive = new Rect(0, mCoordActiveTop, 0, mCoordActiveBot);
private Rect mRectBarEndLeft = new Rect();
private Rect mRectBarEndRight = new Rect();
private Rect mRectBarMid = new Rect();
private Rect mRectHash = new Rect();
private Rect mRectThumb = new Rect();
public TivoScrubBar(Context context) {
this(context, null);
}
public TivoScrubBar(Context context, AttributeSet attrs) {
super(context, attrs);
mBitmapBarEndLeft =
BitmapFactory.decodeResource(getResources(), R.drawable.scrub_left);
mBitmapBarEndRight =
BitmapFactory.decodeResource(getResources(), R.drawable.scrub_right);
mBitmapBarMid =
BitmapFactory.decodeResource(getResources(), R.drawable.scrub_mid);
mBitmapThumb =
BitmapFactory.decodeResource(getResources(), R.drawable.scrub_thumb);
mPaintActiveSection = new Paint();
mPaintActiveSection.setStyle(Paint.Style.FILL);
mPaintActiveSection.setColor(0xFF348E26);
mPaintHash = new Paint();
mPaintHash.setStyle(Paint.Style.FILL);
mPaintHash.setColor(0xFFFFFFFF);
mPaintText = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaintText.setColor(0xFFFFFFFF);
}
@Override
protected void onDraw(Canvas canvas) {
// Calculate the time labels and their sizes.
mPaintText.setTextSize(mSizeTextHei * mScaleHei);
if (mLabelLeft == null) {
mLabelLeft = "";
}
int widLabelLeft =
mSizeTextPadSide + (int) mPaintText.measureText(mLabelLeft);
if (mLabelRight == null) {
mLabelRight = "";
}
int widLabelRight =
mSizeTextPadSide + (int) mPaintText.measureText(mLabelRight);
// Calculate the rects for the bar pieces, based on label sizes.
final int barTop = (int) (mSizeHeiBarPad * mScaleHei);
final int barBot = (int) (barTop + (mSizeHeiBar * mScaleHei));
mRectBarEndLeft.set(0, barTop, Math.max(16, widLabelLeft), barBot);
mRectBarEndRight.set(mSizeViewWid - Math.max(16, widLabelRight), barTop,
mSizeViewWid, barBot);
mRectBarMid.set(mRectBarEndLeft.right, barTop, mRectBarEndRight.left,
barBot);
// Calculate the position of the active region and thumb.
float scale = (float) (mRectBarMid.right - mRectBarMid.left) / mMax;
mCoordThumbLeft =
(int) Math.floor(mRectBarMid.left + (mProgress * scale)
- (int) (mSizeThumbPad * mScaleHei));
//@formatter:off
mRectActive.set(
mRectBarEndLeft.right + (int) (mAvailableMin * scale),
(int) Math.ceil(mCoordActiveTop * mScaleHei),
mRectBarEndLeft.right + (int) (mAvailableMax * scale),
(int) (mCoordActiveBot * mScaleHei));
//@formatter:on
// Draw the green active region, first, under the bar outline, so the
// edges show through, rounded.
canvas.drawRect(mRectActive, mPaintActiveSection);
// Draw the hash marks.
int hashWid = 15 * 60 * 1000;
// TODO: Does this limit match TiVo on screen behavior?
while (true) {
// Minus 30k so that we don't draw a hash right at the end. Not minus
// a full minute though, because the TiVo itself will e.g. draw the
// 1-hour hash for a 61 min. recording.
int numHashes = (mMax - 30000) / hashWid;
if (numHashes <= 10)
break;
hashWid *= 2;
}
for (int x = hashWid; x < mMax - 30000; x += hashWid) {
int hashLeft = mRectBarMid.left + (int) (x * scale) - (mSizeHashWid / 2);
//@formatter:off
mRectHash.set(
hashLeft,
(int) Math.ceil(mCoordActiveTop * mScaleHei),
hashLeft + mSizeHashWid,
(int) (mCoordActiveBot * mScaleHei));
canvas.drawRect(mRectHash, mPaintHash);
}
// Draw the outline of the bar.
canvas.drawBitmap(mBitmapBarEndLeft, null, mRectBarEndLeft, null);
canvas.drawBitmap(mBitmapBarEndRight, null, mRectBarEndRight, null);
canvas.drawBitmap(mBitmapBarMid, null, mRectBarMid, null);
// Draw the time labels.
//@formatter:off
canvas.drawText(
mLabelLeft,
mRectBarEndLeft.left + (mSizeTextPadSide / 2),
mRectBarEndLeft.top + (mSizeTextPadTop * mScaleHei),
mPaintText);
canvas.drawText(
mLabelRight,
mRectBarEndRight.left + (mSizeTextPadSide / 2),
mRectBarEndRight.top + (mSizeTextPadTop * mScaleHei),
mPaintText);
//@formatter:on
// Draw the thumb.
//@formatter:off
mRectThumb.set(
mCoordThumbLeft,
(int) (mCoordThumbTop * mScaleHei),
mCoordThumbLeft + (int) (mSizeThumb * mScaleHei),
(int) (mCoordThumbTop + mSizeThumb * mScaleHei));
//@formatter:on
canvas.drawBitmap(mBitmapThumb, null, mRectThumb, null);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// Force fill_parent width, fixed content height (by images).
mSizeViewWid = MeasureSpec.getSize(widthMeasureSpec);
int viewHei = MeasureSpec.getSize(heightMeasureSpec);
mScaleHei = (float) viewHei / mSizeViewHei;
this.setMeasuredDimension(mSizeViewWid, viewHei);
}
/** Set all the properties that affect the range this view presents. */
public void update(int availableMin, int progress, int availableMax, int max,
String labelLeft, String labelRight) {
boolean change = false;
// Save inputs.
//@formatter:off
if (mAvailableMin != availableMin) change = true;
this.mAvailableMin = availableMin;
if (mProgress != progress) change = true;
this.mProgress = progress;
if (mAvailableMax != availableMax) change = true;
this.mAvailableMax = availableMax;
if (mMax != max) change = true;
this.mMax = max;
if (mLabelLeft != labelLeft) change = true;
this.mLabelLeft = labelLeft;
if (mLabelRight != labelRight) change = true;
this.mLabelRight = labelRight;
//@formatter:on
if (!change) {
return;
}
// Schedule a redraw.
invalidate();
requestLayout();
}
}
| 9,000 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
MindRpcInput.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/MindRpcInput.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Locale;
import android.util.Log;
import com.arantius.tivocommander.Utils;
import com.arantius.tivocommander.rpc.response.MindRpcResponse;
import com.arantius.tivocommander.rpc.response.MindRpcResponseFactory;
/**
* Handle network level input. Generate appropriate response objects.
*/
public class MindRpcInput extends Thread {
private static final String LOG_TAG = "tivo_commander";
public volatile boolean mStopFlag = false;
private final DataInputStream mStream;
public MindRpcInput(DataInputStream mInputStream) {
super("MindRpcInput");
mStream = mInputStream;
}
@SuppressWarnings("deprecation")
@Override
public void run() {
MindRpcResponseFactory mindRpcResponseFactory =
new MindRpcResponseFactory();
while (!mStopFlag) {
try {
// Limit worst case battery consumption?
Thread.sleep(50);
// Use deprecated readline on DataInputStream, because later I have to
// read _bytes_ from it.
String respLine = null;
try {
respLine = mStream.readLine();
} catch (ArrayIndexOutOfBoundsException e) {
break;
}
if (respLine == null) {
// The socket has closed.
break;
}
if (respLine.length() >= 6 && "MRPC/2".equals(respLine.substring(0, 6))) {
String[] respBytes = respLine.split(" ");
int headerLen = Integer.parseInt(respBytes[1]);
int bodyLen = Integer.parseInt(respBytes[2]);
byte[] headers = new byte[headerLen];
readBytes(headers, headerLen);
byte[] body = new byte[bodyLen];
readBytes(body, bodyLen);
final MindRpcResponse response =
mindRpcResponseFactory.create(headers, body);
if (response != null) {
Utils.log(String.format(Locale.US, "% 4d RECV %s", response.getRpcId(),
response.getRespType()));
Utils.logRpc(response.getBody());
MindRpc.dispatchResponse(response);
}
}
} catch (InterruptedException e) {
Utils.log("MindRpcInput: thread interrupted.");
break;
} catch (IOException e) {
Log.e(LOG_TAG, "read: IOException!", e);
break;
}
}
}
private void readBytes(byte[] body, int len) throws IOException {
int bytesRead = 0;
while (bytesRead < len) {
bytesRead += mStream.read(body, bytesRead, len - bytesRead);
}
}
}
| 3,398 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
MindRpc.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/MindRpc.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Random;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.Toast;
import com.arantius.tivocommander.Connect;
import com.arantius.tivocommander.Database;
import com.arantius.tivocommander.Device;
import com.arantius.tivocommander.Discover;
import com.arantius.tivocommander.NowShowing;
import com.arantius.tivocommander.R;
import com.arantius.tivocommander.Settings;
import com.arantius.tivocommander.Utils;
import com.arantius.tivocommander.rpc.request.BodyAuthenticate;
import com.arantius.tivocommander.rpc.request.CancelRpc;
import com.arantius.tivocommander.rpc.request.MindRpcRequest;
import com.arantius.tivocommander.rpc.response.MindRpcResponse;
import com.arantius.tivocommander.rpc.response.MindRpcResponseListener;
public enum MindRpc {
INSTANCE;
private static class AlwaysTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] cert, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] cert, String authType)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
public static Boolean mBodyIsAuthed = false;
public static volatile Boolean mConnectInterrupted = false;
public static Device mTivoDevice;
private static DataInputStream mInputStream;
private static MindRpcInput mInputThread;
private static Activity mOriginActivity;
private static Bundle mOriginExtras;
private static DataOutputStream mOutputStream;
private static MindRpcOutput mOutputThread;
private static TreeMap<Integer, MindRpcResponseListener> mResponseListenerMap =
new TreeMap<Integer, MindRpcResponseListener>();
private static volatile int mRpcId = 1;
private static volatile int mSessionId;
private static Socket mSocket;
private static final int TIMEOUT_CONNECT = 25000;
/**
* Add an outgoing request to the queue.
*
* @param request The request to be sent.
* @param listener The object to notify when the response(s) come back.
*/
public static void addRequest(MindRpcRequest request,
MindRpcResponseListener listener) {
// Reconnect if necessary; but not for BodyAuthenticate! That one RPC
// is sent during connection as part of the verification.
if (!isConnected() && !(request instanceof BodyAuthenticate)) {
init2();
return;
}
mOutputThread.addRequest(request);
if (listener != null) {
mResponseListenerMap.put(request.getRpcId(), listener);
}
}
private static boolean checkSettings(Activity activity) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(
activity.getBaseContext());
Utils.DEBUG_LOG = prefs.getBoolean("debug_log", false);
final Database db = new Database(activity);
db.portLegacySettings(activity);
mTivoDevice = db.getLastUsedDevice();
int error = 0;
if (mTivoDevice == null) {
error = R.string.error_no_device;
} else if (mTivoDevice.addr == null || "".equals(mTivoDevice.addr)) {
error = R.string.error_addr;
} else if (mTivoDevice.port == null || 0 >= mTivoDevice.port) {
error = R.string.error_port;
} else if (mTivoDevice.mak == null || "".equals(mTivoDevice.mak)) {
error = R.string.error_mak;
}
if (error != 0) {
settingsError(activity, error);
return false;
}
return true;
}
private static boolean connect(final Activity originActivity) {
Callable<Boolean> connectCallable = new Callable<Boolean>() {
public Boolean call() {
Utils.log(String.format(Locale.US,
"Connecting to %s:%d ...", mTivoDevice.addr, mTivoDevice.port
));
Utils.log(">>> With interfaces:");
Enumeration<NetworkInterface> ifaces = null;
try {
ifaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e1) {
Utils.log("Cannot get interfaces!");
}
while (ifaces != null && ifaces.hasMoreElements()) {
NetworkInterface iface = ifaces.nextElement();
StringBuilder ifaceStrBld = new StringBuilder();
ifaceStrBld.append(String.format(Locale.US,
" %s %s",
iface.getName(), iface.getDisplayName()
));
boolean haveAddr = false;
for (InterfaceAddress addr : iface.getInterfaceAddresses()) {
if (addr.getAddress().isLoopbackAddress()) continue;
if (addr.getAddress().isLinkLocalAddress()) continue;
ifaceStrBld.append(", ");
ifaceStrBld.append(addr.toString());
haveAddr = true;
}
if (haveAddr) Utils.log(ifaceStrBld.toString());
}
Utils.log("<<<");
SSLSocketFactory sslSocketFactory = createSocketFactory(originActivity);
if (sslSocketFactory == null) {
return false;
}
try {
mSessionId = 0x26c000 + new Random().nextInt(0xFFFF);
mSocket = sslSocketFactory.createSocket();
InetSocketAddress remoteAddr =
new InetSocketAddress(mTivoDevice.addr, mTivoDevice.port);
mSocket.connect(remoteAddr, TIMEOUT_CONNECT);
mInputStream = new DataInputStream(mSocket.getInputStream());
mOutputStream = new DataOutputStream(mSocket.getOutputStream());
} catch (UnknownHostException e) {
Utils.logError("connect: unknown host!", e);
return false;
} catch (IOException e) {
Utils.logError("connect: io exception!", e);
return false;
}
return true;
}
};
ExecutorService executor = new ScheduledThreadPoolExecutor(1);
Future<Boolean> success = executor.submit(connectCallable);
try {
return success.get();
} catch (InterruptedException e) {
Utils.logError("connect: interrupted exception!", e);
return false;
} catch (ExecutionException e) {
Utils.logError("connect: execution exception!", e);
return false;
}
}
@SuppressLint("TrulyRandom")
private static SSLSocketFactory createSocketFactory(
final Activity originActivity
) {
final String password = readPassword(originActivity);
try {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
KeyManagerFactory fac = KeyManagerFactory.getInstance("X509");
InputStream keyInput = originActivity.getResources().openRawResource(
R.raw.cdata);
keyStore.load(keyInput, password.toCharArray());
keyInput.close();
fac.init(keyStore, password.toCharArray());
SSLContext context = SSLContext.getInstance("TLS");
TrustManager[] tm = new TrustManager[] { new AlwaysTrustManager() };
context.init(fac.getKeyManagers(), tm, new SecureRandom());
return context.getSocketFactory();
} catch (CertificateException e) {
Utils.logError("createSocketFactory: CertificateException!", e);
} catch (IOException e) {
Utils.logError("createSocketFactory: IOException!", e);
} catch (KeyManagementException e) {
Utils.logError("createSocketFactory: KeyManagementException!", e);
} catch (KeyStoreException e) {
Utils.logError("createSocketFactory: KeyStoreException!", e);
} catch (NoSuchAlgorithmException e) {
Utils.logError("createSocketFactory: NoSuchAlgorithmException!", e);
} catch (UnrecoverableKeyException e) {
Utils.logError("createSocketFactory: UnrecoverableKeyException!", e);
}
return null;
}
/** Cancel all outstanding RPCs with response listeners. */
public static void cancelAll() {
for (Integer i : mResponseListenerMap.keySet()) {
addRequest(new CancelRpc(i), null);
}
mResponseListenerMap.clear();
}
public static void disconnect() {
Thread disconnectThread = new Thread(new Runnable() {
public void run() {
// TODO: Do disconnect on close (after N idle seconds?).
stopThreads();
if (mSocket != null) {
try {
mSocket.close();
} catch (IOException e) {
Utils.logError("disconnect() socket", e);
}
}
if (mInputStream != null) {
try {
mInputStream.close();
} catch (IOException e) {
Utils.logError("disconnect() input stream", e);
}
}
if (mOutputStream != null) {
try {
mOutputStream.close();
} catch (IOException e) {
Utils.logError("disconnect() output stream", e);
}
}
}
});
mBodyIsAuthed = false;
disconnectThread.start();
try {
disconnectThread.join();
} catch (InterruptedException e) {
Utils.logError("disconnect() interrupted exception", e);
}
}
protected static void dispatchResponse(final MindRpcResponse response) {
final Integer rpcId = response.getRpcId();
if (mResponseListenerMap.get(rpcId) == null) {
return;
}
mOriginActivity.runOnUiThread(new Runnable() {
public void run() {
MindRpcResponseListener l = mResponseListenerMap.get(rpcId);
if (l != null) {
// It might have been removed on another thread, so check for null.
l.onResponse(response);
}
if (response.isFinal()) {
mResponseListenerMap.remove(rpcId);
}
}
});
}
public static Boolean getBodyIsAuthed() {
return mBodyIsAuthed;
}
public static int getRpcId() {
return mRpcId++;
}
public static int getSessionId() {
return mSessionId;
}
/** Init step 1. Every activity that's going to do RPCs should call this,
* passing itself and its data bundle, if any. */
public static boolean init(final Activity originActivity, Bundle originExtras) {
// Always save these; they're used to resume later.
mOriginExtras = originExtras;
mOriginActivity = originActivity;
if (isConnected()) {
// Already connected? No-op.
Utils.log("MindRpc.init(): already connected.");
return false;
}
Utils.log("MindRpc.init(); " + originActivity.toString());
if (!checkSettings(originActivity)) {
originActivity.finish();
return true;
}
init2();
return true;
}
/** Init continues here; it may resume here after disconnection. Fires off
* the Connect activity to surface this flow to the user. */
public static void init2() {
Utils.log("MindRpc.init2(); " + mOriginActivity.toString());
Intent intent =
new Intent(mOriginActivity.getBaseContext(), Connect.class);
mOriginActivity.startActivity(intent);
mOriginActivity.finish();
}
/** Finally, (only) the Connect activity calls back here to finish init. */
public static void init3(final Activity connectActivity) {
if (mOriginActivity == null) {
// We must have been evicted/quit and restarted while at the connect
// screen which calls us. Restart the app from Now Showing.
Intent intent =
new Intent(connectActivity.getBaseContext(), NowShowing.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
connectActivity.startActivity(intent);
connectActivity.finish();
return;
}
Utils.log("MindRpc.init3() " + mOriginActivity.toString());
stopThreads();
disconnect();
// Try to connect in an infinite loop. In case e.g. we need to wait for
// WiFi to resume from sleep to be successful. Only the Connect activity
// calls init3(), and it is responsible for terminating this thread if
// it takes too long.
mConnectInterrupted = false;
while (true) {
if (mConnectInterrupted) {
Utils.log("MindRpc.init3() interrupting connect attempt.");
return;
}
if (connect(connectActivity)) {
break;
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// Ignore.
}
}
mInputThread = new MindRpcInput(mInputStream);
mInputThread.start();
mOutputThread = new MindRpcOutput(mOutputStream);
mOutputThread.start();
MindRpcResponseListener authListener = new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
if ("failure".equals(response.getBody().path("status").asText())) {
settingsError(connectActivity, R.string.error_auth);
try {
mTivoDevice.mak = "";
new Database(connectActivity).saveDevice(mTivoDevice);
} catch (Exception e) {
Utils.logError("Could not remove bad MAK.", e);
}
connectActivity.finish();
} else {
mBodyIsAuthed = true;
Intent intent =
new Intent(connectActivity.getBaseContext(),
mOriginActivity.getClass());
if (mOriginExtras != null) {
intent.putExtras(mOriginExtras);
}
mOriginExtras = null;
connectActivity.startActivity(intent);
connectActivity.finish();
connectActivity.overridePendingTransition(0, 0);
}
}
};
Utils.log("MindRpc.init3(): start auth.");
addRequest(new BodyAuthenticate(mTivoDevice.mak), authListener);
}
protected static boolean isConnected() {
if (mInputThread == null
|| mInputThread.getState() == Thread.State.TERMINATED
|| mOutputThread == null
|| mOutputThread.getState() == Thread.State.TERMINATED) {
mBodyIsAuthed = false;
return false;
}
if (mSocket == null || mSocket.isClosed()) {
mBodyIsAuthed = false;
return false;
}
return mBodyIsAuthed;
}
private static String readPassword(Context ctx) {
InputStream inputStream = ctx.getResources().openRawResource(
R.raw.cdata_pass);
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
try {
return reader.readLine();
} catch (IOException e) {
Utils.logError("readpassword: IOException!", e);
return "";
}
}
public static void saveBodyId(String bodyId, Context context) {
if (bodyId == null || bodyId == "" || bodyId == mTivoDevice.tsn) {
return;
}
mTivoDevice.tsn = bodyId;
new Database(context).saveDevice(mTivoDevice);
}
public static void settingsError(
final Activity activity, final int messageId) {
settingsError(activity, messageId, Toast.LENGTH_SHORT);
}
public static void settingsError(
final Activity activity, final int messageId, final int toastLen) {
Utils.log("Settings error: " + activity.getResources().getString(messageId));
activity.runOnUiThread(new Runnable() {
public void run() {
Utils.toast(activity, messageId, toastLen);
Intent i;
if (activity.getClass() == Discover.class) {
i = new Intent(activity.getBaseContext(), Settings.class);
} else {
i = new Intent(activity.getBaseContext(), Discover.class);
}
activity.startActivity(i);
}
});
}
private static void stopThreads() {
if (mInputThread != null) {
mInputThread.mStopFlag = true;
mInputThread.interrupt();
mInputThread = null;
}
if (mOutputThread != null) {
mOutputThread.mStopFlag = true;
mOutputThread.interrupt();
mOutputThread = null;
}
}
}
| 17,736 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
MindRpcOutput.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/MindRpcOutput.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Locale;
import java.util.concurrent.ConcurrentLinkedQueue;
import android.util.Log;
import com.arantius.tivocommander.Utils;
import com.arantius.tivocommander.rpc.request.MindRpcRequest;
/**
* Handle network level output. Accept request objects.
*/
public class MindRpcOutput extends Thread {
private static final String LOG_TAG = "tivo_commander";
public volatile boolean mStopFlag = false;
private volatile ConcurrentLinkedQueue<MindRpcRequest> mRequestQueue =
new ConcurrentLinkedQueue<MindRpcRequest>();
private final DataOutputStream mStream;
public MindRpcOutput(DataOutputStream mOutputStream) {
super("MindRpcOutput");
mStream = mOutputStream;
}
public void addRequest(MindRpcRequest request) {
mRequestQueue.add(request);
}
@Override
public void run() {
while (!mStopFlag) {
try {
// Limit worst case battery consumption?
Thread.sleep(50);
// If necessary, send requests.
if (mRequestQueue.peek() != null) {
MindRpcRequest request = mRequestQueue.remove();
Utils.log(String.format(Locale.US, "% 4d CALL %s",
request.getRpcId(),
request.getReqType()));
Utils.logRpc(request.getDataMap());
byte[] requestBytes = request.getBytes();
mStream.write(requestBytes, 0, requestBytes.length);
mStream.flush();
}
} catch (InterruptedException e) {
Utils.log("MindRpcOutput: thread interrupted.");
break;
} catch (IOException e) {
Log.e(LOG_TAG, "write: io exception!", e);
break;
}
}
}
}
| 2,559 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
SubscriptionSearch.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/SubscriptionSearch.java | package com.arantius.tivocommander.rpc.request;
import java.util.ArrayList;
import com.arantius.tivocommander.rpc.MindRpc;
public class SubscriptionSearch extends MindRpcRequest {
public SubscriptionSearch() {
super("subscriptionSearch");
mDataMap.put("bodyId", MindRpc.mTivoDevice.tsn);
mDataMap.put("format", "idSequence");
mDataMap.put("levelOfDetail", "low");
mDataMap.put("noLimit", true);
}
public SubscriptionSearch(ArrayList<?> subscriptionIds) {
super("subscriptionSearch");
mDataMap.put("bodyId", MindRpc.mTivoDevice.tsn);
mDataMap.put("levelOfDetail", "medium");
mDataMap.put("noLimit", true);
mDataMap.put("objectIdAndType", subscriptionIds);
}
public SubscriptionSearch(String collectionId) {
super("subscriptionSearch");
mDataMap.put("bodyId", MindRpc.mTivoDevice.tsn);
mDataMap.put("collectionId", collectionId);
mDataMap.put("levelOfDetail", "medium");
}
}
| 949 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
RecordingFolderItemEmpty.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/RecordingFolderItemEmpty.java | package com.arantius.tivocommander.rpc.request;
import com.arantius.tivocommander.rpc.MindRpc;
public class RecordingFolderItemEmpty extends MindRpcRequest {
public RecordingFolderItemEmpty(String recordingFolderItemId) {
super("recordingFolderItemEmpty");
mDataMap.put("bodyId", MindRpc.mTivoDevice.tsn);
mDataMap.put("recordingFolderItemId", recordingFolderItemId);
}
}
| 401 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
TunerStateEventRegister.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/TunerStateEventRegister.java | package com.arantius.tivocommander.rpc.request;
public class TunerStateEventRegister extends MindRpcRequest {
public TunerStateEventRegister() {
super("tunerStateEventRegister");
mResponseCount = "multiple";
}
}
| 233 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
SubscriptionsReprioritize.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/SubscriptionsReprioritize.java | package com.arantius.tivocommander.rpc.request;
import java.util.ArrayList;
import com.arantius.tivocommander.rpc.MindRpc;
public class SubscriptionsReprioritize extends MindRpcRequest {
public SubscriptionsReprioritize(ArrayList<String> subscriptionIds) {
super("subscriptionsReprioritize");
mDataMap.put("bodyId", MindRpc.mTivoDevice.tsn);
mDataMap.put("subscriptionId", subscriptionIds);
}
}
| 429 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
UiNavigate.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/UiNavigate.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc.request;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class UiNavigate extends MindRpcRequest {
public UiNavigate(String recordingId) {
super("uiNavigate");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("fUseTrioId", "true");
parameters.put("fHideBannerOnEnter", "false");
parameters.put("recordingId", recordingId);
mDataMap.put("uri", "x-tivo:classicui:playback");
mDataMap.put("parameters", parameters);
}
public UiNavigate(List<String> recordingIds, String displayName) {
super("uiNavigate");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("fUseTrioId", "true");
parameters.put("fHideBannerOnEnter", "false");
parameters.put("iCurrentRecording", 0);
parameters.put("recordingId", recordingIds);
if (displayName != null && !"".equals(displayName)) {
parameters.put("folderName", displayName);
}
mDataMap.put("uri", "x-tivo:classicui:playback");
mDataMap.put("parameters", parameters);
}
}
| 1,931 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
UpcomingSearch.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/UpcomingSearch.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc.request;
import com.arantius.tivocommander.Utils;
import com.fasterxml.jackson.databind.JsonNode;
public class UpcomingSearch extends CollectionSearch {
private static final JsonNode mResponseTemplate =
Utils
.parseJson("[{\"type\": \"responseTemplate\", \"fieldName\": [\"offer\"], \"typeName\": \"offerList\"}, {\"type\": \"responseTemplate\", \"fieldName\": [\"title\", \"subtitle\", \"channel\", \"startTime\", \"recordingForOfferId\", \"purchasableFrom\", \"price\", \"drm\", \"contentId\", \"collectionId\", \"offerId\", \"partnerOfferId\", \"hdtv\", \"repeat\", \"episodic\", \"seasonNumber\", \"episodeNum\", \"transportType\", \"transport\"], \"typeName\": \"offer\"}, {\"type\": \"responseTemplate\", \"fieldName\": [\"channelNumber\", \"sourceType\", \"logoIndex\", \"callSign\", \"isDigital\"], \"typeName\": \"channel\"}, {\"type\": \"responseTemplate\", \"fieldName\": [\"maxKeepAfterView\", \"maxKeepAfterDownload\"], \"typeName\": \"drm\"}]");
private static final String[] mNote = new String[] { "recordingForOfferId" };
public UpcomingSearch(String collectionId) {
super(collectionId);
setReqType("offerSearch");
mDataMap.put("count", 50);
mDataMap.put("namespace", "refserver");
mDataMap.put("note", mNote);
mDataMap.put("responseTemplate", mResponseTemplate);
mDataMap.put("searchable", true);
mDataMap.remove("imageRuleset");
}
}
| 2,263 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
CancelRpc.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/CancelRpc.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc.request;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
import com.arantius.tivocommander.Utils;
public class CancelRpc extends MindRpcRequest {
protected Integer mCancelRpcId;
public CancelRpc(int rpcId) {
super("cancel");
mCancelRpcId = rpcId;
}
@Override
public byte[] getBytes() throws UnsupportedEncodingException {
// @formatter:off
String headers = Utils.join("\r\n",
"Type: cancel",
"RpcId: " + mCancelRpcId.toString(),
"SchemaVersion:7");
// @formatter:on
// "+ 2" is the "\r\n" we'll add next.
String reqLine =
String.format(Locale.US, "MRPC/2 %d 0",
headers.getBytes("UTF-8").length + 2);
String request =
Utils.join("\r\n", reqLine, headers, "");
byte[] requestBytes = request.getBytes("UTF-8");
return requestBytes;
}
}
| 1,716 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
TodoRecordingSearch.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/TodoRecordingSearch.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc.request;
import java.util.ArrayList;
import com.arantius.tivocommander.rpc.MindRpc;
import com.fasterxml.jackson.databind.JsonNode;
public class TodoRecordingSearch extends MindRpcRequest {
public TodoRecordingSearch(ArrayList<JsonNode> showIds, String orderBy) {
super("recordingSearch");
mDataMap.put("bodyId", MindRpc.mTivoDevice.tsn);
mDataMap.put("levelOfDetail", "medium");
mDataMap.put("objectIdAndType", showIds);
mDataMap.put("state", new String[] { "inProgress", "scheduled" });
}
}
| 1,372 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
BodyAuthenticate.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/BodyAuthenticate.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc.request;
import java.util.HashMap;
import java.util.Map;
public class BodyAuthenticate extends MindRpcRequest {
public BodyAuthenticate(String mak) {
super("bodyAuthenticate");
Map<String, String> credential = new HashMap<String, String>();
credential.put("type", "makCredential");
credential.put("key", mak);
mDataMap.put("credential", credential);
}
}
| 1,232 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
SuggestionsSearch.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/SuggestionsSearch.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc.request;
import com.arantius.tivocommander.Utils;
import com.fasterxml.jackson.databind.JsonNode;
public class SuggestionsSearch extends CollectionSearch {
private static final JsonNode mImageRulset =
Utils
.parseJson("[{\"type\": \"imageRuleset\", \"name\": \"movie\", \"rule\": [{\"width\": 100, \"ruleType\": \"exactMatchDimension\", \"type\": \"imageRule\", \"imageType\": [\"moviePoster\"], \"height\": 150}]}, {\"type\": \"imageRuleset\", \"name\": \"tvPortrait\", \"rule\": [{\"width\": 120, \"ruleType\": \"exactMatchDimension\", \"type\": \"imageRule\", \"imageType\": [\"showcaseBanner\"], \"height\": 90}]}]");
private static final String[] mNote =
new String[] { "bodyLineupCorrelatedCollectionForCollectionId" };
private static final JsonNode mResponseTemplate =
Utils
.parseJson("[{\"type\": \"responseTemplate\", \"fieldName\": [\"collection\"], \"typeName\": \"collectionList\"}, {\"fieldInfo\": [{\"maxArity\": [2], \"fieldName\": [\"category\"], \"type\": \"responseTemplateFieldInfo\"}], \"fieldName\": [\"image\", \"title\", \"collectionId\", \"collectionType\", \"correlatedCollectionForCollectionId\"], \"typeName\": \"collection\", \"type\": \"responseTemplate\"}, {\"type\": \"responseTemplate\", \"fieldName\": [\"displayRank\", \"image\"], \"typeName\": \"category\"}] ");
public SuggestionsSearch(String collectionId) {
super(collectionId);
mDataMap.put("imageRuleset", mImageRulset);
mDataMap.put("note", mNote);
mDataMap.put("responseTemplate", mResponseTemplate);
}
}
| 2,417 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
VideoPlaybackInfoEventRegister.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/VideoPlaybackInfoEventRegister.java | package com.arantius.tivocommander.rpc.request;
public class VideoPlaybackInfoEventRegister extends MindRpcRequest {
public VideoPlaybackInfoEventRegister() {
super("videoPlaybackInfoEventRegister");
mResponseCount = "multiple";
mDataMap.put("throttleDelay", 1000);
}
public VideoPlaybackInfoEventRegister(int delay) {
super("videoPlaybackInfoEventRegister");
mResponseCount = "multiple";
mDataMap.put("throttleDelay", delay);
}
}
| 480 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
OfferSearch.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/OfferSearch.java | package com.arantius.tivocommander.rpc.request;
import com.arantius.tivocommander.rpc.MindRpc;
public class OfferSearch extends MindRpcRequest {
public OfferSearch() {
super("offerSearch");
mDataMap.put("bodyId", MindRpc.mTivoDevice.tsn);
mDataMap.put("count", 50);
mDataMap.put("namespace", "refserver");
mDataMap.put("searchable", true);
}
public OfferSearch(String searchKey, String searchVal) {
super("offerSearch");
mDataMap.put("bodyId", MindRpc.mTivoDevice.tsn);
mDataMap.put("levelOfDetail", "low");
mDataMap.put("namespace", "refserver");
mDataMap.put("note", new String[] { "recordingForContentId" });
mDataMap.put(searchKey, new String[] { searchVal });
mDataMap.put("searchable", true);
}
public void setChannelsForCollection(String collectionId) {
mDataMap.put("collectionId", new String[] { collectionId });
mDataMap.put("groupBy", new String[] { "channelNumber" });
mDataMap.put("orderBy", new String[] { "channelNumber" });
}
}
| 1,022 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
UnifiedItemSearch.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/UnifiedItemSearch.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc.request;
import com.arantius.tivocommander.Utils;
import com.arantius.tivocommander.rpc.MindRpc;
import com.fasterxml.jackson.databind.JsonNode;
public class UnifiedItemSearch extends MindRpcRequest {
private static final int NUM_RESULTS = 25;
private static final JsonNode mImageRuleset =
Utils
.parseJson("[{\"type\": \"imageRuleset\", \"name\": \"movie\", \"rule\": [{\"width\": 100, \"ruleType\": \"exactMatchDimension\", \"type\": \"imageRule\", \"imageType\": [\"moviePoster\"], \"height\": 150}]}, {\"type\": \"imageRuleset\", \"name\": \"tvLandscape\", \"rule\": [{\"width\": 139, \"ruleType\": \"exactMatchDimension\", \"type\": \"imageRule\", \"imageType\": [\"showcaseBanner\"], \"height\": 104}]}, {\"type\": \"imageRuleset\", \"name\": \"tvPortrait\", \"rule\": [{\"width\": 120, \"ruleType\": \"exactMatchDimension\", \"type\": \"imageRule\", \"imageType\": [\"showcaseBanner\"], \"height\": 90}]}, {\"type\": \"imageRuleset\", \"name\": \"personLandscape\", \"rule\": [{\"width\": 104, \"ruleType\": \"exactMatchDimension\", \"type\": \"imageRule\", \"imageType\": [\"person\"], \"height\": 78}]}, {\"type\": \"imageRuleset\", \"name\": \"personPortrait\", \"rule\": [{\"width\": 113, \"ruleType\": \"exactMatchDimension\", \"type\": \"imageRule\", \"imageType\": [\"person\"], \"height\": 150}]}]");
private static final JsonNode mResponseTemplate =
Utils
.parseJson("[{\"fieldInfo\": [{\"maxArity\": [2], \"fieldName\": [\"category\"], \"type\": \"responseTemplateFieldInfo\"}], \"fieldName\": [\"image\", \"title\", \"collectionId\", \"collectionType\", \"movieYear\", \"starRating\", \"tvRating\", \"mpaaRating\"], \"typeName\": \"collection\", \"type\": \"responseTemplate\"}, {\"fieldInfo\": [{\"maxArity\": [2], \"fieldName\": [\"category\"], \"type\": \"responseTemplateFieldInfo\"}], \"fieldName\": [\"image\", \"title\", \"subtitle\", \"collectionId\", \"collectionType\", \"contentId\", \"movieYear\", \"starRating\", \"tvRating\", \"mpaaRating\"], \"typeName\": \"content\", \"type\": \"responseTemplate\"}, {\"type\": \"responseTemplate\", \"fieldName\": [\"displayRank\", \"image\"], \"typeName\": \"category\"}, {\"type\": \"responseTemplate\", \"fieldName\": [\"first\", \"last\", \"image\", \"personId\"], \"typeName\": \"person\"}, {\"type\": \"responseTemplate\", \"fieldName\": [\"unifiedItem\"], \"typeName\": \"unifiedItemList\"}]");
public UnifiedItemSearch(String keyword) {
super("unifiedItemSearch");
mDataMap.put("bodyId", MindRpc.mTivoDevice.tsn);
mDataMap.put("count", NUM_RESULTS);
mDataMap.put("imageRuleset", mImageRuleset);
mDataMap.put("includeUnifiedItemType", new String[] { "collection",
"content", "person" });
mDataMap.put("keyword", keyword);
mDataMap.put("levelOfDetail", "medium");
mDataMap.put("mergeOverridingCollections", true);
mDataMap.put("numRelevantItems", NUM_RESULTS);
mDataMap.put("orderBy", new String[] { "relevance" });
mDataMap.put("responseTemplate", mResponseTemplate);
mDataMap.put("searchable", true);
}
}
| 3,935 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
Subscribe.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/Subscribe.java | package com.arantius.tivocommander.rpc.request;
import java.util.HashMap;
import com.arantius.tivocommander.rpc.MindRpc;
import com.fasterxml.jackson.databind.JsonNode;
public class Subscribe extends MindRpcRequest {
public Subscribe() {
super("subscribe");
mDataMap.put("bodyId", MindRpc.mTivoDevice.tsn);
mDataMap.put("recordingQuality", "best");
}
public void setCollection(String collectionId, JsonNode channel, int max,
String which, String subscriptionId) {
HashMap<String, Object> idSetSource = new HashMap<String, Object>();
idSetSource.put("channel", channel);
idSetSource.put("collectionId", collectionId);
idSetSource.put("type", "seasonPassSource");
if (subscriptionId != null && !"".equals(subscriptionId)) {
mDataMap.put("subscriptionId", subscriptionId);
}
mDataMap.put("idSetSource", idSetSource);
mDataMap.put("maxRecordings", max);
mDataMap.put("showStatus", which);
}
public void setIgnoreConflicts(boolean ignoreConflicts) {
mDataMap.put("ignoreConflicts", ignoreConflicts);
}
public void setKeepUntil(String behavior) {
mDataMap.put("keepBehavior", behavior);
}
public void setOffer(String offerId, String contentId) {
HashMap<String, String> idSetSource = new HashMap<String, String>();
idSetSource.put("contentId", contentId);
idSetSource.put("offerId", offerId);
idSetSource.put("type", "singleOfferSource");
mDataMap.put("idSetSource", idSetSource);
}
public void setPadding(Integer start, Integer stop) {
if (start != 0) {
mDataMap.put("startTimePadding", start);
}
if (stop != 0) {
mDataMap.put("endTimePadding", stop);
}
}
public void setPriority(Integer priority) {
if (priority > 0) {
mDataMap.put("priority", priority);
}
}
}
| 1,825 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
RecordingUpdate.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/RecordingUpdate.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc.request;
import com.arantius.tivocommander.rpc.MindRpc;
public class RecordingUpdate extends MindRpcRequest {
public RecordingUpdate(String recordingId, String state) {
super("recordingUpdate");
mDataMap.put("bodyId", MindRpc.mTivoDevice.tsn);
mDataMap.put("recordingId", new String[] { recordingId });
mDataMap.put("state", state);
}
}
| 1,211 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
RecordingSearch.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/RecordingSearch.java | package com.arantius.tivocommander.rpc.request;
import java.util.ArrayList;
import com.arantius.tivocommander.rpc.MindRpc;
import com.fasterxml.jackson.databind.JsonNode;
public class RecordingSearch extends MindRpcRequest {
public RecordingSearch(String recordingId) {
super("recordingSearch");
mDataMap.put("bodyId", MindRpc.mTivoDevice.tsn);
if ("deleted".equals(recordingId)) {
mDataMap.put("format", "idSequence");
mDataMap.put("state", new String[] { "deleted" });
} else {
mDataMap.put("recordingId", new String[] { recordingId });
}
mDataMap.put("levelOfDetail", "high");
}
public RecordingSearch(ArrayList<JsonNode> showIds) {
super("recordingSearch");
mDataMap.put("objectIdAndType", showIds);
}
}
| 772 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
PersonSearch.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/PersonSearch.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc.request;
import com.arantius.tivocommander.Utils;
import com.fasterxml.jackson.databind.JsonNode;
public class PersonSearch extends MindRpcRequest {
private static final JsonNode mImageRuleset =
Utils
.parseJson("[{\"type\": \"imageRuleset\", \"name\": \"person\", \"rule\": [{\"width\": 150, \"ruleType\": \"exactMatchDimension\", \"type\": \"imageRule\", \"imageType\": [\"person\"], \"height\": 200}]}]");
public PersonSearch(String personId) {
super("personSearch");
mDataMap.put("imageRuleset", mImageRuleset);
mDataMap.put("levelOfDetail", "high");
mDataMap.put("note", new String[] { "roleForPersonId" });
mDataMap.put("personId", new String[] { personId });
}
}
| 1,567 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
TodoSearch.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/TodoSearch.java | package com.arantius.tivocommander.rpc.request;
import com.arantius.tivocommander.rpc.MindRpc;
public class TodoSearch extends MindRpcRequest {
public TodoSearch() {
super("recordingSearch");
mDataMap.put("bodyId", MindRpc.mTivoDevice.tsn);
mDataMap.put("format", "idSequence");
mDataMap.put("state", new String[] { "inProgress", "scheduled" });
}
}
| 373 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
RecordingFolderItemSearch.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/RecordingFolderItemSearch.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc.request;
import java.util.ArrayList;
import com.arantius.tivocommander.Utils;
import com.arantius.tivocommander.rpc.MindRpc;
import com.fasterxml.jackson.databind.JsonNode;
public class RecordingFolderItemSearch extends MindRpcRequest {
private static final JsonNode mResponseTemplate =
Utils
.parseJson("[{\"type\":\"responseTemplate\",\"fieldName\":[\"recordingFolderItem\"],\"typeName\":\"recordingFolderItemList\"},{\"type\":\"responseTemplate\",\"fieldName\":[\"folderTransportType\",\"folderType\",\"recordingFolderItemId\",\"recordingForChildRecordingId\",\"folderItemCount\",\"recordingStatusType\",\"startTime\",\"title\",\"childRecordingId\"],\"typeName\":\"recordingFolderItem\"},{\"type\":\"responseTemplate\",\"fieldName\":[\"contentId\",\"collectionId\",\"hdtv\",\"channel\",\"startTime\"],\"typeName\":\"recording\"}]");
/** Produces an idSequence of shows for the given folder, all if null. */
public RecordingFolderItemSearch(String folderId, String orderBy) {
super("recordingFolderItemSearch");
addCommonDetails(orderBy);
mDataMap.put("format", "idSequence");
if (folderId != null) {
mDataMap.put("parentRecordingFolderItemId", folderId);
}
}
/** Given a set of IDs, produces details about the shows. */
public RecordingFolderItemSearch(JsonNode showIds, String orderBy) {
super("recordingFolderItemSearch");
addCommonDetails(orderBy);
mDataMap.put("objectIdAndType", showIds);
}
/** Given a set of IDs, produces details about the shows. */
public RecordingFolderItemSearch(ArrayList<?> showIds, String orderBy) {
super("recordingFolderItemSearch");
addCommonDetails(orderBy);
mDataMap.put("objectIdAndType", showIds);
mDataMap.put("state", new String[] { "inProgress", "scheduled" });
}
private void addCommonDetails(String orderBy) {
mDataMap.put("orderBy", new String[] { orderBy });
mDataMap.put("bodyId", MindRpc.mTivoDevice.tsn);
mDataMap.put("note", new String[] { "recordingForChildRecordingId" });
mDataMap.put("responseTemplate", mResponseTemplate);
}
}
| 2,954 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
ContentSearch.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/ContentSearch.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc.request;
import com.arantius.tivocommander.Utils;
import com.fasterxml.jackson.databind.JsonNode;
public class ContentSearch extends BaseSearch {
private static final JsonNode mImageRuleset =
Utils
.parseJson("[{\"type\":\"imageRuleset\",\"name\":\"movie\",\"rule\":[{\"type\":\"imageRule\",\"width\":133,\"ruleType\":\"exactMatchDimension\",\"imageType\":[\"moviePoster\"],\"height\":200}]},{\"type\":\"imageRuleset\",\"name\":\"tvLandscape\",\"rule\":[{\"type\":\"imageRule\",\"width\":139,\"ruleType\":\"exactMatchDimension\",\"imageType\":[\"showcaseBanner\"],\"height\":104}]},{\"type\":\"imageRuleset\",\"name\":\"tvPortrait\",\"rule\":[{\"type\":\"imageRule\",\"width\":200,\"ruleType\":\"exactMatchDimension\",\"imageType\":[\"showcaseBanner\"],\"height\":150}]}]");
private static final String[] mNote =
new String[] { "recordingForContentId" };
private static final JsonNode mResponseTemplate =
Utils
.parseJson("[{\"type\":\"responseTemplate\",\"fieldName\":[\"state\",\"recordingId\"],\"typeName\":\"recording\"},{\"type\":\"responseTemplate\",\"fieldName\":[\"partnerId\",\"contentId\"],\"typeName\":\"offer\"},{\"type\":\"responseTemplate\",\"fieldName\":[\"content\"],\"typeName\":\"contentList\"},{\"type\":\"responseTemplate\",\"fieldInfo\":[{\"type\":\"responseTemplateFieldInfo\",\"maxArity\":[50],\"fieldName\":[\"credit\"]},{\"type\":\"responseTemplateFieldInfo\",\"maxArity\":[2],\"fieldName\":[\"category\"]}],\"fieldName\":[\"contentId\",\"broadbandOfferGroupForContentId\",\"recordingForContentId\",\"hdtv\",\"title\",\"movieYear\",\"subtitle\",\"seasonNumber\",\"episodeNum\",\"episodic\",\"starRating\",\"description\",\"tvRating\",\"mpaaRating\",\"tvAdvisory\",\"category\",\"credit\",\"originalAirYear\",\"image\"],\"typeName\":\"content\"},{\"type\":\"responseTemplate\",\"fieldName\":[\"first\",\"last\",\"role\"],\"typeName\":\"credit\"},{\"type\":\"responseTemplate\",\"fieldName\":[\"displayRank\",\"image\"],\"typeName\":\"category\"},{\"type\":\"responseTemplate\",\"fieldName\":[\"thumbsRating\"],\"typeName\":\"userContent\"},{\"type\":\"responseTemplate\",\"fieldName\":[\"channelNumber\",\"sourceType\",\"logoIndex\",\"callSign\",\"isDigital\"],\"typeName\":\"channel\"}]");
public ContentSearch(String contentId) {
super(null, contentId);
addCommon(mImageRuleset, mNote, mResponseTemplate);
}
}
| 3,246 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
PersonCreditsSearch.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/PersonCreditsSearch.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc.request;
import com.arantius.tivocommander.Utils;
import com.arantius.tivocommander.rpc.MindRpc;
import com.fasterxml.jackson.databind.JsonNode;
public class PersonCreditsSearch extends MindRpcRequest {
private static final JsonNode mImageRuleset =
Utils
.parseJson("[{\"type\": \"imageRuleset\", \"name\": \"movie\", \"rule\": [{\"width\": 100, \"ruleType\": \"exactMatchDimension\", \"type\": \"imageRule\", \"imageType\": [\"moviePoster\"], \"height\": 150}]}, {\"type\": \"imageRuleset\", \"name\": \"tvLandscape\", \"rule\": [{\"width\": 139, \"ruleType\": \"exactMatchDimension\", \"type\": \"imageRule\", \"imageType\": [\"showcaseBanner\"], \"height\": 104}]}]");
private static final JsonNode mResponseTemplate =
Utils
.parseJson("[{\"type\": \"responseTemplate\", \"fieldName\": [\"collection\"], \"typeName\": \"collectionList\"}, {\"fieldInfo\": [{\"maxArity\": [50], \"fieldName\": [\"credit\"], \"type\": \"responseTemplateFieldInfo\"}], \"fieldName\": [\"image\", \"title\", \"collectionId\"], \"typeName\": \"collection\", \"type\": \"responseTemplate\"}, {\"type\": \"responseTemplate\", \"fieldName\": [\"role\", \"personId\"], \"typeName\": \"credit\"}]");
public PersonCreditsSearch(String personId) {
super("collectionSearch");
final String creditJson =
"[{\"personId\": \"" + personId + "\", \"type\": \"credit\"}]";
mDataMap.put("bodyId", MindRpc.mTivoDevice.tsn);
mDataMap.put("count", 50);
mDataMap.put("credit", Utils.parseJson(creditJson));
mDataMap.put("imageRuleset", mImageRuleset);
mDataMap.put("levelOfDetail", "high");
mDataMap.put("responseTemplate", mResponseTemplate);
}
}
| 2,545 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
BaseSearch.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/BaseSearch.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc.request;
import com.arantius.tivocommander.rpc.MindRpc;
import com.fasterxml.jackson.databind.JsonNode;
public class BaseSearch extends MindRpcRequest {
public BaseSearch(String collectionId, String contentId) {
super(""); // We'll figure out type next.
if (collectionId != null) {
setReqType("collectionSearch");
mDataMap.put("collectionId", new String[] { collectionId });
mDataMap.put("filterUnavailable", false);
} else if (contentId != null) {
setReqType("contentSearch");
mDataMap.put("contentId", new String[] { contentId });
mDataMap.put("filterUnavailableContent", false);
}
mDataMap.put("bodyId", MindRpc.mTivoDevice.tsn);
mDataMap.put("levelOfDetail", "high");
}
protected void addCommon(JsonNode imageRuleset, String[] note,
JsonNode responseTemplate) {
mDataMap.put("imageRuleset", imageRuleset);
mDataMap.put("note", note);
mDataMap.put("responseTemplate", responseTemplate);
}
}
| 1,836 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
BodyConfigSearch.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/BodyConfigSearch.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc.request;
import com.arantius.tivocommander.rpc.MindRpc;
public class BodyConfigSearch extends MindRpcRequest {
public BodyConfigSearch() {
super("bodyConfigSearch");
mDataMap.put("bodyId", MindRpc.mTivoDevice.tsn);
}
}
| 1,084 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
KeyEventSend.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/KeyEventSend.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc.request;
public class KeyEventSend extends MindRpcRequest {
public KeyEventSend(char letter) {
super("keyEventSend");
mDataMap.put("event", "ascii");
mDataMap.put("value", (int) letter);
}
public KeyEventSend(String key) {
super("keyEventSend");
mDataMap.put("event", key);
}
}
| 1,162 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
CollectionSearch.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/CollectionSearch.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc.request;
import com.arantius.tivocommander.Utils;
import com.fasterxml.jackson.databind.JsonNode;
public class CollectionSearch extends BaseSearch {
protected static final JsonNode mImageRuleset =
Utils
.parseJson("[{\"type\":\"imageRuleset\",\"name\":\"movie\",\"rule\":[{\"type\":\"imageRule\",\"width\":133,\"ruleType\":\"exactMatchDimension\",\"imageType\":[\"moviePoster\"],\"height\":200}]},{\"type\":\"imageRuleset\",\"name\":\"tvLandscape\",\"rule\":[{\"type\":\"imageRule\",\"width\":139,\"ruleType\":\"exactMatchDimension\",\"imageType\":[\"showcaseBanner\"],\"height\":104}]}]}]");
protected static final String[] mNote = new String[] {};
protected static final JsonNode mResponseTemplate =
Utils
.parseJson("[{\"type\": \"responseTemplate\", \"fieldName\": [\"subscriptionType\"], \"typeName\": \"subscriptionIdentifier\"}, {\"type\": \"responseTemplate\", \"fieldName\": [\"state\", \"recordingId\", \"subscriptionIdentifier\"], \"typeName\": \"recording\"}, {\"type\": \"responseTemplate\", \"fieldName\": [\"partnerId\", \"contentId\"], \"typeName\": \"offer\"}, {\"type\": \"responseTemplate\", \"fieldName\": [\"collection\"], \"typeName\": \"collectionList\"}, {\"fieldInfo\": [{\"maxArity\": [50], \"fieldName\": [\"credit\"], \"type\": \"responseTemplateFieldInfo\"}, {\"maxArity\": [2], \"fieldName\": [\"category\"], \"type\": \"responseTemplateFieldInfo\"}], \"fieldName\": [\"broadbandOfferGroupForCollectionId\", \"broadcastOfferGroupForCollectionId\", \"collectionId\", \"collectionType\", \"hdtv\", \"title\", \"movieYear\", \"episodic\", \"starRating\", \"description\", \"tvRating\", \"mpaaRating\", \"category\", \"credit\", \"userContentForCollectionId\", \"image\"], \"typeName\": \"collection\", \"type\": \"responseTemplate\"}, {\"type\": \"responseTemplate\", \"fieldName\": [\"example\"], \"typeName\": \"offerGroup\"}, {\"type\": \"responseTemplate\", \"fieldName\": [\"first\", \"last\", \"role\"], \"typeName\": \"credit\"}, {\"type\": \"responseTemplate\", \"fieldName\": [\"displayRank\"], \"typeName\": \"category\"}, {\"type\": \"responseTemplate\", \"fieldName\": [\"thumbsRating\"], \"typeName\": \"userContent\"}, {\"type\": \"responseTemplate\", \"fieldName\": [\"channelNumber\", \"sourceType\", \"logoIndex\", \"callSign\", \"isDigital\"], \"typeName\": \"channel\"}]");
public CollectionSearch(String collectionId) {
super(collectionId, null);
addCommon(mImageRuleset, mNote, mResponseTemplate);
}
}
| 3,354 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
Unsubscribe.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/Unsubscribe.java | package com.arantius.tivocommander.rpc.request;
import com.arantius.tivocommander.rpc.MindRpc;
public class Unsubscribe extends MindRpcRequest {
public Unsubscribe(String subscriptionId) {
super("unsubscribe");
mDataMap.put("bodyId", MindRpc.mTivoDevice.tsn);
mDataMap.put("subscriptionId", subscriptionId);
}
}
| 330 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
MindRpcRequest.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/MindRpcRequest.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc.request;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import com.arantius.tivocommander.Utils;
import com.arantius.tivocommander.rpc.MindRpc;
public abstract class MindRpcRequest {
private String mReqType;
protected Map<String, Object> mDataMap = new HashMap<String, Object>();
protected String mResponseCount = "single";
protected int mRpcId;
protected int mSessionId = 0;
public MindRpcRequest(String type) {
mRpcId = MindRpc.getRpcId();
mSessionId = MindRpc.getSessionId();
setReqType(type);
}
public Map<String, Object> getDataMap() {
return mDataMap;
}
public String getDataString() {
String data = Utils.stringifyToJson(mDataMap);
if (data == null) {
Utils.logError("Stringify failure; request body");
}
return data;
}
public String getReqType() {
return mReqType;
}
public int getRpcId() {
return mRpcId;
}
public void setLevelOfDetail(String levelOfDetail) {
mDataMap.put("levelOfDetail", levelOfDetail);
}
public void setReqType(String type) {
mReqType = type;
mDataMap.put("type", mReqType);
}
/**
* Convert the request into a well formatted byte array for the network.
* @throws UnsupportedEncodingException
*/
public byte[] getBytes() throws UnsupportedEncodingException {
// @formatter:off
String headers = Utils.join("\r\n",
"Type: request",
"RpcId: " + getRpcId(),
"SchemaVersion: 7",
"Content-Type: application/json",
"RequestType: " + mReqType,
"ResponseCount: " + mResponseCount,
"BodyId: " + MindRpc.mTivoDevice.tsn,
"X-ApplicationName: Quicksilver ",
"X-ApplicationVersion: 1.2 ",
String.format("X-ApplicationSessionId: 0x%x", mSessionId));
// @formatter:on
String body = getDataString();
// NOTE: The lengths here must be the length in *bytes*, not characters!
// Thus all the .getBytes() conversions to find the proper lengths.
// "+ 2" is the "\r\n" we'll add next.
String reqLine =
String.format(Locale.US, "MRPC/2 %d %d",
headers.getBytes("UTF-8").length + 2,
body.getBytes("UTF-8").length);
String request = Utils.join("\r\n", reqLine, headers, body);
byte[] requestBytes = request.getBytes("UTF-8");
return requestBytes;
}
}
| 3,256 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
WhatsOnSearch.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/WhatsOnSearch.java | package com.arantius.tivocommander.rpc.request;
public class WhatsOnSearch extends MindRpcRequest {
public WhatsOnSearch() {
super("whatsOnSearch");
mResponseCount = "multiple";
}
}
| 203 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
CreditsSearch.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/request/CreditsSearch.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc.request;
import com.arantius.tivocommander.Utils;
import com.fasterxml.jackson.databind.JsonNode;
public class CreditsSearch extends BaseSearch {
private static final JsonNode mImageRuleset =
Utils
.parseJson("[{\"type\": \"imageRuleset\", \"name\": \"personPortrait\", \"rule\": [{\"width\": 113, \"ruleType\": \"exactMatchDimension\", \"type\": \"imageRule\", \"imageType\": [\"person\"], \"height\": 150}]}]");
private static final String[] mNote = new String[] {};
private static final JsonNode mResponseTemplateColl =
Utils
.parseJson("[{\"type\": \"responseTemplate\", \"fieldName\": [\"collection\"], \"typeName\": \"collectionList\"}, {\"fieldInfo\": [{\"maxArity\": [50], \"fieldName\": [\"credit\"], \"type\": \"responseTemplateFieldInfo\"}], \"fieldName\": [ \"collectionId\", \"collectionType\", \"credit\", \"title\"], \"typeName\": \"collection\", \"type\": \"responseTemplate\"}, {\"type\": \"responseTemplate\", \"fieldName\": [\"first\", \"last\", \"role\", \"image\", \"personId\", \"characterName\"], \"typeName\": \"credit\"}]");
private static final JsonNode mResponseTemplateCont =
Utils
.parseJson("[{\"type\": \"responseTemplate\", \"fieldName\": [\"content\"], \"typeName\": \"contentList\" }, {\"fieldInfo\": [{\"maxArity\": [50], \"fieldName\": [\"credit\"], \"type\": \"responseTemplateFieldInfo\"}], \"fieldName\": [\"contentId\", \"collectionId\", \"collectionType\", \"credit\", \"title\"], \"typeName\": \"content\", \"type\": \"responseTemplate\"}, {\"type\": \"responseTemplate\", \"fieldName\": [\"first\", \"last\", \"role\", \"image\", \"personId\", \"characterName\"], \"typeName\": \"credit\"}]");
public CreditsSearch(String collectionId, String contentId) {
super(collectionId, contentId);
addCommon(mImageRuleset, mNote,
collectionId != null ? mResponseTemplateColl : mResponseTemplateCont);
}
}
| 2,790 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
MindRpcResponseFactory.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/response/MindRpcResponseFactory.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc.response;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import com.arantius.tivocommander.Utils;
import com.fasterxml.jackson.databind.JsonNode;
public class MindRpcResponseFactory {
public MindRpcResponse create(byte[] headers, byte[] body) {
Boolean isFinal = true;
int rpcId = 0;
String line;
BufferedReader headerReader =
new BufferedReader(new StringReader(new String(headers)));
try {
while ((line = headerReader.readLine()) != null) {
if (line.length() > 9 && "IsFinal:".equals(line.substring(0, 8))) {
isFinal = "true".equals(line.substring(9));
} else if (line.length() > 7 && "RpcId:".equals(line.substring(0, 6))) {
rpcId = Integer.parseInt(line.substring(7));
}
}
} catch (IOException e) {
}
String bodyStr = new String(body);
JsonNode bodyObj = Utils.parseJson(bodyStr);
if (bodyObj == null) {
Utils.logError("Parse failure; response body");
return null;
} else {
if (bodyObj.path("type").asText().equals("error")) {
Utils.logError("Response type is error! " + bodyStr);
}
return new MindRpcResponse(isFinal, rpcId, bodyObj);
}
}
}
| 2,098 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
MindRpcResponse.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/response/MindRpcResponse.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc.response;
import com.fasterxml.jackson.databind.JsonNode;
public class MindRpcResponse {
private final JsonNode mBody;
private final Boolean mIsFinal;
private final int mRpcId;
private final String mRespType;
public MindRpcResponse(Boolean isFinal, int rpcId, JsonNode bodyObj) {
mBody = bodyObj;
mIsFinal = isFinal;
mRpcId = rpcId;
mRespType = bodyObj.path("type").asText();
}
public JsonNode getBody() {
return mBody;
}
public int getRpcId() {
return mRpcId;
}
public String getRespType() {
return mRespType;
}
public Boolean isFinal() {
return mIsFinal;
}
}
| 1,479 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
MindRpcResponseListener.java | /FileExtraction/Java_unseen/arantius_TiVo-Commander/src/com/arantius/tivocommander/rpc/response/MindRpcResponseListener.java | /*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander.rpc.response;
public interface MindRpcResponseListener {
/**
* Handle the response, if appropriate; return true if handled, false if not.
*
* @param response The new response object being dispatched.
*/
public void onResponse(MindRpcResponse response);
}
| 1,119 | Java | .java | arantius/TiVo-Commander | 29 | 8 | 2 | 2011-08-15T22:49:33Z | 2021-04-02T22:05:57Z |
TsTasks.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/test/net.heartsome.cat.ts.test.ui/src/net/heartsome/cat/ts/test/ui/tasks/TsTasks.java | package net.heartsome.cat.ts.test.ui.tasks;
import net.heartsome.cat.ts.test.ui.constants.TsUIConstants;
import net.heartsome.test.swtbot.utils.HSBot;
import org.eclipse.swtbot.swt.finder.exceptions.WidgetNotFoundException;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
/**
* 一些基本任务
* @author felix_lu
*/
public final class TsTasks {
/**
*
*/
private TsTasks() {
}
/**
* 解析状态栏中的数据
* @param originalText
* 状态栏原始文本
* @param groupSign
* 分组标记
* @param delimiter
* 分隔符
* @param key
* 状态栏项的名称
* @return String 指定状态栏项的值
*/
public static String getStatusValueByKey(String originalText, String groupSign, String delimiter, String key) {
originalText = originalText.replace("\n", "");
String[] statusGroup = originalText.split(groupSign);
String[] statusItem = null;
for (int i = 0; i < statusGroup.length; i++) {
String statusText = statusGroup[i];
if (statusText != null && statusText.contains(key)) {
statusItem = statusGroup[i].split(delimiter);
return statusItem[1];
}
}
return null;
}
/**
* 关掉多余的对话框,以避免影响后面执行的用例;
*/
public static void closeDialogs() {
SWTBotShell[] shells = HSBot.bot().shells();
int len = shells.length;
if (len > 1) {
org.eclipse.swtbot.swt.finder.utils.SWTBotPreferences.TIMEOUT = 1000; // 减少等待时间
for (int i = len - 1; i >= 1; i--) {
try {
if (shells[i].bot().button(TsUIConstants.getString("btnCancel")).isActive()) {
shells[i].bot().button(TsUIConstants.getString("btnCancel")).click();
}
} catch (WidgetNotFoundException e1) {
try {
if (shells[i].bot().button(TsUIConstants.getString("btnOK")).isActive()) {
shells[i].bot().button(TsUIConstants.getString("btnOK")).click();
}
} catch (WidgetNotFoundException e2) {
try {
if (shells[i].bot().button(TsUIConstants.getString("btnClose")).isActive()) {
shells[i].bot().button(TsUIConstants.getString("btnClose")).click();
} else {
shells[i].close();
}
} catch (WidgetNotFoundException e3) {
shells[i].close();
}
}
}
}
org.eclipse.swtbot.swt.finder.utils.SWTBotPreferences.TIMEOUT = 5000; // 恢复默认的超时时间
}
}
}
| 2,413 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
SegmentAsserts.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/test/net.heartsome.cat.ts.test.ui/src/net/heartsome/cat/ts/test/ui/tasks/SegmentAsserts.java | package net.heartsome.cat.ts.test.ui.tasks;
import static org.junit.Assert.assertTrue;
import net.heartsome.cat.ts.test.ui.editors.XlfEditor;
import net.heartsome.cat.ts.test.ui.utils.XliffUtil;
import net.heartsome.test.swtbot.widgets.HsSWTBotStyledText;
/**
* TS 的一些断言方法,其中有些是直接断言,有些则是返回布尔值
* @author felix_lu
*/
public final class SegmentAsserts {
/**
*
*/
private SegmentAsserts() {
}
/**
* 断言文本段可编辑
* @param xu
* 文本段对应的 XliffUtil 对象
*/
public static void segIsEditable(XliffUtil xu) {
assertTrue("The segment is not editable.", xu.tuIsEditable());
}
/**
* 判断指定的文本段可以在给出的 index 处分割(即不在文本段首、末位置)
* @param st
* 文本段内容对应的 StyledText 对象
* @param index
* 分割点索引
* @return boolean True 表示可以在该处分割
*/
public static boolean indexIsSplitable(HsSWTBotStyledText st, int index) {
int length = st.getText().length(); // TODO 增加分割点在内部标记上的判断
return index > 0 && index < length;
}
/**
* 判断给出的两个文本段是否可以合并
* @param xe
* 文本段所在的 XlfEditor 对象
* @param xu1
* 第一个文本段对应的 XliffUtil 对象
* @param xu2
* 第二个文本段对应的 XliffUtil 对象
* @return boolean
*/
public static boolean segsAreMergeable(XlfEditor xe, XliffUtil xu1, XliffUtil xu2) {
if (!xe.isSorted()) { // 编辑器未按源或目标文本进行排序,因为排序后显示的顺序与文件中的物理顺序极有可能不同
if (xu1.tuIsEditable() && xu2.tuIsEditable()) { // 两个文本段均未批准、未锁定
if (xu1.getXlfFile().equals(xu2.getXlfFile())) { // 两个文本段来自同一个 XLIFF 文件
if (xu1.getOriginalFile().equals(xu2.getOriginalFile())) { // 两个文本段在 XLIFF 文件中属于同一个 <file> 节点
if (xu1.getRowID().equals(xu2.getPrevNotNullXU().getRowID())
&& xu2.getRowID().equals(xu1.getNextNotNullXU().getRowID())) { // 是否为两个连续的非空文本段
return true;
}
}
}
}
}
return false;
}
/**
* 断言文本段已被成功分割
* @param tuid
* 分割前的文本段 trans-unit id
* @param expectedText
* 由分割前的文本段源文本内容在指定位置分割后得到的两个字符串所组成的数组
* @param xu
* 分割后的两个文本段对应的 XLIFFUtil 对象所组成的数组
*/
public static void segIsSplit(String tuid, String[] expectedText, XliffUtil[] xu) {
// 分割后的两个新文本段在同一个以分割前文本段的 tuid 为 id 的 group 中
String groupId = xu[0].getAttributeOfGroup("id");
assertTrue(groupId.equals(xu[1].getAttributeOfGroup("id")));
assertTrue(tuid.equals(groupId));
assertTrue("hs-split".equals(xu[0].getAttributeOfGroup("ts")));
// 两个新文本段的 tuid
assertTrue((tuid + "-1").equals(xu[0].getAttributeOfTU("id")));
assertTrue((tuid + "-2").equals(xu[1].getAttributeOfTU("id")));
// 源文本内容:可能是标记源代码状态,也可能是简单标记状态
assertTrue(expectedText[0].equals(xu[0].getSourceText()) || expectedText[0].equals(xu[0].getSourceTextTagged()));
assertTrue(expectedText[1].equals(xu[1].getSourceText()) || expectedText[1].equals(xu[1].getSourceTextTagged()));
// 目标文本段状态:目标文本为空时 new、非空时 translated
targetStatus(xu[0]);
targetStatus(xu[1]);
}
/**
* 断言文本段没有被分割
* @param tuid
* 尝试分割前的文本段 trans-unit id
* @param expectedText
* 尝试分割前的文本段源文本内容
* @param xu
* 分割后的文本段对应的 XLIFFUtil 对象
*/
public static void segNotSplit(String tuid, String expectedText, XliffUtil xu) {
assertTrue("Parameters should not be null.", tuid != null && expectedText != null && xu != null);
String newTUID = xu.getAttributeOfTU("id");
assertTrue("TUID: " + tuid + " is not the same as the new one.", tuid.equals(newTUID));
String text = xu.getSourceText();
assertTrue("Source text: " + expectedText + " is not the same as the new one.", expectedText.equals(text)
|| expectedText.equals(xu.getSourceTextTagged()));
}
/**
* 断言指定的两个文本段已经成功合并
* @param xu
* 两个要合并的文本段对应的 XliffUtil 对象
* @param tuid
* 两个文本段在合并之前的 trans-unit id 值
* @param expectedText
* 两个文本段合并后的源文本预期内容
*/
public static void segsAreMerged(XliffUtil[] xu, String[] tuid, String expectedText) {
// 合并前的两个 trans-unit 仍然存在且 id 不变
// 此处不直接用 getTUID() 方法的原因是该方法不是实时地从 XLIFF 文件中读数据,
// 而是直接返回通过 rowID 解析得到的成员变量值。
assertTrue(tuid[0].equals(xu[0].getAttributeOfTU("id")));
// FIXME assertTrue(tuid[1].equals(xu[1].getAttributeOfTU("id")));
// 源文本内容
assertTrue(expectedText.equals(xu[0].getSourceText()));
assertTrue(xu[1].getSourceText() == null || "".equals(xu[1].getSourceText()));
// trans-unit 节点的批准和锁定属性
assertTrue(xu[0].tuIsEditable());
// FIXME assertTrue(xu[1].tuIsApproved() && !xu[1].tuIsTranslatable());
// 目标文本段状态
// FIXME targetStatus(xu[0]);
// FIXME targetStatus(xu[1]);
}
/**
* 断言指定的两个文本段没有被合并
* @param xu
* 两个要合并的文本段对应的 XliffUtil 对象
* @param tuid
* 两个文本段在合并之前的 trans-unit id 值
* @param sourceText
* 两个文本段在合并之前的源文本内容
*/
public static void segsNotMerged(XliffUtil[] xu, String[] tuid, String[] sourceText) {
// 尝试合并前的两个 trans-unit 不变
// 此处不直接用 getTUID() 方法的原因是该方法不是实时地从 XLIFF 文件中读数据,
// 而是直接返回通过 rowID 解析得到的成员变量值。
assertTrue(tuid[0].equals(xu[0].getAttributeOfTU("id")));
// assertTrue(tuid[1].equals(xu[1].getAttributeOfTU("id")));
// 源文本内容
assertTrue(sourceText[0].equals(xu[0].getSourceText()));
assertTrue(sourceText[1].equals(xu[1].getSourceText()));
}
/**
* 断言指定的文本段没有被改动
* @param xu
* XliffUtil 对象
* @param tuid
* 尝试改动之前的文本段 trans-unit id
* @param sourceText
* 尝试改动之前的源文本内容
*/
public static void segNoChange(XliffUtil xu, String tuid, String sourceText) {
assertTrue(tuid.equals(xu.getAttributeOfTU("id")));
assertTrue(sourceText.equals(xu.getSourceText()));
}
/**
* 断言目标文本状态:当存在 target 节点且目标文本非空时为 translated、 目标文本为空时 new,没有 state 属性时为 null
* @param xu
* 要验证的文本段对应的 XliffUtil 对象
*/
public static void targetStatus(XliffUtil xu) {
String targetText = xu.getTargetText();
if (targetText != null) {
String targetStatus = xu.getTargetStatus();
if ("".equals(targetText)) {
assertTrue(targetStatus == null || "new".equals(targetStatus));
} else {
assertTrue("translated".equals(targetStatus));
}
}
}
}
| 7,571 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Waits.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/test/net.heartsome.cat.ts.test.ui/src/net/heartsome/cat/ts/test/ui/tasks/Waits.java | package net.heartsome.cat.ts.test.ui.tasks;
import net.heartsome.cat.ts.test.ui.constants.TsUIConstants;
import net.heartsome.cat.ts.test.ui.waits.IsProjectExist;
import net.heartsome.cat.ts.test.ui.waits.IsProjectNotExist;
import net.heartsome.test.swtbot.utils.HSBot;
import net.heartsome.test.swtbot.waits.IsProjectDirExist;
import net.heartsome.test.swtbot.waits.IsProjectDirNotExist;
import net.heartsome.test.swtbot.waits.IsShellClosed;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
import org.hamcrest.core.IsEqual;
/**
* @author felix_lu
* @version
* @since JDK1.6
*/
public final class Waits {
private static SWTBot bot = HSBot.bot();
/**
*
*/
private Waits() {
}
/**
* 等待项目在项目导航树上出现
* @param prjName
* 项目名称 ;
*/
public static void prjExistOnTree(String prjName) {
bot.waitUntil(new IsProjectExist(prjName));
}
/**
* 等待项目从项目导航树上消失
* @param prjName
* 项目名称 ;
*/
public static void prjNotExistOnTree(String prjName) {
bot.waitUntil(new IsProjectNotExist(prjName));
}
/**
* 等待项目目录在工作空间中出现
* @param prjName
* ;
*/
public static void prjExistInWorkspace(String prjName) {
bot.waitUntil(new IsProjectDirExist(prjName));
}
/**
* 等待项目目录从工作空间中消失
* @param prjName
* ;
*/
public static void prjNotExistInWorkspace(String prjName) {
bot.waitUntil(new IsProjectDirNotExist(prjName));
}
/**
* 等待对话框关闭
* @param shell
* 对话框 ;
*/
public static void shellClosed(SWTBotShell shell) {
bot.waitUntil(new IsShellClosed(new IsEqual<Shell>(shell.widget)));
}
/**
* 判断当前激活的对话框是否为进度对话框,若是则等待其关闭,否则不做任何事 ;
*/
public static void progressFinished() {
SWTBotShell dlg = bot.activeShell();
if (dlg.getText().equals(TsUIConstants.getString("dlgTitleProgressInformation"))) {
shellClosed(dlg);
}
}
}
| 2,145 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConfirmDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/test/net.heartsome.cat.ts.test.ui/src/net/heartsome/cat/ts/test/ui/msgdialogs/ConfirmDialog.java | package net.heartsome.cat.ts.test.ui.msgdialogs;
import net.heartsome.cat.ts.test.ui.constants.TsUIConstants;
import net.heartsome.test.swtbot.utils.HSBot;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotButton;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotLabel;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
/**
* 确认对话框:只有 OK 和 Cancel 按钮
* @author felix_lu
*/
public class ConfirmDialog extends SWTBotShell {
/** 对话框标题文本:提示信息 */
public static String dlgTitleTips = TsUIConstants.getString("dlgTitleTips");
/** 确认信息:是否确实要从服务器上删除数据库。 */
public static String msgDeleteDatabaseFromServer = TsUIConstants.getString("msgDeleteDatabaseFromServer");
private SWTBot dialogBot = this.bot();
private String msg;
/**
* @param shellIndex
* 对话框所在 Shell 索引号
* @param msg
* 信息内容
*/
public ConfirmDialog(int shellIndex, String msg) {
super(HSBot.bot().shells()[shellIndex].widget);
this.msg = msg;
}
/**
* 不指定标题和索引时,默认为通用标题 Confirm
* @param msg
* 信息内容
*/
public ConfirmDialog(String msg) {
this(TsUIConstants.getString("dlgTitleConfirm"), msg);
}
/**
* @param dialogTitle
* 对话框标题
* @param msg
* 信息内容
*/
public ConfirmDialog(String dialogTitle, String msg) {
super(HSBot.bot().shell(dialogTitle).widget);
this.msg = msg;
}
/**
* @return 按钮:取消;
*/
public SWTBotButton btnCancel() {
return dialogBot.button(TsUIConstants.getString("btnCancel"));
}
/**
* @return 按钮:确定;
*/
public SWTBotButton btnOK() {
return dialogBot.button(TsUIConstants.getString("btnOK"));
}
/**
* @return 文字标签:信息内容;
*/
public SWTBotLabel lblMessage() {
return dialogBot.label(msg);
}
}
| 1,965 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConfirmProjectDeleteDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/test/net.heartsome.cat.ts.test.ui/src/net/heartsome/cat/ts/test/ui/msgdialogs/ConfirmProjectDeleteDialog.java | package net.heartsome.cat.ts.test.ui.msgdialogs;
import static org.junit.Assert.assertTrue;
import java.text.MessageFormat;
import net.heartsome.cat.ts.test.ui.constants.TsUIConstants;
import net.heartsome.test.swtbot.utils.HSBot;
import net.heartsome.test.utilities.common.FileUtil;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotButton;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotLabel;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotRadio;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
/**
* 确认对话框:删除项目
* @author felix_lu
* @version
* @since JDK1.6
*/
public class ConfirmProjectDeleteDialog extends SWTBotShell {
private SWTBot dialogBot = this.bot();
private String prjName;
// /**
// * 按标题查找对话框
// */
// public ConfirmProjectDeleteDialog() {
// // super(HSBot.bot().shell(TsUIConstants.getString("dlgTitleConfirmProjectDelete")).widget);
// }
/**
* @param prjName
* 项目名称
*/
public ConfirmProjectDeleteDialog(String prjName) {
super(HSBot.bot().shells()[1].widget); // 由于在 MAC OS 中该对话框没有独立的标题栏,所以无法通过对话框标题来确定。
this.prjName = prjName;
assertTrue(msgConfirmDeleteProject().isVisible());
}
/**
* @return 按钮:否;
*/
public SWTBotButton btnNo() {
return dialogBot.button(TsUIConstants.getString("btnNo"));
}
/**
* @return 按钮:是;
*/
public SWTBotButton btnYes() {
return dialogBot.button(TsUIConstants.getString("btnYes"));
}
// /**
// * @return 按钮:预览 未展开;
// */
// public SWTBotButton btnPreviewCollapsed() {
// return dialogBot.button(TsUIConstants.getString("btnPreviewCollapsed"));
// }
//
// /**
// * @return 按钮:预览 展开;
// */
// public SWTBotButton btnPreviewExpanded() {
// return dialogBot.button(TsUIConstants.getString("btnPreviewExpanded"));
// }
//
// /**
// * @return 复选框:删除磁盘内容;
// */
// public SWTBotCheckBox chkbxDeleteProjectContentsOnDisk() {
// return dialogBot.checkBox(TsUIConstants.getString("chkbxDeleteProjectContentsOnDisk"));
// }
/**
* @return 文字标签:确认是否删除项目;
*/
public SWTBotLabel msgConfirmDeleteProject() {
assertTrue("参数错误,项目名称为 null。", prjName != null);
return dialogBot.label(MessageFormat.format(TsUIConstants.getString("msgConfirmDeleteProject"), prjName));
}
/**
* @return 单选按钮:同时删除目录下的内容;
*/
public SWTBotRadio radBtnAlsoDeleteContentsUnder() {
assertTrue("参数错误,项目名称为 null。", prjName != null);
String path = FileUtil.joinPath(FileUtil.getWorkspacePath(), prjName);
String msg = TsUIConstants.getString("radBtnAlsoDeleteContentsUnder");
return dialogBot.radio(MessageFormat.format(msg, path));
}
/**
* @return 单选按钮:不删除内容;
*/
public SWTBotRadio radBtnDoNotDeleteContents() {
return dialogBot.radio(TsUIConstants.getString("radBtnDoNotDeleteContents"));
}
}
| 3,075 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ProgressDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/test/net.heartsome.cat.ts.test.ui/src/net/heartsome/cat/ts/test/ui/msgdialogs/ProgressDialog.java | package net.heartsome.cat.ts.test.ui.msgdialogs;
import net.heartsome.cat.ts.test.ui.constants.TsUIConstants;
import net.heartsome.test.swtbot.utils.HSBot;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotButton;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotCheckBox;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotLabel;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
/**
* 进度对话框
* @author felix_lu
*/
public class ProgressDialog extends SWTBotShell {
/** 对话框标题:进度信息 */
public static final String TITLE_PROGRESS_INFO = "dlgTitleProgressInformation";
/** 对话框标题:预翻译进度 */
public static final String TITLE_PRE_TRANSLATING = "dlgTitlePreTranslating";
/** 信息内容:正在预翻译 */
public static final String MSG_PRE_TRANSLATING = "msgPreTranslating";
private SWTBot dlgBot = this.bot();
/**
* @param dialogTitleKey
* 进度对话框标题在资源文件中的 Key,请使用本类常量
*/
public ProgressDialog(String dialogTitleKey) {
super(HSBot.bot().shell(TsUIConstants.getString(dialogTitleKey)).widget);
}
/**
* @param msgKey 信息内容在资源文件中的 Key,请使用本类常量
* @return 文字标签:进度信息内容;
*/
public SWTBotLabel lblMsg(String msgKey) {
return dlgBot.label(TsUIConstants.getString(msgKey));
}
/**
* @return 按钮:取消;
*/
public SWTBotButton btnCancel() {
return dlgBot.button(TsUIConstants.getString("btnCancel"));
}
/**
* @return 按钮:详情 未展开;
*/
public SWTBotButton btnDetailsCollapsed() {
return dlgBot.button(TsUIConstants.getString("btnDetailsCollapsed"));
}
/**
* @return 按钮:详情 展开;
*/
public SWTBotButton btnDetailsExpanded() {
return dlgBot.button(TsUIConstants.getString("btnDetailsExpanded"));
}
/**
* @return 按钮:在后台运行;
*/
public SWTBotButton btnRunInBackground() {
return dlgBot.button(TsUIConstants.getString("btnRunInBackground"));
}
/**
* @return 复选框:总是在后台运行;
*/
public SWTBotCheckBox chkbxAlwaysRunInBackground() {
return dlgBot.checkBox(TsUIConstants.getString("chkbxAlwaysRunInBackground"));
}
}
| 2,259 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
InformationDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/test/net.heartsome.cat.ts.test.ui/src/net/heartsome/cat/ts/test/ui/msgdialogs/InformationDialog.java | package net.heartsome.cat.ts.test.ui.msgdialogs;
import net.heartsome.cat.ts.test.ui.constants.TsUIConstants;
import net.heartsome.test.swtbot.utils.HSBot;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotButton;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotLabel;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
/**
* 信息对话框:只有一个 OK 按钮
* @author felix_lu
*/
public class InformationDialog extends SWTBotShell {
/** 对话框标题文本:提示信息 */
public static String dlgTitleTips = TsUIConstants.getString("dlgTitleTips");
/** 对话框标题文本:错误提示 */
public static String dlgTitleErrorInfo = TsUIConstants.getString("dlgTitleErrorInfo");
public static String dleTitleError = TsUIConstants.getString("dlgTitleError");
/** 提示信息:服务器为必填项。 */
public static String msgServerIsRequired = TsUIConstants.getString("msgServerIsRequired");
/** 提示信息:端口为必填项。 */
public static String msgPortIsRequired = TsUIConstants.getString("msgPortIsRequired");
/** 提示信息:实例为必填项。 */
public static String msgInstanceIsRequired = TsUIConstants.getString("msgInstanceIsRequired");
/** 提示信息:路径为必填项。 */
public static String msgPathIsRequired = TsUIConstants.getString("msgPathIsRequired");
/** 提示信息:用户名为必填项。 */
public static String msgUsernameIsRequired = TsUIConstants.getString("msgUsernameIsRequired");
/** 提示信息:连接错误。 */
public static String msgServerConnectionError = TsUIConstants.getString("msgServerConnectionError");
/** 提示信息:库与项目语言对无匹配。 */
public static String msgNoMatchInDB = TsUIConstants.getString("msgNoMatchInDB");
private SWTBot dialogBot = this.bot();
private String msg;
/**
* @param shellIndex
* 对话框 Shell 索引,适用无标题的对话框
* @param msg
* 信息内容在资源文件中的 Key
*/
public InformationDialog(int shellIndex, String msg) {
super(HSBot.bot().shells()[shellIndex].widget);
this.msg = msg;
}
/**
* 不提供标题时,默认为通用标题 Information
* @param msg
* 信息内容在资源文件中的 Key
*/
public InformationDialog(String msg) {
this(TsUIConstants.getString("dlgTitleInformation"), msg);
}
/**
* @param dialogTitle
* 对话框标题
* @param msg
* 信息内容
*/
public InformationDialog(String dialogTitle, String msg) {
super(HSBot.bot().shell(dialogTitle).widget);
this.msg = msg;
}
/**
* @param msg
* 信息内容;
*/
public void setMsg(String msg) {
this.msg = msg;
}
/**
* @return 按钮:确定;
*/
public SWTBotButton btnOK() {
return dialogBot.button(TsUIConstants.getString("btnOK"));
}
/**
* @return 文字标签:信息内容;
*/
public SWTBotLabel lblMessage() {
return dialogBot.label(msg);
}
}
| 3,018 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
InfoFileNotFound.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/test/net.heartsome.cat.ts.test.ui/src/net/heartsome/cat/ts/test/ui/msgdialogs/InfoFileNotFound.java | package net.heartsome.cat.ts.test.ui.msgdialogs;
import java.text.MessageFormat;
import net.heartsome.cat.ts.test.ui.constants.TsUIConstants;
import net.heartsome.test.swtbot.utils.HSBot;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotButton;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotLabel;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
/**
* 信息对话框:文件未找到
* @author felix_lu
* @version
* @since JDK1.6
*/
public class InfoFileNotFound extends SWTBotShell {
private SWTBot dialogBot = this.bot();
private String file;
/**
* 按标题查找对话框
* @param file 文件名
*/
public InfoFileNotFound(String file) {
super(HSBot.bot().shell(TsUIConstants.getString("dlgTitleFileNotFound")).widget);
this.file = file;
}
/**
* @return 按钮:确定;
*/
public SWTBotButton btnOK() {
return dialogBot.button(TsUIConstants.getString("btnOK"));
}
/**
* @return 文字标签:文件名非法;
*/
public SWTBotLabel msgFileNameInvalid() {
return dialogBot.label(file + TsUIConstants.getString("msgFileNameInvalid"));
}
/**
* @return 文字标签:文件未找到;
*/
public SWTBotLabel msgFileNotFound() {
String msg = TsUIConstants.getString("msgFileNotFound");
return dialogBot.label(MessageFormat.format(msg, file));
}
}
| 1,368 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ProjectTreeItem.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/test/net.heartsome.cat.ts.test.ui/src/net/heartsome/cat/ts/test/ui/views/ProjectTreeItem.java | package net.heartsome.cat.ts.test.ui.views;
import net.heartsome.test.swtbot.utils.HSBot;
import net.heartsome.test.swtbot.waits.IsEditorOpened;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEditor;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotMenu;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
/**
* 树节点:指定项目在树上的节点,单例模式
* @author felix_lu
* @version
* @since JDK1.6
*/
public final class ProjectTreeItem extends SWTBotTreeItem {
private String prjName;
private ProjectTreeView ptv = ProjectTreeView.getInstance();
private static ProjectTreeItem ptn;
/**
* @param prjName
*/
private ProjectTreeItem(String prjName) {
super(ProjectTreeView.getTree().expandNode(prjName).select().widget);
this.prjName = prjName;
}
/**
* 获得指定名称的项目所在节点
* @param prjName
* 指定的项目名称
* @return TSProjectTreeNode 项目所在的树节点
*/
public static ProjectTreeItem getInstance(String prjName) {
if (ptn == null) {
ptn = new ProjectTreeItem(prjName);
}
return ptn;
}
/**
* 选择指定项目中指定类型的文件
* @param fileType
* 指定的类型,即项目的第一级子目录,默认目录有:Source, Target, XLIFF, SKL, TMX, TBX, Other
* @param fileName
* 指定的文件名称
* @return SWTBotTreeItem 指定的文件所在的树节点
*/
public SWTBotTreeItem selectFile(String fileType, String fileName) {
return this.expandNode(fileType).select(fileName);
}
/**
* 合并打开当前项目中的所有 XLIFF
*/
public void ctxMenuOpenProjectFiles() {
ptn.select();
SWTBotMenu openProjectFiles = ptv.ctxMenuOpenProjectFiles();
openProjectFiles.isEnabled(); // 确认右键菜单中的打开项目功能可用
openProjectFiles.click(); // 点击该菜单项
// 确认文件被成功打开
SWTBotEditor editor = HSBot.bot().editorByTitle(prjName);
HSBot.bot().waitUntil(new IsEditorOpened(editor));
}
/**
* 打开当前项目中的一个 XLIFF 文件
* @param xlfFileName
* 要打开的 XLIFF 文件名称
*/
public void ctxMenuOpenFile(final String xlfFileName) {
selectFile("XLIFF", xlfFileName);
SWTBotMenu openFiles = ptv.ctxMenuOpenFile();
openFiles.isEnabled();
openFiles.click();
SWTBotEditor editor = HSBot.bot().editorByTitle(xlfFileName);
HSBot.bot().waitUntil(new IsEditorOpened(editor));
}
/**
* 转换当前项目中的一个源文件为 XLIFF
* @param srcFileName
* 要转换的源文件名称
*/
public void ctxMenuConvertFile(String srcFileName) {
selectFile("Source", srcFileName);
SWTBotMenu convertFiles = ptv.ctxMenuConvertSrcFile2Xliff();
convertFiles.isEnabled();
convertFiles.click();
// TODO:确认转换对话框正确打开
}
/**
* 转换当前项目中的一个 XLIFF 为源格式
* @param xlfFileName
* 要转换为源格式的 XLIFF 文件名称
*/
public void ctxMenuReverseConvertFile(String xlfFileName) {
selectFile("XLIFF", xlfFileName);
SWTBotMenu reverseConvertFile = ptv.ctxMenuConvertXliffFile2Tgt();
reverseConvertFile.isEnabled();
reverseConvertFile.click();
// TODO:确认转换对话框正确打开
}
}
| 3,276 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TmMatchesPanelView.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/test/net.heartsome.cat.ts.test.ui/src/net/heartsome/cat/ts/test/ui/views/TmMatchesPanelView.java | package net.heartsome.cat.ts.test.ui.views;
import net.heartsome.cat.ts.test.ui.constants.TsUIConstants;
import net.heartsome.cat.ts.test.ui.tasks.TsTasks;
import net.heartsome.test.swtbot.utils.HSBot;
import net.heartsome.test.swtbot.widgets.HsSWTBotStyledText;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotView;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotToolbarButton;
/**
* 视图:记忆库匹配面板,单例模式
* @author felix_lu
* @version
* @since JDK1.6
*/
public final class TmMatchesPanelView extends SWTBotView {
private SWTBot viewBot = bot();
private static TmMatchesPanelView view;
/**
* 按名称查找视图
*/
private TmMatchesPanelView() {
super(HSBot.bot().viewByTitle(TsUIConstants.getString("viewTitleTmMatchesPanel")).getReference(), HSBot.bot());
}
/**
* @return 记忆库匹配面板视图实例;
*/
public static TmMatchesPanelView getInstance() {
if (view == null) {
view = new TmMatchesPanelView();
}
return view;
}
/**
* @return 工具栏按钮:接受匹配;
*/
public SWTBotToolbarButton tlbBtnAcceptMatch() {
return toolbarButton(TsUIConstants.getString("tlbBtnAcceptMatch"));
}
/**
* @return 工具栏按钮:仅接受文本;
*/
public SWTBotToolbarButton tlbBtnAcceptTextOnly() {
return toolbarButton(TsUIConstants.getString("tlbBtnAcceptTextOnly"));
}
/**
* @return 工具栏按钮:在记忆库中标记匹配;
*/
public SWTBotToolbarButton tlbBtnFlagMatchInTm() {
return toolbarButton(TsUIConstants.getString("tlbBtnFlagMatchInTm"));
}
/**
* @return 工具栏按钮:显示/隐藏匹配属性;
*/
public SWTBotToolbarButton tlbBtnToggleMatchDetail() {
return toolbarButton(TsUIConstants.getString("tlbBtnToggleMatchDetail"));
}
/**
* @return StyledText:匹配源文本;
*/
public HsSWTBotStyledText matchSourceText() {
return new HsSWTBotStyledText(viewBot.styledText(0).widget);
}
/**
* @return StyledText:匹配目标文本;
*/
public HsSWTBotStyledText matchTargetText() {
return new HsSWTBotStyledText(viewBot.styledText(1).widget);
}
/**
* @return 文本:匹配的修改日期值;
*/
public String matchDetailModifyDate() {
return getMatchDetail(TsUIConstants.getString("matchDetailModifyDate"));
}
/**
* @return 文本:匹配的来源值;
*/
public String matchDetailOriginTM() {
return getMatchDetail(TsUIConstants.getString("matchDetailOriginTM"));
}
/**
* @return 文本:匹配的修改人值;
*/
public String matchDetailJobOwner() {
return getMatchDetail(TsUIConstants.getString("matchDetailJobOwner"));
}
/**
* @return 文本:匹配的作业相关信息值;
*/
public String matchDetailJobInfo() {
return getMatchDetail(TsUIConstants.getString("matchDetailJobInfo"));
}
/**
* @param key
* @return 文本:匹配信息中指定 key 对应的值;
*/
public String getMatchDetail(String key) {
String text = viewBot.label().getText();
String groupSign = TsUIConstants.getString("matchDetailGroupSign");
String delimiter = TsUIConstants.getString("matchDetailDelimiter");
return TsTasks.getStatusValueByKey(text, groupSign, delimiter, key);
}
}
| 3,233 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DocumentPropertiesView.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/test/net.heartsome.cat.ts.test.ui/src/net/heartsome/cat/ts/test/ui/views/DocumentPropertiesView.java | package net.heartsome.cat.ts.test.ui.views;
import net.heartsome.cat.ts.test.ui.constants.TsUIConstants;
import net.heartsome.test.swtbot.utils.HSBot;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotView;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotButton;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotCombo;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTable;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTableColumn;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotText;
/**
* 视图:文档属性,单例模式
* @author felix_lu
* @version
* @since JDK1.6
*/
public final class DocumentPropertiesView extends SWTBotView {
private SWTBot viewBot = this.bot();
private static SWTBotView view;
/**
* 按标题查找视图
*/
private DocumentPropertiesView() {
super(HSBot.bot().viewByTitle(TsUIConstants.getString("viewTitleDocumentProperties")).getReference(), HSBot
.bot());
}
/**
* @return 文档属性视图实例;
*/
public static SWTBotView getInstance() {
if (view == null) {
view = new DocumentPropertiesView();
}
return view;
}
/**
* @return 按钮:接受;
*/
public SWTBotButton btnAccept() {
return viewBot.button(TsUIConstants.getString("btnAccept"));
}
/**
* @return 按钮:添加;
*/
public SWTBotButton btnAdd() {
return viewBot.button(TsUIConstants.getString("btnAdd"));
}
/**
* @return 按钮:取消;
*/
public SWTBotButton btnCancel() {
return viewBot.button(TsUIConstants.getString("btnCancel"));
}
/**
* @return 按钮:删除;
*/
public SWTBotButton btnDelete() {
return viewBot.button(TsUIConstants.getString("btnDelete"));
}
/**
* @return 按钮:编辑;
*/
public SWTBotButton btnEdit() {
return viewBot.button(TsUIConstants.getString("btnEdit"));
}
/**
* @return 下拉列表:文件;
*/
public SWTBotCombo cmbWLblFile() {
return viewBot.comboBoxWithLabel(TsUIConstants.getString("cmbWLblFile"));
}
/**
* @return 表格:文件属性;
*/
public SWTBotTable tblProperties() {
return viewBot.table();
}
/**
* @return 表格列:属性名称;
*/
public SWTBotTableColumn tblColProperty() {
return tblProperties().header(TsUIConstants.getString("tblColProperty"));
}
/**
* @return 表格列:属性值;
*/
public SWTBotTableColumn tblColValue() {
return tblProperties().header(TsUIConstants.getString("tblColValue"));
}
/**
* @return 文本框:客户;
*/
public SWTBotText txtWLblClient() {
return viewBot.textWithLabel(TsUIConstants.getString("txtWLblClient"));
}
/**
* @return 文本框:作业日期;
*/
public SWTBotText txtWLblJobDate() {
return viewBot.textWithLabel(TsUIConstants.getString("txtWLblJobDate"));
}
/**
* @return 文本框:作业相关信息;
*/
public SWTBotText txtWLblJobInfo() {
return viewBot.textWithLabel(TsUIConstants.getString("txtWLblJobInfo"));
}
/**
* @return 文本框:负责人;
*/
public SWTBotText txtWLblOwner() {
return viewBot.textWithLabel(TsUIConstants.getString("txtWLblOwner"));
}
/**
* @return 文本框:项目相关信息;
*/
public SWTBotText txtWlblProjectInfo() {
return viewBot.textWithLabel(TsUIConstants.getString("txtWlblProjectInfo"));
}
/**
* @return 文本框:骨架文件;
*/
public SWTBotText txtWLblSkeleton() {
return viewBot.textWithLabel(TsUIConstants.getString("txtWLblSkeleton"));
}
/**
* @return 文本框:原始数据类型;
*/
public SWTBotText txtWLblSourceDataType() {
return viewBot.textWithLabel(TsUIConstants.getString("txtWLblSourceDataType"));
}
/**
* @return 文本框:源文件编码;
*/
public SWTBotText txtWLblSourceEncoding() {
return viewBot.textWithLabel(TsUIConstants.getString("txtWLblSourceEncoding"));
}
/**
* @return 文本框:源语言;
*/
public SWTBotText txtWLblSourceLanguage() {
return viewBot.textWithLabel(TsUIConstants.getString("txtWLblSourceLanguage"));
}
/**
* @return 文本框:目标语言;
*/
public SWTBotText txtWLblTargetLanguage() {
return viewBot.textWithLabel(TsUIConstants.getString("txtWLblTargetLanguage"));
}
}
| 4,189 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.